1、生成ssh-key脚本
[root@controller1 ~]# cat ssh-keygen.exp
#!/bin/expect
set timeout 30
spawn ssh-keygen
expect {
"Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r"; exp_continue}
"Enter passphrase (empty for no passphrase):" { send "\r"; exp_continue}
"Enter same passphrase again:" { send "\r"; exp_continue}
}
interact
#给脚本授权
chmod a+x ssh-keygen.exp
#运行脚本
[root@controller1 ~]# ./ssh-keygen.exp
spawn ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:KQ82vKOBbx/JAi+HNqkwV3/k7mmaoX5BaL/BeGzK3Tc root@controller1
The key's randomart image is:
+---[RSA 2048]----+
| |
| |
| . |
| o.. . |
| ...** S |
| B.+OX |
|o O.==O=+ |
|.= =+=+Bo.E |
|. o=o+++. . |
+----[SHA256]-----+
spawn_id: spawn id exp4 not open
while executing
"interact"
(file "./ssh-keygen.exp" line 9)
2、分发公钥给其它服务器脚本
[root@controller1 ~]# cat ssh-copy-controller2.exp
#!/bin/expect
set timeout 30
spawn ssh-copy-id root@controller2
expect {
"yes/no" { send "yes\r" ; exp_continue}
"password" { send "hotdoor\r"; exp_continue}
}
interact
#给脚本授权
chmod a+x ssh-keygen.exp
#运行脚本
[root@controller1 ~]# ./ssh-copy-controller2.exp
spawn ssh-copy-id root@controller2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'controller2 (10.10.0.22)' can't be established.
ECDSA key fingerprint is SHA256:E7LEFgQL2FAe3g9D6iA/Xahy/ny8VSDy/EmDliwJ9c4.
ECDSA key fingerprint is MD5:d5:77:5d:0e:f4:38:0d:b2:d2:74:82:28:17:50:62:ac.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@controller2's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@controller2'"
and check to make sure that only the key(s) you wanted were added.
spawn_id: spawn id exp4 not open
while executing
"interact"
(file "./ssh-copy-controller2.exp" line 8)
3、测试不需要Key分发文件
[root@controller1 ~]# scp text.txt root@controller2:/root
text.txt 100% 4 5.3KB/s 00:00
4、更多用法参考:
https://www.cnblogs.com/kevingrace/p/5900303.html