0

我没有在我的两台服务器 a 和 b 之间启用无密码 ssh。所以我使用 sshpass 从 a 连接到服务器 b。

我需要在服务器 b 的 /etc/hosts 中添加主机条目。但是我登录到服务器 b 的用户是非 root 用户,但具有编辑 root 拥有的文件的 sudo 权限。

如何在使用 sshpass 时通过 shell 脚本将主机条目从服务器 a 添加到服务器 b 的 /etc/hosts。

这是尝试过的脚本:

#!/bin/bash

export SSHPASS="password"
SSHUSER=ciuser
WPC_IP=10.8.150.28

sshpass -e ssh -o UserKnownHostsFile=/dev/null -o 'StrictHostKeyChecking no' $SSHUSER@$WPC_IP "echo test >> /etc/hosts"

输出:

bash test.sh
Warning: Permanently added '10.8.150.28' (RSA) to the list of known hosts.
bash: /etc/hosts: Permission denied

谢谢你。

4

1 回答 1

1

sudo 不能直接使用重定向,因此您可以使用sudo tee -a附加到文件:

echo '1.2.3.4 test' | sudo tee -a /etc/hosts

在您的命令中,这将是:

sshpass -e ssh -o UserKnownHostsFile=/dev/null -o 'StrictHostKeyChecking no' "$SSHUSER@$WPC_IP" "echo test | sudo tee -a /etc/hosts"

请注意,这需要没有 tty 的无密码 sudo 访问,这不一定与您的 sudo 权限相同。

于 2016-12-02T22:45:09.030 回答