您的位置:首页 > 运维架构 > Linux

使用expect实现ssh自动输入密码,从而自动登陆Linux

2010-12-18 14:22 1041 查看
以下来自网上的一些资料和自己的实验,用以下命令执行:

expect -f expect-ssh.exp <username> <password> <hostname or ip>

注意,在这个expect-ssh.exp中,connect函数主要负责登陆,代码的最后两行,两个send是登陆上去后,执行的命令,注意最后一定要执行一个exit,否则会导致expect执行完成后还留在远程主机上。

这里是expect-ssh.exp的源码: proc usage {} {
puts stderr "usage: $::argv0 username password ipaddress"
exit 1
}

proc connect {pass} {
expect {
"(yes/no)?" {
send "yes\n"
expect "*password:" {
send "$pass\n"
expect {
"*#" {
return 0
}
}
}
}
"*password:" {
send "$pass\n"
expect {
"*#" {
return 0
}
}
}
}
return 1
}

if {$argc != 3} { usage }

set username [lindex $argv 0]
set password [lindex $argv 1]
set hostip [lindex $argv 2]

spawn ssh ${username}@${hostip}

if {[connect $password]} {
exit 1
}

send "rm -f /root/testeric;rm -f pattern_file\n"
send "exit\n"
expect eof
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: