linux expect自动切换用户

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nayi_224/article/details/82759882

背景

我需要写这样一个脚本

切换用户
kill一个进程
执行一个sh脚本
退回原用户

但是又不想在切换用户的时候手动输入密码,于是我找到了expect这样一个东西。它可以实现自动向服务器中输入的功能。

安装

我用的是这个
https://www.cnblogs.com/daojian/archive/2012/10/10/2718390.html
安装的时候注意命令中的版本号要与自己的保持一致。

编写脚本

vi test.sh

#!/usr/expect/bin/expect -f
set timeout 1
spawn su - root

expect ":"
send "密码\n"
expect "#"
send "ps -ef|grep xxxxxxxxx|grep -v grep|awk '{print \$2}'|xargs kill -9\r"
send "sh /xxx/xxx.sh\r"
send "exit\r"
send "cd /home/xxx\r"

set timeout 1 是设置超时时间。默认是10秒,它会在10秒后自动完成输入操作。我将它设置成了1秒

set timeout 1

设为 -1 时为不限时。

set timeout -1

执行
/home/xxxx/test.sh

猜你喜欢

转载自blog.csdn.net/nayi_224/article/details/82759882
今日推荐