expect可以帮助我们 自动化完成一些交互操作。

使用expect来执行ssh命令

  1. 编写脚本

#!/usr/bin/expect
#sshlogin.exp

set timeout 30
set host "192.168.1.8"
set username "your_username"
set password "yout_password"

spawn ssh [email protected]$host
#expect "*password:*" {send "$password\r"}
expect {
"*password:" {send "$password\r"}
}
interact

  1. 给脚本权限

    chmod 755 
    
  2. 运行脚本

    ./sshlogin.exp
    

使用一行命令直接运行

expect -c 'spawn ssh {{username}}@{{host}}; expect "*password:*"; send "{{password}}\r"; interact'

references:

https://en.wikipedia.org/wiki/Expect

https://stackoverflow.com/questions/3149367/how-to-get-expect-c-to-work-in-single-line-rather-than-script