- 1. 编写expect脚本实现自动输入密码
- define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password “123456” - 1.product key pair
echo -e “\n”|ssh-keygen -t dsa -N “” >/dev/null 2>&1
if [ $? -eq 0 ];then
action “create dsa $ip” /bin/true
else
action “create dsa $ip” /bin/false
exit 1
fi - 2.dis pub key
n=cat iplis.txt
for ip in $n
do
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub $ip >/dev/null 2>&1
if [ $? -eq 0 ];then
action “$ip” /bin/true
else
action “$ip” /bin/false
fi
done
密钥分发我们要在gongli用户下执行,所以下面的步骤需要切换到gongli用户下,同样是在管理机
(m01)上进行操作。
切换到gongli用户下: su - gongli
1. 编写expect脚本实现自动输入密码
文件名:fenfa_sshkey.exp
#!/usr/bin/expect
if { $argc != 2 } {
send_user “usage: expect fenfa_sshkey.exp file host\n”
exit
}
define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password “123456”
spawn ssh-copy-id -i $file “-p 65533 gongli@$host”
expect {
“yes/no” {send “yes\r”;exp_continue}
“*password” {send “$password\r”}
}
expect eof
exit -noexit {
send_user “king say good bye to your!\n”
}
2. 编写shell脚本实现密钥自动创建和分发
文件名:auto_dis_sshkey.sh
#!/bin/sh
. /etc/init.d/functions
1.product key pair
echo -e “\n”|ssh-keygen -t dsa -N “” >/dev/null 2>&1
if [ $? -eq 0 ];then
action “create dsa $ip” /bin/true
else
action “create dsa $ip” /bin/false
exit 1
fi
2.dis pub key
n=cat iplis.txt
for ip in $n
do
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub $ip >/dev/null 2>&1
if [ $? -eq 0 ];then
action “$ip” /bin/true
else
action “$ip” /bin/false
fi
done
3. 服务器列表
文件名:iplis.txt
172.16.1.8
172.16.1.31
172.16.1.41
4. 开始批量分发ssh key密钥
命令:
sh auto_dis_sshkey.sh
可以看到全部都OK。
5. 结果测试
写个小脚本,批量获取远程服务器的系统版本信息。
文件名:get_version.sh
#!/bin/sh
n=cat iplis.txt
for ip in $n
do
echo ==========$ip============
ssh “-p 65533” gongli@$ip cat /etc/redhat-release
done
执行结果:
全部大功告成!
总结:
要想批量管理服务器,对服务器的配置要求需要统一,比如 统一用户名和密码、服务器端口、权限、
等等,能不用root登录服务器尽量不要使用root的。如何解决需要root身份才能执行的操作?
解决方法1:sudo 提权
解决方法2:普通用户登录服务器后 su – 切换到root用户身份。
方法2里面存在一定的安全风险,尽量选择方法1。