expect的安裝與使用
是什么
expect 是用來進行自動化控制和測試的工具。主要是和交互式軟件telnet ftp ssh 等進行自動化的交互。
如何安裝
1.檢測是否安裝
ls /usr/bin |grep expect
如果不存在,則進行安裝
2.安裝
sudo apt-get install expect
$ ls /usr/bin |grep expect
autoexpect
expect
expect_autoexpect
expect_autopasswd
expect_cryptdir
expect_decryptdir
expect_dislocate
expect_ftp-rfc
expect_kibitz
expect_lpunlock
expect_mkpasswd
expect_multixterm
expect_passmass
expect_rftp
expect_rlogin-cwd
expect_timed-read
expect_timed-run
expect_tknewsbiff
expect_tkpasswd
expect_unbuffer
expect_weather
expect_xkibitz
expect_xpstat
具體使用
案例一,進入ssh腳本
spawn是進入expect環境后才可以執行的expect內部命令。expect是一種腳本語言,它能夠代替我們實現與終端的交互,我們不必再守候在電腦旁邊輸入密碼,或是根據系統的輸出再運行相應的命令。
1.創建腳本
#! /usr/bin/expect
# 設置超時時間
set timeout 3
# fork一個子進程執行ssh
spawn ssh root@xxx.xxx.xxx.xxx
# 捕獲到密碼
expect "*password*"
# 輸入密碼並回車
send "xxxxxx\r"
# 捕獲#
expect "*#"
# 進入常用目錄下
send "cd /home/wwwroot/default\r"
# 允許用戶進行交互
interact
2.創建權限
sudo chmod +x xxx.sh
3.執行腳本
./xxx.sh
jiqing@Ubuntu:~/sh$ ./xxx.sh
spawn ssh root@xxx
root@xxx's password:
Last login: Thu Jun 21 15:07:03 2018 from 218.93.209.10
Welcome to Alibaba Cloud Elastic Compute Service !
[root@iZuf6ingetk3pr7xgv1vq1Z ~]# cd /home/wwwroot/default
[root@iZuf6ingetk3pr7xgv1vq1Z default]#
優化通用版本,支持第一次yes判斷,支持ip輸入
#! /usr/bin/expect
set ip [lindex $argv 0]
set password [lindex $argv 1]
if {$ip == ""} {
puts "請輸入ip"
exit
}
if {$password == ""} {
set password "123456"
}
# 設置超時時間
set timeout 3
# fork一個子進程執行ssh
spawn ssh root@$ip
expect {
"*yes/no*" { send "yes\r"; exp_continue}
"*password*" { send "$password\r" }
}
# 捕獲到密碼
# expect "*password*"
# 輸入密碼並回車
# send "$password\r"
# 捕獲#
expect "*#"
# 進入常用目錄下
send "cd /home/wwwroot/default\r"
# 允許用戶進行交互
interact
繼續升級成昵稱,比ip更好用
#! /usr/bin/expect
set pro_name [lindex $argv 0]
set password [lindex $argv 1]
if {$pro_name == ""} {
puts "請輸入名稱"
exit
}
switch $pro_name {
"meiren" -
"yanglu" -
"wenbo" {
set ip "ip1"
}
"siemens" {
set ip "ip2"
}
"tqmp" {
set ip "ip3"
}
default {
puts "請輸入正確的名稱"
exit
}
}
if {$password == ""} {
set password "xxx"
}
# 設置超時時間
set timeout 3
# fork一個子進程執行ssh
spawn ssh root@$ip
expect {
"*yes/no*" { send "yes\r"; exp_continue}
"*password:*" { send "$password\r" }
}
# 捕獲到密碼
# expect "*password*"
# 輸入密碼並回車
# send "$password\r"
# 捕獲#
expect "*#"
# 進入常用目錄下
send "cd /home/wwwroot/default\r"
# 允許用戶進行交互
interact
666 ,一個腳本,一鍵鏈接ssh。
案例二,進行cd操作
#! /usr/bin/expect
# 跳轉到項目目錄下
set pro_name [lindex $argv 0]
spawn bash
if {$pro_name != ""} {
set target_dir "/home/wwwroot/default/$pro_name"
} else {
set target_dir "/home/wwwroot/default"
}
# 判斷目錄是否存在
if {![file isdirectory $target_dir]} {
puts "項目目錄不存在"
set target_dir "/home/wwwroot/default"
}
send "cd $target_dir\r"
interact
ps:expect的語法與shell腳本有點不同,多用用就習慣了。運用起來,讓他們幫助你更好的工作。
更多功能,需要在工作中去探索和使用。我愛linux。