有时需要在两台或多台linux服务器间建立ssh连接,则可以采用下面的脚本实现多台服务器间建立SSH信任:
创建一个脚本文件:ssh_trust.sh 内容如下:
#!/bin/bash
src_host=$1
src_username=$2
src_passwd=$3
dst_host=$4
dst_username=$5
dst_passwd=$6
#在远程主机1上生成公私钥对
Keygen()
{
expect << EOF
spawn ssh $src_username@$src_host ssh-keygen -t rsa
while 1 {
expect {
"password:" {
send "$src_passwd\n"
}
"yes/no*" {
send "yes\n"
}
"Enter file in which to save the key*" {
send "\n"
}
"Enter passphrase*" {
send "\n"
}
"Enter same passphrase again:" {
send "\n"
}
"Overwrite (y/n)" {
send "n\n"
}
eof {
exit
}
}
}
EOF
}
#从远程主机1获取公钥保存到本地
Get_pub()
{
expect << EOF
spawn scp $src_username@$src_host:~/.ssh/id_rsa.pub /tmp
expect {
"password:" {
send "$src_passwd\n";exp_continue
}
"yes/no*" {
send "yes\n";exp_continue
}
eof {
exit
}
}
EOF
}
#将公钥的内容附加到远程主机2的authorized_keys
Put_pub()
{
src_pub="$(cat /tmp/id_rsa.pub)"
expect << EOF
spawn ssh $dst_username@$dst_host "chmod 700 ~/.ssh;echo $src_pub >> ~/.ssh/authorized_keys;chmod 600 ~/.ssh/authorized_ke
ys"
expect {
"password:" {
send "$dst_passwd\n";exp_continue
}
"yes/no*" {
send "yes\n";exp_continue
}
eof {
exit
}
}
EOF
}
Keygen
Get_pub
Put_pub
直接运行以上脚本时,可能会提示脚本的错误,则很可能是拷贝文件过程中进行了字符的转换,则可以尝试以下命令:
[root@zjxl-100 wxr]# dos2unix ssh_trust.sh