Linux 之 expect

来源:互联网 发布:c语言开源框架 编辑:程序博客网 时间:2024/06/16 05:04

################

expect:

################

[set timeout 10]:设置超时时间,单位s,timeout -1永不超时

[ spawn ssh root@ip ]:是进入expect环境后才可以执行的expect的内部命令。主要功能是给ssh运行进程加个壳,用来传递交互指令。

[ expect "password:"]:判断上次输出结果是否包含"password:"的字符串,如果有立即返回,否则就等待一段时间,就是set timeout 10的时间。

[ send "yes\r"]:执行交互动作,与手动输入一样。

[ interact ]:保持交互状态,留在远程终端

[ $argv ]:参数数组,[ lindex $argv n],n从0开始

################


#!/usr/bin/expect##shell类型set ip [lindex $argv 0]                     ##接受第一个参数set password [lindex $argv 1]##接受第二个参数set timeout 10                                ##设置超时时间,单位s,timeout -1为永不超时spawn ssh root@ip                       ##发送ssh请求expect{                                         ##返回匹配信息"*yes/no" {send "yes\r";exp_continue}##第一次ssh连接会提示yes/no,继续"*password:"{send "$password\r"}##出现密码提示,发送密码}interact##交互模式,用户会停留在远程服务器上

#!/usr/bin/expectset ip [lindex $argv 0]set password redhat##登录密码为redhat(已知密码的情况)set timeout 10spawn ssh root@ipexpect{"*yes/no" {send "yes\r";exp_continue}"*password:"{send "$password\r"}}interact

#!/usr/bin/expectset ip [lindex $argv 0]set password redhatset timeout 10spawn ssh root@ipexpect{"*yes/no" {send "yes\r";exp_continue}"*password:"{send "$password\r"}}expect "#*"##登录后send "pwd\r"##执行密令pwd,查看当前路径send "exit\r"##退出expect eof


0 0