背景
为了使一台主机能够对多台主机进行免密登录操作,同时又不需要在脚本执行期间进行交互性的输入。我编写下面的脚本,这里主要使用到expect命令。
脚本
配置文件
配置文件,文件名为hostname,用以存储从本机(假设ip为10.191.10.1)需要免密登录的主机的ip
10.191.10.2
#10.191.10.3
10.191.10.4
10.191.10.5
脚本
#!/bin/bash
# 该脚本用于实现配置root免密登录到其他主机的功能
#
# @Author TomatoChao
###################################################################
filepath=~/.ssh/id_rsa.pub
user=root
password=admin@123
auto_ssh_copy_id() {
expect -c "set timeout -1;
spawn ssh-copy-id -i $4 $2@$1;
expect {
*(yes/no)* {send -- yes\r;exp_continue;}
*password:* {send -- $3\r;exp_continue;}
eof { exit 0;}
}";
}
# 判断本地的公钥是否存在,如果不存在则需要生成公钥
[ ! -f $filepath ] && {
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
}
hosts=`cat hostname | grep -v "^#"`
# 对配置文件中的每一台主机进行免密登录操作
for serverIp in $hosts
do
# echo $serverIp--$user--$password
# 将公钥发送给需要免密登录的主机
auto_ssh_copy_id $serverIp $user $password $filepath
done