转自:www.chinaunix.net。作者:老表
在工作中经常遇到给两台主机建立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_passwdn"
- }
- "yes/no*" {
- send "yesn"
- }
- "Enter file in which to save the key*" {
- send "n"
- }
- "Enter passphrase*" {
- send "n"
- }
- "Enter same passphrase again:" {
- send "n"
- }
- "Overwrite (y/n)" {
- send "nn"
- }
- eof {
- exit
- }
- }
- }
- EOF
- }
- #从远程主机1获取公钥保存到本地
- Get_pub()
- {
- expect << EOF
- spawn scp $src_username@$src_host:~/.ssh/id_rsa.pub /tmp
- expect {
- "password:" {
- send "$src_passwdn";exp_continue
- }
- "yes/no*" {
- send "yesn";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_passwdn";exp_continue
- }
- "yes/no*" {
- send "yesn";exp_continue
- }
- eof {
- exit
- }
- }
- EOF
- }
- Keygen
- Get_pub
- Put_pub
- ./ssh_trust.sh host1 user1 passwd1 host2 user2 passwd2
说明:
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 < file
5、只在linuxredhat上测试过,运行成功,欢迎大家提意见~~