2021-05-12 14:32:11
Linux 指令碼之 expect命令使用
1 概述
expect 是由Don Libes基於Tcl(Tool Command Language )語言開發的,主要應用於自動化互動式操作的場景,藉助Expect處理互動的命令,可以將互動過程如:ssh登入,ftp登入等寫在一個指令碼上,使之自動化完成。尤其適用於需要對多台伺服器執行相同操作的環境中,可以大大提高系統管理人員的工作效率
2 語法
expect命令
expect 語法:
expect [選項] [ -c cmds] [ [ -[f|b] ] cmdfile] [ args]
選項
-c:從命令列執行expect指令碼,預設expect是互動地執行的
範例:expect -c 'expect "n" {send "pressed entern"}
-d:可以輸出輸出偵錯資訊
範例:expect -d ssh.exp
expect中相關命令
spawn:啟動新的進程
send:用於向進程傳送字串
expect:從進程接收字串
interact:允許使用者互動
exp_continue匹配多個字串在執行動作後加此命令
expect最常用的語法(tcl語言:模式-動作)
單一分支模式語法:
expect “hi” {send “You said hin"}
匹配到hi後,會輸出“you said hi”,並換行
多分支模式語法:
expect "hi" { send "You said hin" }
"hehe" { send “Hehe yourselfn" }
"bye" { send “Good byen" }
匹配hi,hello,bye任意字串時,執行相應輸出。等同如下:
expect {
"hi" { send "You said hin"}
"hehe" { send "Hehe yourselfn"}
"bye" { send “Good byen"}
}
3 指令碼
以下是在expect在shell指令碼中呼叫常用的幾個用法,自動拷貝指令碼,下發指令碼,ssh 和telnet 連線遠端主機.
#!/bin/bash
#
#******************************************************************************
#Author: Sunny
#Date: 2017-09-03
#FileName: scp.sh
#version: 1.0
#Your change info:
#Description: For
#Copyright(C): 2017 All rihts reserved
#*****************************************************************************
echo "1 copy wang home dir,usage:$0"
echo "2 copy file under wang home,usage: $0 file_to_copy"
echo "3 send file to wang home,usage: $0 file_to_send"
echo "4 login other host by ssh,usage: $0 login_ip"
echo "5 login other host by telnet,usage: $0 login_ip login_user"
read -p "input the remote ip: " ip
read -p "input full path file_name or dir: " file
read -p "input host password: " passwd
read -p "Please input your choice: " choice
case $choice in
1)
expect -c "
spawn scp -r root@$ip:$file "$file_$(date +%F-%H-%M)"
expect {
# "*assword" {set timeout 300; send "$passwdr"; }
"*assword" {set timeout 300; send "$passwdr"; }
"yes/no" { send "yesr"; exp_continue; }
}
expect eof"
;;
2)
expect -c "
spawn scp root@$ip:$file /root/
expect {
# "*assword" {set timeout 500; send "$passwdr"; }
"*assword" {set timeout 500; send "$passwdr"; }
"yes/no" { send "yesr"; exp_continue; }
}
expect eof"
;;
3)
expect -c "
spawn scp $file root@$ip:/root
expect {
# "*assword" {set timeout 500; send "$passwdr"; }
"*assword" {set timeout 500; send "$passwdr"; }
"yes/no" { send "yesr"; exp_continue; }
}
expect eof"
;;
4)
expect -c "
spawn ssh $ip
expect {
"yes/no" { send "yesr"; exp_continue; }
"*assword" {set timeout 500; send "$passwdr"; }
}
interact
expect eof"
;;
5)
expect -c "
spawn telnet $ip
expect {
"*assword" {set timeout 500; send "$passwdr"; }
"login" { send "sunnyr";exp_continue; }
}
interact
expect eof"
;;
*)
echo "Your input is wrong,please check"
exit
;;
esac
4 總結
expect可以實際靜默的操作,這個在指令碼中經常用到,讀者根據對應的功能,拷貝相關程式碼,可以直接把變數換成固定的值,不需要每次執行指令碼都需要人工輸入變數值,實現靜默操作。
本文永久更新連結地址:http://www.linuxidc.com/Linux/2017-10/147227.htm
相關文章