依赖
apt install tcl expect
测试远程登陆获取ifconfig
# cat action.exp
#!/bin/expect # 指定解释器
set ip [lindex $argv 0] # 获取执行时的参数
set pwd [lindex $argv 1]
set timeout 3 # 指定expect的超时时间
spawn ssh -p33322 jeff@$ip # 与后面的expect eof对应,指定一个运行过程
expect {
"yes/no" {send "yes\r" ;exp_continue} # expect指定当输出结果中包含yes/no的时候,输入yes
"password" {send "$pwd\r"}
}
expect "#" # 指定当登入成功后,命令输入前包含#号时再执行下面操作,如果在超时时间过了后依旧没有出现,则会退出
send "ifconfig |grep -E '10|175' \r" # send命令输入远程执行的命令
send "exit\r" # 退出远程ssh
expect eof # 退出expect交互环境
运行
expect ./action.exp 10.0.2.53 password