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、测试
4、脚本内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
#==================================================== # 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 "\<$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格式,则重新输入
#^$:从开始到结束是数字才满足条件,=~:一个操作符,表示左边是否满足右边(作为一个模式)正则表达式
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_pass=${Password}" >> $User_File
#如果上面输入都满足条件,将输入的信息追加到用户信息文件中,并打印追加内容 echo "------------------------"
tail -n 1 $User_File
|