rule 发表于 2018-8-24 09:44:25

Shell判断输入是否有效IP和字母

#====================================================  
# Author: lizhenliang - EMail:zhenliang369@163.com
  
# Last modified: 2015-02-1
  
# Filename: input_hostinfo.sh
  
# Description:
  
# blog:lizhenliang.blog.51cto.com
  
#====================================================
  
User_File=/etc/ansible/hosts
  
Check_IP()
  
{
  
while true
  
do
  
    read -p "Please input IP address: " ip
  
    IP_Count=`cat user_info |grep "\" |wc -l`   #统计用户信息文件中是否包含输入的IP,如果已存在则重新输入
  
    if [ -z $ip ];then      #输入不能为空
  
      echo "Enter not null."
  
    elif [ $ip == exit -o $ip == quit -o $ip == q ];then      #如果输入exit、quit、q就退出输入模式
  
      exit 1;
  
    elif [$IP_Count -eq 1 ];then
  
      echo "IP $ip is already! Please enter the IP agagin."
  
    elif [[ $ip =~ ^{1,3}\.{1,3}\.{1,3}\.{1,3}$ ]];then   #输入的不是数字或不是IP格式,则重新输入
  
      #^$:从开始到结束是数字才满足条件,=~:一个操作符,表示左边是否满足右边(作为一个模式)正则表达式
  
      a=`echo $ip |cut -d. -f1`
  
      b=`echo $ip |cut -d. -f2`
  
      c=`echo $ip |cut -d. -f3`
  
      d=`echo $ip |cut -d. -f4`
  
      if [ $a -le 255 -a $b -le 255 -a $c -le 255 -a $d -le 255 ];then
  
      #当满足输入条件时,截取IP四段数字进行整数比较,判断四段数字是否小于或等于255,同时满足条件,跳出所有循环继续,如果其中一个不满足,则重新输入
  
            break;
  
      else
  
            echo "IP format error,Please enter the IP again."
  
      fi
  
    else
  
      echo "IP format error,Please enter the IP again."
  
    fi
  
done
  
}
  
########################################################
  
Check_User()
  
{
  
while true
  
do
  
    read -p "Please input username: " username
  
    if [ -z $username ];then      #输入不能为空
  
      echo "Enter not null."
  
    elif [[ ! $username =~ ^+$ ]];then      #输入的不是字母,则重新输入
  
      echo "Enter the username must is letter."
  
    else
  
      break;      #当满足输入条件时,跳出所有循环
  
    fi
  
done
  
}
  
########################################################
  
Password()
  
{
  
    read -p "Please input pass: " Password
  
}
  
########################################################
  
Check_IP;
  
Check_User;
  
Password;
  
echo "$ip   ansible_ssh_user=${username}    ansible_ssh_pass=${Password}" >> $User_File
  
#如果上面输入都满足条件,将输入的信息追加到用户信息文件中,并打印追加内容
  
echo "------------------------"
  
tail -n 1 $User_File


页: [1]
查看完整版本: Shell判断输入是否有效IP和字母