首页 > 系统服务 > 详细

Linux expect

时间:2020-02-11 19:56:22      阅读:52      评论: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
##############################################
技术分享图片

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" 
##############################################
技术分享图片

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

  匹配终端输出字符

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

  执行远程命令或者脚本

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

  判断执行完毕与否

4.send "exit\r" 

  退出 shell

Linux expect

原文:https://www.cnblogs.com/lgj8/p/12296432.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!