码迷,mamicode.com
首页 > 系统相关 > 详细

Linux expect

时间:2015-12-04 12:24:24      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

Linux expect 使用简介
一.登陆到远程主机

脚本代码如下:

技术分享
##############################################
#!/usr/bin/expect
set timeout 30
spawn ssh -l username hostip
expect { 
"yes/no" { send "yes\r";exp_continue } 
"password:" { send "hostpassword\r" } 
} 
interact
##############################################
View Code

1. #!/usr/bin/expect
  这一行告诉操作系统脚本里的代码使用那一个shell来执行。这里的expect其实和linux下的bash
2. set timeout 30
  设置 脚本超时时间
3. spawn ssh -l username hostip
  spawn是进入expect环境后才可以执行的expect内部命令,主要的功能是给ssh运行进程加个壳,用来传递交互指令。
4. expect { 

      "yes/no" { send "yes\r";exp_continue }
      "password:" { send "hostpassword\r" }
      }

  判断连接 主机后输出的字符串进行捕获,发送相应的动作和密码确定连接(Linux 第一次连接主机会提示是否连接此主机) send "hostpassword\r"(发送密码,换行符号进行确认)

5. interact

  完成连接后保持连接在被控主机,如果不加此字段会登陆后就退出改 shell

二.执行远程命令行

  

技术分享
##############################################
#!/usr/bin/expect
set timeout 30
spawn ssh -l username hostip
expect { 
"yes/no" { send "yes\r";exp_continue } 
"password:" { send "hostpassword\r" } 
} 
expect -re "\](\$|#) " 
send "bash /root/test.sh \r" 
expect -re "\](\$|#) " 
send "exit\r" 
##############################################
View Code

1.expect -re "\](\$|#) "

  匹配终端输出字符

2.send "bash /root/test.sh \r" 

  执行远程命令或者脚本

3.expect -re "\](\$|#) " 

  判断执行完毕与否

4.send "exit\r" 

  退出 shell

Linux expect

标签:

原文地址:http://www.cnblogs.com/edwardlogs/p/5018731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!