导读 expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预(如:借助Expect处理交互的命令,可以将交互过程:ssh登录,ftp登录等写在一个脚本上,使之自动化完成。尤其适用于需要对多台服务器执行相同操作的环境中,可以大大提高系统管理人员的工作效率)

我们通过Shell可以实现简单的控制流功能,如:循环、判断等。但是对于需要交互的场合则必须通过人工来干预,有时候我们可能会需要实现和交互程序如telnet服务器等进行交互的功能。而expect就使用来实现这种功能的工具。expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预(如:借助Expect处理交互的命令,可以将交互过程:ssh登录,ftp登录等写在一个脚本上,使之自动化完成。尤其适用于需要对多台服务器执行相同操作的环境中,可以大大提高系统管理人员的工作效率)

首先需要有expect:

可以通过以下命令查看是否安装,如果未安装直接 yum install expect,如果不行请自行百度安装。

[root@localhost home]# whereis expect
expect: /usr/bin/expect /usr/share/man/man1/expect.1.gz

[root@localhost home]# expect
编写脚本如下:
#!/bin/bash
passwd="123456"
/usr/bin/expect <<-EOF
set timeout 50
spawn ssh  root@10.10.22.38
expect {
"*yes/*" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect "*]*"
send "df -h\r"
EOF

解释一下:

/usr/bin/expect <<-EOF  #开始用expcet执行标志
EOF  #结束标志
expect {} #是expect要实现交互的命令集
[root@localhost home]# ssh root@10.10.22.38
"*yes/*"
"*password:" { send "$passwd\r" } #如上如果遇到返回值 *代表无限字符,后面是password:则执行 send发送字符串 \r回车
expect "*]*"    #等待出现]执行下一条命令
send "df -h\r"  #执行命令并回车。
登录后复制 
#!/bin/bash
passwd="admin"
/usr/bin/expect <<-EOF set timeout 50 spawn telnet 0 expect { "Login*" { send "admin\r"} } expect { "*assword:" { send "$passwd\r" } } expect { "*admin>" {send "security enable protocol-detect\r"}
}
expect { 
"*admin>" {send "security set port-abnormal detect 2\r"}
}
expect { 
"*admin>" {send "security show protocol-detect status\r"}
}
expect { 
"*admin>" {send "security show port-abnormal-detect level\r"}
}
expect { 
"*admin>" {send "exit\r"}
}

EOF

原文来自:https://blog.51cto.com/u_14181351/5508763

本文地址:https://www.linuxprobe.com/linux-shel-telnet.html编辑:问题终结者,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/