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

标签 bash ssh sudo

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

#!/bin/bash

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

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

此类脚本的示例:

#!/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/

相关文章:

linux - 为 bash 设置默认命令

linux - Bash 脚本 : select lines starting with number in specific range

linux - 系统命令返回是什么?

linux - 在matlab中以编程方式运行shell脚本

linux - `' ` 在 `printf "%x""' 你"` 中的功能是什么?

python - 使用 Python 通过 SSH 隧道连接到远程 PostgreSQL 数据库

bash - 我如何使用 su 作为该用户执行 bash 脚本的其余部分?

node.js - 如何在没有 sudo 权限的 CentOS 上安装 Node.js

python - 无法找到包 python-gnomedesktop : Installing PyViz in ns3

bash - 为什么在传递到 bash 时使用 -Lo- 和 curl?