linux工具笔记 - expect自动ssh交互模板
背景
控制远程的命令交互场景,例如自动化测试场景,需要可以通过脚本来执行ssh控制测试机,那么可以通过expect加shell来实现;
代码
编写expect文件a.ex
#!/usr/bin/expect
set IP [lindex $argv 0]
set USER [lindex $argv 1]
set PASSWD [lindex $argv 2]
set CMD [lindex $argv 3]
set timeout 2
spawn ssh $USER@$IP $CMD
expect {
"(yes/no)?" {
send "yes\r"
expect "password:"
send "$PASSWD\r"
exp_continue
}
"password:" {send "$PASSWD\r"}
"* to host" {exit 1}
}
expect eof
运行a.ex
chmod +x ./a.ex
./a.ex 172.23.23.224 root 123123 "date +%s"
#执行完毕,可见连接到172.23.23.224主机,并执行date命令,最终输出到stdout