分发系统-expect

分发系统—expect

登录多台系统执行指定命令;
创建文件最好以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 [email protected]

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开始;

猜你喜欢

转载自blog.51cto.com/shuzonglu/2107919
今日推荐