1. 程式人生 > >Linux之expect非交互式功能

Linux之expect非交互式功能

class ack scrip then eof inet6 queue cast with

我在上一篇博文linux之SSH密鑰認證 提過ssh之間的相互認證,但是每次使用ssh登錄到其它服務器還是要輸入密碼的。

expect是用於提供自動交互的工具,自動連接被管理的服務器,不需要手動輸入密碼。

1、安裝expect

[root@mg ~]# yum install -y expect

2、編寫expect腳本,直接分發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 }

3、測試

/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) cant 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.72s password: 
 8 Now try logging into the machine, with "ssh ‘-p 22 [email protected]", and check in:
 9 
10   .ssh/authorized_keys
11 
12 to make sure we havent added extra keys that you werent 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免密碼操作成功。

Linux之expect非交互式功能