shell脚本之expect模拟交互ssh

2020-09-29 11:41发布

1.EXPECT简介

expect 是基于tcl 演变而来的,所以很多语法和tcl 类似,基本的语法如下

所示:

        首行加上/usr/bin/expect

       spawn: 后面加上需要执行的shell 命令,比如说spawn sudo touch testfile;也即启动新的进程

       expect: 只有spawn 执行的命令结果才会被expect 捕捉到,因为spawn 会启

动一个进程,只有这个进程的相关信息才会被捕捉到,主要包括:标准输入的提示信息,eof 和timeout。也即从新进程接收字符串

       send 和send_user:send 会将expect 脚本中需要的信息发送给spawn 启动

的那个进程,而send_user 只是回显用户发出的信息,类似于shell 中的echo 而

已。用于向进程发送字符串

       interact:允许用户交互

Expect用法:

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

  • send:用于向进程发送字符串

  • expect:从进程接收字符串

  • spawn:启动新的进程

  • interact:允许用户交互

 2.脚本ssh实现交互并在交互端使用ifconfig命令

[root@localhost shell]# vim expect.sh

#!/usr/bin/expect
spawn 192.168.253.179
expect {
        "(yes/no)?" { send "yes\r";exp_continue}  #exp_continue 继续的意思
        "password:" { send "123456\r"}
}
expect "[root@localhost ~]#"
send "ifconfig ens33\r"
expect eof    #直接退出
interact        # 交互完后,将控制权交给控制台

 

[root@localhost ~]# chmod +x expect.sh   #授权
[root@localhost ~]# ./expect.sh     #执行

转载自:CSDN  作者:Hya、

原文链接:https://blog.csdn.net/yeyslspi59/article/details/106817733