我在上一篇博文linux之SSH密鑰認證 提過ssh之間的相互認證,可是每次使用ssh登陸到其它服務器仍是要輸入密碼的。linux
expect是用於提供自動交互的工具,自動鏈接被管理的服務器,不須要手動輸入密碼。vim
一、安裝expect服務器
[root@mg ~]# yum install -y expect
二、編寫expect腳本,直接分發SSH公鑰,不用手工輸入密碼。ssh
vim /server/scripts/expect.exp工具
1 #!/usr/bin/expect 2 3 #-------------CopyRight------------- 4 # Name:ssh send password 5 # Version Number:1.00 6 # Type:sh 7 # Language:expect 8 # Date:2018-05-24 9 # Author:sandy 10 # QQ:442656067 11 # Email:eeexu123@163.com 12 # Blog:https://www.cnblogs.com/eeexu123/ 13 14 if { $argc != 2 } { 15 send_user "usage: expect fenfa_expect file host\n" //判斷傳入參數是不是2個 16 exit 1 17 } 18 19 #define var 20 set file [lindex $argv 0] //第一個參數是ssh公鑰 21 set host [lindex $argv 1] //第二個參數是鏈接的遠程主機地址 22 set passwd "herine" //設置鏈接用戶的密碼 23 24 25 #send ssh key 26 spawn ssh-copy-id -i $file "-p 22 root@$host" //發送ssh公鑰命令 27 expect { 28 "yes/no" {send "yes\r";exp_continue} //是否繼續鏈接,expect交互式功能,自動添加yes,並繼續。yes後成必須加\r回車符30 } 31 32 sleep 3 //等待鏈接到遠程主機 33 expect "*password" //輸入密碼,expect交互功能,自動添加密碼變量。後面加\r回車符 34 send "$passwd\r" 35 expect eof 36 37 exit -onexit { 38 send_user "Goodbye!\n" //退出 39 }
三、測試測試
/usr/bin/expect test_expect.exp ~/.ssh/id_dsa.pub 172.16.1.72
上面一條命令能夠放在腳本里,大批量創建ssh密鑰鏈接
1 [root@mg scripts]# /usr/bin/expect test_expect.exp ~/.ssh/id_dsa.pub 172.16.1.72 2 spawn ssh-copy-id -i /root/.ssh/id_dsa.pub -p 22 root@172.16.1.72 3 The authenticity of host '172.16.1.72 (172.16.1.72)' can't be established. 4 RSA key fingerprint is a5:17:d4:89:36:79:58:aa:99:8d:f0:ce:98:5a:d3:f4. 5 Are you sure you want to continue connecting (yes/no)? yes 6 Warning: Permanently added '172.16.1.72' (RSA) to the list of known hosts. 7 root@172.16.1.72's password: 8 Now try logging into the machine, with "ssh '-p 22 root@172.16.1.72'", and check in: 9 10 .ssh/authorized_keys 11 12 to make sure we haven't added extra keys that you weren't expecting. 13 14 Goodbye!
ssh遠程使用命令加密
1 [root@mg scripts]# ssh root@172.16.1.72 "/sbin/ifconfig eth1" 2 eth1 Link encap:Ethernet HWaddr 00:0C:29:8D:65:92 3 inet addr:172.16.1.72 Bcast:172.16.1.255 Mask:255.255.255.0 4 inet6 addr: fe80::20c:29ff:fe8d:6592/64 Scope:Link 5 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 6 RX packets:560 errors:0 dropped:0 overruns:0 frame:0 7 TX packets:218 errors:0 dropped:0 overruns:0 carrier:0 8 collisions:0 txqueuelen:1000 9 RX bytes:72275 (70.5 KiB) TX bytes:39742 (38.8 KiB)
由上能夠,expect交互功能在SSH免密碼操做成功。spa