首页 > 其他 > 详细

分发系统-expect

时间:2018-04-26 11:39:50      阅读:183      评论:0      收藏:0      [点我收藏+]
分发系统—expect

expect是一种自动交互语言,能实现在shell脚本中为scp和ssh等自动输入密码自动登录。
登录多台系统执行指定命令;
创建文件最好以expect结尾;

安装包

yum install -y expect

自动远程登录

1.expect
代码:


#! /usr/bin/expect
set host "192.168.188.3"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"assword:" { send "$passwd\r" }
}
interact

说明:

  • set host:设置变量host;
  • send "yes":输出yes;
  • \r:回车
  • “assword:”{ send “$passwd\r”} :获取信息有assword:字样,就输入变量$passwd 回车;
  • interact:不退出,停留登录;

自动远程登录,执行命令并退出

2.expect
代码:


#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.188.3

expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/1.txt\r"
expect "]*"
send "echo 11111 > /tmp/1.txt\r"
expect "]*"
send "exit\r"

说明:

expect "]*":代表截取到]*字样的命令时;其中*代表通配符;

传递参数

3.expect
代码:


#!/usr/bin/expect

set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "123456"
set cm [lindex $argv 2]
spawn ssh $user@$host

expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"

说明:

set user [lindex $argv 0]:定义变量user,指定它的参数为第一个参数,由外界输入提供;参数是有0开始;

分发系统-expect

原文:http://blog.51cto.com/shuzonglu/2107919

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