通过 ssh 的 sudo cmd 连续两次期望
我使用 expect
通过 ssh 在远程主机中使用 sudo 执行一些命令。脚本如下:
spawn ssh -q ${user}@${host}
expect "*?assword:"
send "${pass}\r"
expect "${user}@"
send "sudo ls\r"
expect "*?assword:"
send "${pass}\r"
expect "${user}@"
send "exit\r"
interac
第一次运行得很好,但是当我连续执行时出现了一些错误。这是因为 sudo 不会立即过期,所以如果短时间内 sudo 某个命令两次,第二次可能不需要密码,因此第二次发送 "${pass}\r “上面脚本中的失败了!
那么,当 sudo 未过期时,我们如何检测并避免发送密码呢?谢谢!
I used expect
to execute some command with sudo in remote host via ssh. The script lies as follow:
spawn ssh -q ${user}@${host}
expect "*?assword:"
send "${pass}\r"
expect "${user}@"
send "sudo ls\r"
expect "*?assword:"
send "${pass}\r"
expect "${user}@"
send "exit\r"
interac
It runs perfectly the first time, but when I executed it consecutively some error occurred. That's because sudo
won't expire right away, so if sudo some command twice in a short time, the second maybe not need the password, thus the second send "${pass}\r"
in above script failed!
So how can we detect that and avoid sending password when sudo does not expire? thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
修改脚本,以便期望 sudo 密码是可选的:
Modify the script so that expecting the sudo password is optional:
日志记录后立即运行
sudo -k
清理 sudo 身份验证缓存。Clean the sudo authentication cache running
sudo -k
just after logging.