shell脚本实现自动输入账号密码连接运服务器并执行其他命令的方法-总结

操作

  • vi ssh.sh
#!/usr/tcl/bin/expect
 
if {$argc < 3} {
    puts "Usage:cmd <host> <username> <password>"
    exit 1
}
 
set timeout -1
set host [lindex $argv 0] 
set username [lindex $argv 1]
set password [lindex $argv 2]
 
spawn ssh $username@$host
expect { 
    "*yes/no" {send "yes\r"; exp_continue}
    "*password:" {send "$password\r"; exp_continue}
    "$username@*" {send "mkdir zzz;mkdir aaa;exit;\r" }
}
#interact
expect eof
exit
  • chmod +x ssh.sh
  • ./ssh.sh 127.0.0.1 root 123456

注意

  • 第一行定要写这句话,否则会报spawn: command not found
    #!/usr/tcl/bin/expect:使用expect来解释该脚本;
  • 这个脚本和shell脚本部分指令不兼容.注意分开写
  • 这3个必须要有,否则他一登录就退出掉了,不会执行mkdir的内容。


    image.png
  • interact会停在远程服务器上。

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容