標籤:shell判斷輸入是否有效ip shell判斷輸入是否為字母
1、需求目的
最近在研究ansible自動化工具,在主機表(/etc/ansible/hosts)添加管理節點資訊時,幾台到十幾台還可以手動添加,到了百十台工作量就大了。於是想用指令碼自動添加,減少工作量,剛開始想到for迴圈自動添加,但添加的IP、使用者、密碼,都不相同,實現起來比較困難,也沒太多時間去研究,結果就用了手動互動輸入。
使用者資訊表如下格式:
# cat /etc/ansible/hosts
192.168.1.100 ansible_ssh_user=user ansible_ssh_pass=123
2、實現思路
2.1 先輸入IP,並判斷輸入的是否有效IP地址和輸入的IP是否已經存在
2.2 判斷輸入使用者名稱是否為字母
2.3 密碼就不多說,如上述都滿足條件,則通過變數引用將節點資訊追加到主機表中,並列印輸入內容
3、測試
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/59/40/wKioL1TNiiOCwn4QAALd2jSUE0s070.jpg" title="QQ圖片20150201100145.png" alt="wKioL1TNiiOCwn4QAALd2jSUE0s070.jpg" />
4、指令碼內容如下
#====================================================
# Author: lizhenliang - EMail:[email protected]
# 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 "\<$ip\>" |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-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[1-9]{1,3}$ ]];then #輸入的不是數字或不是IP格式,則重新輸入
#^$:從開始到結束是數字才滿足條件,=~:一個操作符,表示左邊是否滿足右邊(作為一個模式)Regex
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 =~ ^[a-z]+$ ]];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_user=${Password}" >> $User_File
#如果上面輸入都滿足條件,將輸入的資訊追加到使用者資訊檔中,並列印追加內容
echo "------------------------"
tail -n 1 $User_File
本文出自 ““企鵝”那點事兒” 部落格,請務必保留此出處http://lizhenliang.blog.51cto.com/7876557/1610406
Shell判斷輸入是否有效IP和字母