分发系统—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 [email protected]$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 [email protected]$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开始;
原文地址:http://blog.51cto.com/shuzonglu/2107919
时间: 2024-10-19 06:31:25