linux expect自动登录ssh
expect是一种能够按照脚本内容里面设定的方式与交互式程序进行“会话”的程序。根据脚本内容,Expect可以知道
程序会提示或反馈什么内容以及 什么是正确的应答。它是一种可以提供“分支和嵌套结构”来引导程序流程的解释型脚本语言。
shell功能很强大,但是不能实现有交互功能的多机器之前的操作,例如ssh和ftp.而expect可以帮助我们来实现.
expect install : $sudo apt-get install expect
#!/usr/bin/expect -f
set ip [lindex $argv 0 ] //接收第一个参数,并设置IP
set password [lindex $argv 1 ] //接收第二个参数,并设置密码
set timeout 10 //设置超时时间
spawn ssh root@$ip //发送ssh请滶
expect { //返回信息匹配
"*yes/no" { send "yes\r"; exp_continue} //第一次ssh连接会提示yes/no,继续
"*password:" { send "$password\r" } //出现密码提示,发送密码
}
interact //交互模式,用户会停留在远程服务器上面.
--------------------------------------------------------
ssh远程登录到服务器,并且执行命令,执行完后并退出
#!/usr/bin/expect -f
set ip 192.168.1.130
set password admin
set timeout 10
spawn ssh root@$ip
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*password:" { send "$password\r" }
}
expect "#*"
send "pwd\r"
send "exit\r"
expect eof
----------------------------------------
一个实用的脚本
#!/usr/bin/expect
#sudo apt-get install expect
set timeout 13
spawn ssh caoming0510@192.168.65.14
expect {
"*(yes/no)? " {send "yes\r"; exp_continue}
"*password: " {send "ebadde\r"}
}
interact
#!/usr/bin/expect -f
#sudo apt-get install expect
set file [lindex $argv 0 ]
if { $file == "" } {
puts "plase must input one ages"
exit 70
}
spawn scp -pr3 root@192.168.133.129:/root/$file root@192.168.133.128:/root
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*Password:" { send "a+123456\r" }
}
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*Password:" { send "a+123456\r" }
}
interact
--------------------------------------------
[interact]
执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。
如果没有这一句登录完成后会退出,而不是留在远程终端上。如果你只是登录过去执行
[expect "password:"]
这个命 令的意思是判断上次输出结果里是否包含“password:”的字符串,如果有
则立即返回,否则就等待一段时间后返回,这里等待时长就是前面设置的30秒
[set timeout 30]
基本上认识英文的都知道这是设置超时时间的,现在你只要记住他的计时单位是:秒
[spawn ssh -l username 192.168.1.1]
spawn是进入expect环境后才可以执行的expect内部命令,如果没有装expect或者直接在默认的SHELL
下执行是找不到spawn命 令的。所以不要用 “which spawn“之类的命令去找spawn命令。好比windows里的
dir就是一个内部命令,这个命令由shell自带,你无法找到一个dir.com 或 dir.exe 的可执行文件。它主
要的功能是给ssh运行进程加个壳,用来传递交互指令。

浙公网安备 33010602011771号