最近想寫一個自動化安裝腳本,涉及到遠程登陸、分發文件包、遠程執行命令等,其中少不了來回輸入登陸密碼,交互式輸入命令等,這樣就大大下降了效率,那麼有什麼方法能解決呢?不妨試試expect:linux
遠程登陸linux服務器的時候,ssh命令須要手工輸入密碼,當登陸多臺機器的時候就會很是繁瑣。nginx
通常機器不會自帶expect和tcl須要手動安裝。vim
[root@bqh-nfs-123 ~]# yum install expect tcl -y [root@bqh-nfs-123 ~]# rpm -qa expect tcl expect-5.44.1.15-5.el6_4.x86_64 tcl-8.5.7-6.el6.x86_64
expect腳本通常以#!/usr/bin/expect -f開頭,相似bash腳本。bash
expect腳本經常以.exp或者.ex結束。服務器
expect命令採用了tcl的模式-動做語法,此語法有如下幾種模式:app
set password 123456 expect "*assword:" { send "$password\r" }
當輸出中匹配*assword:時,輸出password變量的數值和回車。ssh
set password 123456 expect { "(yes/no)?" { send "yes\r"; exp_continue } "*assword:" { send "$password\r" } }
當輸出中包含(yes/no)?時,輸出yes和回車,同時從新執行此多分支語句。工具
當輸出中匹配*assword:時,輸出password變量的數值和回車。spa
[root@bqh-nfs-123 scripts]# vim test.exp #!/usr/bin/expect -f #expect的路徑,which expect查詢獲取 set timeout 20 #鏈接超時 set host "192.168.0.124" set password "123456" spawn ssh root@$host #登陸服務器用戶+地址 expect { #等待接受進程返回的字符串 "yes/no" {send "yes\n";exp_continue} #等待輸入yes "password:" {send "$password\n"} #等待輸入密碼 } interact #將腳本的控制權交給用戶,用戶可繼續輸入命令
執行結果以下:3d
[root@bqh-nfs-123 scripts]# vim test.exp #!/usr/bin/expect -f set timeout 20 set host "192.168.0.124" set password "123456" spawn ssh root@$host expect { "yes/no" {send "yes\n";exp_continue} "password:" {send "$password\n"} } expect "]*" send "/application/nginx/sbin/nginx\n" expect "]*" send "lsof -i:80\n" expect "]*" send "echo 1147076062 >1.log\n" expect "]*" send "cat 1.log\n" expect "]*" send "exit\n"
執行結果以下:
[root@bqh-nfs-123 scripts]# cat test1.exp #!/usr/bin/expect set user [lindex $argv 0] set host [lindex $argv 1] set passwd "123456" set cmd [lindex $argv 2] spawn ssh $user@$host expect { "yes/no" { send "yes\n"} "password:" { send "$passwd\n" } } expect "]*" send "$cmd\n" expect "]*" send "exit\n"
執行結果以下: