Linux记录-批量安装ssh(转载)
首先,需要检查expect是否安装:rpm -qa|grep expect
然后,在操作机上创建公钥:ssh-keygen 一路回车即可
创建好之后到/root/.ssh/下就可以看到id开头的2个文件,其中id_rsa.pub就是公钥文件,需要做的就是将这个文件传送给其他机器:ssh-copy-id -i /root/.ssh/id_rsa.pub root@ip
最后ssh root@ip就实现无密码登录了。
#!/bin/bash
#2013-04-08
#author myhoop
#blog http://myhoop.blog.51cto.com
#批量ssh认证建立
for p in $(cat /usr2/script/ip.txt) #注意ip.txt文件的绝对路径
do
ip=$(echo "$p"|cut -f1 -d":") #取ip.txt文件中的ip地址
password=$(echo "$p"|cut -f2 -d":") #取ip.txt文件中的密码
#expect自动交互开始
expect -c "
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip
expect {
\"*yes/no*\" {send \"yes\r\"; exp_continue}
\"*password*\" {send \"$password\r\"; exp_continue}
\"*Password*\" {send \"$password\r\";}
}
"
done
#通过ssh批量执行命令
for h in $(cat /usr2/script/ip.txt|cut -f1 -d":")
do
ssh root@$h '此处写要执行的命令'
#如果命令是多行的,请参照下面
#ssh root@$h '此处写要执行的命令1'
#ssh root@$h '此处写要执行的命令2'
#ssh root@$h '此处写要执行的命令3'
done
#ip.txt文件里面ip和密码写法
192.168.0.2:admin2
192.168.0.3:admin3

浙公网安备 33010602011771号