非交互式 ssh sudo... 以纯文本形式提示输入密码

Iai*_*ain 9 security ssh sudo macos

我正在运行一些非交互式 ssh 命令。通过 ssh 代理可以很好地处理 ssh 身份验证,但是如果我运行需要 sudo 的命令,则终端中的密码提示是纯文本。例如:

ssh remotemachine "sudo -u www mkdir -p /path/to/new/folder"
Run Code Online (Sandbox Code Playgroud)

将提示我输入纯文本密码。有谁知道我如何让它使用正常的安全提示,或者我可以通过交换机传递密码?(这样我就可以在发送命令之前在这边设置一个安全提示)

任何帮助深表感谢。

Oll*_*lli 13

使用ssh -t

人 ssh

-t   Force pseudo-tty allocation. This can be used to execute arbitrary 
     screen-based programs on a remote machine, which can be very useful, 
     e.g. when implementing menu services. Multiple -t options force tty 
     allocation, even if ssh has no local tty.
Run Code Online (Sandbox Code Playgroud)

所以你的命令将是

ssh remotemachine -t "sudo -u www mkdir -p /path/to/new/folder"
Run Code Online (Sandbox Code Playgroud)

如果不想输入密码,可以(如果允许)sudoers使用 command进行修改visudo

添加参数NOPASSWD:,例如

username ALL=(ALL) NOPASSWD: /bin/mkdir
Run Code Online (Sandbox Code Playgroud)

如果您无法编辑 /etc/sudoers,您可以使用sudo -S

男人须藤

-S      The -S (stdin) option causes sudo to read the password from
        the standard input instead of the terminal device.  The
        password must be followed by a newline character.
Run Code Online (Sandbox Code Playgroud)

有了这个,命令将是

echo "your_password" | ssh remotemachine -t \
     "sudo -S -u www mkdir -p /path/to/new/folder"
Run Code Online (Sandbox Code Playgroud)

请记住,这会将您的密码添加到您的 shell 的命令历史记录中(使用 bash,那就是~/.bash_history文件)。