?語法
expect [選項] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ] 選項 -c:從命令行執行expect腳本,默認expect是交互地執行的 示例:expect -c 'expect "\n" {send "pressed enter\n"}' -d:輸出調試信息 示例:expect -d ssh.expexpect中的相關命令 spawn:啟動新的進程 send:向進程發送字符串 expect:從進程接收字符串 interact:允許用戶交互exp_continue 匹配多個字符串時在執行動作后加此命令 expect最常用的語法(tcl語言:模式-動作) 單一分支模式的語法: expect "hi" { send "You said hi\n" } 匹配到 hi 后,會輸出"you said hi",并換行多分支模式的語法: expect "hi" { send "You said hi\n" } \ "hehe" { send “Hehe yourself\n" } \ "bye" { send "Goodbye\n" } 匹配 hi, hehe, bye 中的任意字符串時, 發送相應字符串。等同于:expect { "hi" { send "You said hi\n" } "hehe" { send "Hehe yourself\n" } "bye" { send "Goodbye\n" } }
樣例
準備測試環境
如圖顯示,一個txt文件,源主機192.168.146.129拷貝至目的主機192.168.146.128,會提示輸入密碼
安裝expect
源主機安裝即可
yum -y install expect
安裝好的expect的命令在?/usr/bin目錄下
編寫測試代碼
[root@master opt]# vim copyfile.sh #!/bin/bashsource_file_name="1.txt"
dst_host_name="192.168.146.128"RED='\E[1;31m'
GREEN='\E[1;32m'
YELOW='\E[1;33m'
SHAN='\E[1;31;5m'
RES='\E[0m'# 使用expect -c '...'的方式直接在腳本中嵌入了Expect的代碼塊
expect -c '# set 方式設置所需要用到的環境變量set source_file "/opt/1.txt"set dst_host "192.168.146.128"set dst_dir "/opt/"set dst_user "root"set dst_password "123456"# spawn啟動某個命令的子進程spawn scp -r $source_file $dst_user@$dst_host:$dst_dir# except的匹配,匹配到yes 就用send輸入yes然后繼續,匹配到password字樣,就send密碼expect {"(yes/no)?" {send "yes\n"exp_continue}"password" {send "$dst_password\n"}}# 等待命令結束expect eof# 輸出一個提示語puts "File transfer successful!"# 允許用戶交互spawn的子進程命令interact'if [[ $? -eq 0 ]];thenecho -e "${GREEN}[+]File: $source_file_name copy to $dst_host_name completed!${RES}"
elseecho -e "${RED}[-]File: $source_file_name copy to $dst_host_name failed!${RES}"
fi
exit 0
執行
全程無交互,文件拷貝成功
目標主機查看?
目標主機192.168.146.128上已有了1.txt文件。