Loading

Linux shell利用expect自动连接ssh执行服务器端脚本文件

利用expect自动连接ssh执行对端shell脚本

书接上回,上次讲了在scp传输文件时,怎么利用expect来实现自动输入密码的问题,这次来讲怎么利用expect来实现ssh执行对端shell脚本。

关于expect的介绍,请参看之前的文章linux shell用expect实现在scp时自动输入密码_师从名剑山的博客-CSDN博客_expect自动输入密码

ssh执行命令

  1. 当需要执行的命令只有一条时

ssh user@ip "ls -l"

  1. 当有两条或者两条以上时:

ssh user@ip "cd /root; ls -l"

两条命令之间用 ;隔开时,就会按照顺序执行命令。当两条命令用&&隔开时,只有当第一条命令执行成功时,才会执行第二条。

并且,两条命令时,必须要用双引号连接起来,否则第二条命令会在本地执行。

使用expect

遇到的问题在这里,当我用如下代码运行时,shell脚本死活执行不成功

/usr/bin/expect << EOF
set timeout 30
spawn ssh $user@$host "/bin/bash test.sh $type"
expect { 
"yes/no" { send "yes\r";exp_continue;}
"*assword:" { send "$passwd\r";}
}
EOF

后面更换成这个代码之后,能够正常的运行了

/usr/bin/expect << EOF
set timeout 30
spawn ssh $user@$host
expect { 
"yes/no" { send "yes\r";exp_continue;}
"*assword:" { send "$passwd\r";}
}
expect "root@*" {send "/bin/bash /setup/test.sh $type\r"}
expect "root@*" {send "exit\r"}
expect eof
EOF
}
posted @ 2022-09-03 19:46  师从名剑山  阅读(230)  评论(0编辑  收藏  举报