#!/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
脚本主要由3个
expect组成,比较简单,用法是
./ssh_trust.sh host1 user1 passwd1 host2 user2 passwd2
即建立从user1@host1到user2@host2的ssh信任。
说明:
1、当然得安装
expect
2、脚本放在第三方机器(能远程登录host1和host2)上运行即可,当然放在host1和host2上运行也行。
3、如果想批量建立信任,可以编辑一个文件夹file如:
host1 user1 passwd1 host2 user2 passwd2
host3 user3 passwd3 host4 user4 passwd4
host5 user5 passwd5 host6 user6 passwd6
使用下面命令执行脚本即可:
xargs -n6 ./ssh_trust.sh < file4、仓促写的,脚本只是简单实现功能,使用前确保参数的可用性(用户密码主机名),不然很容易报错