安装expect命令:
yum install expect -y
创建exp脚本,注意首行为 #!/usr/bin/expect,并修改权限为750
touch ssh.exp
chmod 750 ssh.exp
拷贝以下内容到ssh.exp文件
#!/usr/bin/expect
#参数校验
if { $argc != 3 } {
send_user "usage: ./ssh.exp <host> <user> <password> \n"
exit
}
#变量设置
#log_file login.log
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set newpassword "mikepeng"
set timeout 30
#过滤关键字
set key_password "*password: "
set key_yesorno "*(yes/no)? "
#函数定义
proc func_login {password newpassword} {
expect {
"*(yes/no)? " {
send "yes\r";
exp_continue
}
"*password: " {
send "$password\r";
exp_continue
}
"*]\$ " {
#send_log "\r>>>>>>>>>> Login in SUCCESS <<<<<<<<<<<<\r";
puts "\r>>>>>>>>>> Login in SUCCESS <<<<<<<<<<<<\r"
}
"Permission denied*" {
send_error "\r>>>>>>>>>> Login in FAILED <<<<<<<<<<<<\r";
close;
exit
}
"*UNIX password: " {
send "$password\r";
}
"New password: " {
send "$newpassword\r";
}
"Retype new password: " {
send "$newpassword\r";
}
}
}
####################开始执行#####################
spawn ssh $user@$host
func_login $password $newpassword
#todo
send "touch test.txt\r"
#结束退出
send "exit\r"
expect eof
执行ssh.exp文件
./ssh.exp 192.168.31.101 thinker 123456