gpt4 book ai didi

bash - 从文件读取时,通过 SSH 编写 sudo 脚本的行为很奇怪

转载 作者:行者123 更新时间:2023-12-02 13:52:37 26 4
gpt4 key购买 nike

我发现我可以从 bash 脚本中在远程系统上运行单个 sudo 命令。例如:

#!/bin/bash

ssh -t <REMOTE_IP> 'sudo ls /root'

但是,如果我尝试通过包含远程系统 IP 的文件的循环运行相同的命令,它开始变得奇怪。它无法使用 -t 选项分配 TTY,因此我使用了两个 (-t -t)。这样做会使其进入密码提示。然后,当我什至没有输入密码时,它告诉我我的密码不正确,显示第二个提示,回显我的密码,然后在我按 Enter 键后挂起。

此类脚本的示例:
#!/bin/bash

while read i
do
ssh -t -t $i "sudo ls /root"
done < ip.list

我看到的结果示例:
user@opensuse:~/bin> ./test.sh 
10.153.171.131

[sudo] password for user:
Sorry, try again.
[sudo] password for user: Pa55w0rd
^CKilled by signal 2. *This is where it hangs and I have to kill it.*

我没有找到太多的解释方式,所以如果有人能对此有所了解,我将不胜感激。

谢谢。

最佳答案

您正在重定向 stdin在你的循环中:

while read i
do
ssh -t -t $i "sudo ls /root"
done < ip.list

这意味着 (a) ssh不再连接到您的 TTY,并且 (b) 它可能会吃掉您的输入。理想情况下,您应该将输入从 /dev/null 重定向到 ssh并配置 sudo不需要 TTY。但是,您可以尝试:
ssh -t $i "sudo ls /root" < /dev/tty

关于bash - 从文件读取时,通过 SSH 编写 sudo 脚本的行为很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com