详解Linux expect使用方法

expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信,本篇文章为大家详细讲解一下Linux expect使用方法。

expect参数

启用选项

  • -c:执行脚本前先执行的命令,可多次使用。
  • -d:debug模式,可以在运行时输出一些诊断信息,与在脚本开始处使用
    exp_internal 1相似。
  • -D:启用交换调式器,可设一整数参数。
  • -f:从文件读取命令,仅用于使用#!时。如果文件名为”-“,则从stdin读取(使用”./-“从文件名为-的文件读取)。
  • -i:交互式输入命令,使用”exit”或”EOF”退出输入状态。
  • --:标示选项结束(如果你需要传递与expect选项相似的参数给脚本时),可放到
    #!行:
    #!/usr/bin/expect --
  • -v:显示expect版本信息。

expect的4个命令

Expect中最关键的四个命令是send,expect,spawn,interact。

命令说明
send用于向进程发送字符串
expect从进程接收字符串
spawn启动新的进程
interact允许用户交互

常用命令

`# 命令行参数`

`# $argv,参数数组,使用[lindex $argv n]获取,$argv 0为脚本名字`

`# $argc,参数个数`

`set` `username [lindex $argv 1]` `# 获取第1个参数`

`set` `passwd` `[lindex $argv 2]` `# 获取第2个参数`

`set` `timeout 30` `# 设置超时`

`# spawn是expect内部命令,开启ssh连接`

`spawn` `ssh` `-l username 192.168.1.1`

`# 判断上次输出结果里是否包含“password:”的字符串,如果有则立即返回,否则就等待一段时间(timeout)后返回`

`expect` `"password:"`

`# 发送内容ispass(密码、命令等)`

`send` `"ispass\r"`

`# 发送内容给用户`

`send_user` `"$argv0 [lrange $argv 0 2]\n"`

`send_user` `"It's OK\r"`

`# 执行完成后保持交互状态,控制权交给控制台(手工操作)。否则会完成后会退出。`

`interact`

命令介绍

  • close:关闭当前进程的连接。

  • debug:控制调试器。

  • disconnect:断开进程连接(进程仍在后台运行)。

    • 定时读取密码、执行priv_prog
       `send_user` `"password?\ "`

       `expect_user -re` `"(.*)\n"`

       `for` `{} 1 {} {`

       `if` `{[fork]!=0} {``sleep` `3600;``continue``}`

       `disconnect`

       `spawn priv_prog`

       `expect Password:`

       `send` `"$expect_out(1,string)\r"`

       `. . .`

       `exit`

       `}`
  • exit:退出expect。
  • exp_continue [-continue_timer]:继续执行下面的匹配。
  • exp_internal [-f file] value:

expect范例

1.远程登录并创建文件后退出
#!/usr/bin/expect           ##注意路径,使用 [whereis expect] 查看set user "hadoop"           ##设定参数,注意",'的区别set pwd "yangkun"set host "48.93.36.144"set timeout -1              ##;号可有可无
spawn ssh -p 2020 $user@$host
expect {                    ##expect后有空格
   "*yes/no" {send "yes\r";exp_continue}
   "*password:" {send "$pwd\r"}
}
expect "]*"                 ## 通配符,使用 ]* 有效, 使用  *# 无效
send "touch /home/hadoop/aa.txt\r"
expect "]*"
send "echo hello world >> /home/hadoop/aa.txt\r"
expect "]*"
[interact]                  ##人为交互
send "exit\r"               ##退出
2.配置免密登录并安装JDK
#!/bin/bash#!/usr/bin/expect
SERVERS="114.114.114.114"       ##数组以空格分隔,可以为目标ip 或者hostName
PASSWORD="yangkun"## 实现免密登录配置的函数auto_ssh_copy_id() {
   expect -c "set timeout -1;        spawn ssh-copy-id \"-p 2020 $1\";       ## 这里要注意,使用'或\'不可行        expect {            *(yes/no)* {send -- yes\r;exp_continue;}            *password:* {send -- $2\r;exp_continue;}            eof {exit 0;}        }";
}

## 循环执行,配置主机到从节点所有免密ssh_copy_id_to_all() {
   for SERVER in $SERVERS              ## 取值需要加$
   do
       auto_ssh_copy_id $SERVER $PASSWORD
   done    
}

## 调用循环配置函数
ssh_copy_id_to_all


## 批量部署for SERVER in $SERVERSdo
   scp install.sh root@$SERVER:/root
   ssh root@$SERVER /root/install.sh
done
  • 读取文件中的host配置
让脚本自动读取slaves文件中的机器名来批量安装
cat slaves | while read host
doecho $host
expect -c "set timeout -f spawn ssh-copy-id $host"done

3.批量配置JDK,install.sh

#!/bin/bash
BASE_SERVER=master
BASE_PATH=/home/hadoop/soft
TARGET_PATH=/usr/local
JAVA_PATH=$TARGET_PATH/java
## 1.判断是否存在文件夹,不存在则创建soft文件夹#if [ ! -d "$BASE_PATH" ]; then#   mkdir "$BASE_PATH"#fi## 2.从指定host拷贝jdk到目标机器上(已经拷贝文件夹)
scp -r $BASE_SERVER:$BASE_PATH $BASE_PATH## 2.解压jdk到指定目录if [ ! -d "$JAVA_PATH" ]; then
   sudo -S mkdir -p "$JAVA_PATH"fi## 赋予权限
sudo -S chmod -R hadoop:hadoop $JAVA_PATH

tar -zxvf $BASE_PATH/jdk1.8.0_121.tar.gz -C $JAVA_PATH#### 3.配置环境变量
sudo -S cat>>/etc/profileexport JAVA_HOME=$JAVA_PATH/jdk1.8.0_121
export PATH=\$PATH:\$JAVA_HOME/bin
EOF
  • 自动telnet会话
#!/usr/bin/expect -fset ip [lindex $argv 0 ]         # 接收第1个参数,作为IPset userid [lindex $argv 1 ]     # 接收第2个参数,作为useridset mypassword [lindex $argv 2 ] # 接收第3个参数,作为密码set mycommand [lindex $argv 3 ]  # 接收第4个参数,作为命令set timeout 10                   # 设置超时时间# 向远程服务器请求打开一个telnet会话,并等待服务器询问用户名
spawn telnet $ip
   expect "username:"
   # 输入用户名,并等待服务器询问密码
   send "$userid\r"
   expect "password:"
   # 输入密码,并等待键入需要运行的命令
   send "$mypassword\r"
   expect "%"
   # 输入预先定好的密码,等待运行结果
   send "$mycommand\r"
   expect "%"
   # 将运行结果存入到变量中,显示出来或者写到磁盘中
   set results $expect_out(buffer)
   # 退出telnet会话,等待服务器的退出提示EOF
   send "exit\r"
   expect eof

4.自动建立FTP会话

  #!/usr/bin/expect -fset ip [lindex $argv 0 ]         # 接收第1个参数,作为IPset userid [lindex $argv 1 ]     # 接收第2个参数,作为Useridset mypassword [lindex $argv 2 ] # 接收第3个参数,作为密码set timeout 10                   # 设置超时时间# 向远程服务器请求打开一个FTP会话,并等待服务器询问用户名
spawn ftp $ip
   expect "username:"
   # 输入用户名,并等待服务器询问密码
   send "$userid\r"
   expect "password:"
   # 输入密码,并等待FTP提示符的出现
   send "$mypassword\r"
   expect "ftp>"
   # 切换到二进制模式,并等待FTP提示符的出现
   send "bin\r"
   expect "ftp>"
   # 关闭ftp的提示符
   send "prompt\r"
   expect "ftp>"
   # 下载所有文件
   send "mget *\r"
   expect "ftp>"
   # 退出此次ftp会话,并等待服务器的退出提示EOF
   send "bye\r"
   expect eof
  • 自动登录ssh执行命令
#!/usr/bin/expectset IP     [lindex $argv 0]
set USER   [lindex $argv 1]
set PASSWD [lindex $argv 2]
set CMD    [lindex $argv 3]

spawn ssh $USER@$IP $CMD
expect {
   "(yes/no)?" {
       send "yes\r"
       expect "password:"
       send "$PASSWD\r"
       }
   "password:" {send "$PASSWD\r"}
   "* to host" {exit 1}
   }
expect eof

5.自动登录ssh

#!/usr/bin/expect -f  set ip [lindex $argv 0 ]         # 接收第1个参数,作为IPset username [lindex $argv 1 ]   # 接收第2个参数,作为usernameset mypassword [lindex $argv 2 ] # 接收第3个参数,作为密码set timeout 10                   # 设置超时时间

spawn ssh $username@$ip       # 发送ssh请求
expect {                      # 返回信息匹配"*yes/no" { send "yes\r"; exp_continue}  # 第一次ssh连接会提示yes/no,继续  "*password:" { send "$mypassword\r" }    # 出现密码提示,发送密码  
}
interact        # 交互模式,用户会停留在远程服务器上面

6.批量登录ssh服务器执行操作范例,设定增量的for循环

#!/usr/bin/expectfor {set i 10} {$i set timeout 30
 set ssh_user [lindex $argv 0]
 spawn ssh -i .ssh/$ssh_user abc$i.com

 expect_before "no)?" {
 send "yes\r" }
 sleep 1
 expect "password*"
 send "hello\r"
 expect "*#"
 send "echo hello expect! > /tmp/expect.txt\r"
 expect "*#"
 send "echo\r"
}
exit

7.批量登录ssh并执行命令,foreach语法

#!/usr/bin/expectif {$argc!=2} {
   send_user "usage: ./expect ssh_user password\n"
   exit
}
foreach i {11 12} {
   set timeout 30
   set ssh_user [lindex $argv 0]
   set password [lindex $argv 1]
   spawn ssh -i .ssh/$ssh_user [email protected]
   expect_before "no)?" {
   send "yes\r" }
   sleep 1

   expect "Enter passphrase for key*"
   send "password\r"
   expect "*#"
   send "echo hello expect! > /tmp/expect.txt\r"
   expect "*#"
   send "echo\r"
}
exit

8.另一自动ssh范例,从命令行获取服务器IP,foreach语法,expect嵌套

   #!/usr/bin/expect# 使用方法: script_name ip1 ip2 ip3 ...set timeout 20
if {$argc "Usage: script IPs"
 exit 1
}
# 替换你自己的用户名set user "username"#替换你自己的登录密码set password "yourpassword"

foreach IP $argv {
spawn ssh $user@$IP

expect \
 "(yes/no)?" {
   send "yes\r"
   expect "password:?" {
     send "$password\r"
   }
 } "password:?" {
   send "$password\r"
}

expect "\$?"# 替换你要执行的命令
send "last\r"
expect "\$?"
sleep 10
send "exit\r"
expect eof
}

9.批量ssh执行命令,用shell调用tclsh方式、多进程同时执行

*   tclsh - Simple shell containing Tcl interpreter
1
#!/bin/sh# -*- tcl -*- \exec tclsh $0 "$@"
package require Expect
set username [lindex $argv 0]
set password [lindex $argv 1]
set argv [lrange $argv 2 end]
set prompt "(%|#|\\$) $"
foreach ip $argv {
   spawn ssh -t $username@$ip sh
   lappend ids $spawn_id
}
expect_before -i ids eof {
   set index [lsearch $ids $expect_out(spawn_id)]
   set ids [lreplace $ids $index $index]
   if [llength $ids] exp_continue
}
expect -i ids "(yes/no)\\?" {
   send -i $expect_out(spawn_id) yes\r
   exp_continue
} -i ids "Enter passphrase for key" {
   send -i $expect_out(spawn_id) \r
   exp_continue
} -i ids "assword:" {
   send -i $expect_out(spawn_id) $password\r
   exp_continue
} -i ids -re $prompt {
   set spawn_id $expect_out(spawn_id)
   send "echo hello; exit\r"
   exp_continue
} timeout {
   exit 1
}

10.ssh登录过程常规提示文字

The authenticity of host '192.168.17.35 (192.168.17.35)' can't be established. RSA key fingerprint is 25:e8:4c:89:a3:b2:06:ee:de:66:c7:7e:1b:fa:1c:c5. Are you sure you want to continue connecting (yes/no)? Warning: Permanently added '192.168.17.35' (RSA) to the list of known hosts. Enter passphrase for key '/data/key/my_dsa': Last login: Sun Jan 26 13:39:37 2014 from 192.168.11.143 [root@master003 ~]# [email protected]'s password:


Last login: Thu Jan 23 17:50:43 2014 from 192.168.11.102
[root@lvsmaster ~]#

11.ssh自动登录expect脚本:ssh.expect

   #!/usr/bin/expect -f# Auther:YuanXing# Update:2014-02-08if {$argc "Usage:\n  $argv0 IPaddr User Passwd Port Passphrase\n"
   puts stderr "argv error!\n"
   sleep 1
   exit 1
}

set ip         [lindex $argv 0 ]
set user       [lindex $argv 1 ]
set passwd     [lindex $argv 2 ]
set port       [lindex $argv 3 ]
set passphrase [lindex $argv 4 ]
set timeout 6
if {$port == ""} {
   set port 22
}
#send_user "IP:$ip,User:$user,Passwd:$passwd,Port:$port,Passphrase:$passphrase"
spawn ssh -p $port $user@$ip

expect_before "(yes/no)\\?" {
   send "yes\r"}

expect \
"Enter passphrase for key*" {
   send "$passphrase\r"
   exp_continue
} " password:?" {
   send "$passwd\r"
   exp_continue
} "*\[#\\\$]" {
   interact
} "* to host" {
   send_user "Connect faild!"
   exit 2
} timeout {
   send_user "Connect timeout!"
   exit 2
} eof {
   send_user "Lost connect!"
   exit
}

12.Mikrotik backup script using ssh and expect

#!/bin/bash# TAG: mikrotik, ssh, expect, lftp

BACKUP_DIR="/var/backups"
HOSTNAME="192.168.88.1"
PORT="22"
USER="admin"
PASS="123456"
TMP=$(mktemp)
TODAY=$(date +%F)
FILENAME="$HOSTNAME-$TODAY"
PATH="/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin"# create expect script
cat > $TMP #exp_internal 1 # Uncomment for debug
set timeout -1
spawn ssh -p$PORT $USER@$HOSTNAME
match_max 100000
expect -exact "password:"
send -- "$PASS\r"
sleep 1
expect " > "
send -- "/export file=$FILENAME\r"
expect " > "
send -- "/system backup save name=$FILENAME\r"
expect " > "
send -- "quit\r"
expect eof
EOF

# run expect script#cat $TMP # Uncomment for debug
expect -f $TMP# remove expect script
rm $TMP# download and remove backup files# "xfer:clobber on" means overwrite existing filescd ${BACKUP_DIR}echo "  set xfer:clobber on  get ${FILENAME}.rsc  rm ${FILENAME}.rsc  get ${FILENAME}.backup  rm ${FILENAME}.backup" |
lftp -u $USER,$PASS $HOSTNAME

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/204995.html<

(0)
运维的头像运维
上一篇2025-04-07 10:05
下一篇 2025-04-07 10:06

相关推荐

  • 个人主题怎么制作?

    制作个人主题是一个将个人风格、兴趣或专业领域转化为视觉化或结构化内容的过程,无论是用于个人博客、作品集、社交媒体账号还是品牌形象,核心都是围绕“个人特色”展开,以下从定位、内容规划、视觉设计、技术实现四个维度,详细拆解制作个人主题的完整流程,明确主题定位:找到个人特色的核心主题定位是所有工作的起点,需要先回答……

    2025-11-20
    0
  • 社群营销管理关键是什么?

    社群营销的核心在于通过建立有温度、有价值、有归属感的社群,实现用户留存、转化和品牌传播,其管理需贯穿“目标定位-内容运营-用户互动-数据驱动-风险控制”全流程,以下从五个维度展开详细说明:明确社群定位与目标社群管理的首要任务是精准定位,需明确社群的核心价值(如行业交流、产品使用指导、兴趣分享等)、目标用户画像……

    2025-11-20
    0
  • 香港公司网站备案需要什么材料?

    香港公司进行网站备案是一个涉及多部门协调、流程相对严谨的过程,尤其需兼顾中国内地与香港两地的监管要求,由于香港公司注册地与中国内地不同,其网站若主要服务内地用户或使用内地服务器,需根据服务器位置、网站内容性质等,选择对应的备案路径(如工信部ICP备案或公安备案),以下从备案主体资格、流程步骤、材料准备、注意事项……

    2025-11-20
    0
  • 如何企业上云推广

    企业上云已成为数字化转型的核心战略,但推广过程中需结合行业特性、企业痛点与市场需求,构建系统性、多维度的推广体系,以下从市场定位、策略设计、执行落地及效果优化四个维度,详细拆解企业上云推广的实践路径,精准定位:明确目标企业与核心价值企业上云并非“一刀切”的方案,需先锁定目标客户群体,提炼差异化价值主张,客户分层……

    2025-11-20
    0
  • PS设计搜索框的实用技巧有哪些?

    在PS中设计一个美观且功能性的搜索框需要结合创意构思、视觉设计和用户体验考量,以下从设计思路、制作步骤、细节优化及交互预览等方面详细说明,帮助打造符合需求的搜索框,设计前的规划明确使用场景:根据网站或APP的整体风格确定搜索框的调性,例如极简风适合细线条和纯色,科技感适合渐变和发光效果,电商类则可能需要突出搜索……

    2025-11-20
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注