使用 ssh 和 sudo 错误远程重启服务

use*_*290 4 linux ubuntu systemd systemctl

我正在使用以下命令尝试重新启动服务

ssh username@server "systemctl restart storeapp.service"
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误消息。

Failed to stop storeapp.service: Interactive authentication required.
Run Code Online (Sandbox Code Playgroud)

然后我尝试

ssh -t username@server "systemctl restart storeapp.service"
Run Code Online (Sandbox Code Playgroud)

这失败了,因为它没有使用正确的用户名进行身份验证,它正在跳过username@server其他用户。 Authenticating as : otheruser. 我已经设置了 ssh 密钥。我怎么能克服这个?或者这是系统管理员权限问题?

如果我运行ssh username@server "systemctl status storeapp.service"它,我可以看到我的服务的状态。

mau*_*wns 7

好吧,解决此问题的最简单方法可能是添加:

<username> ALL = NOPASSWD: /bin/systemctl restart storeapp.service
Run Code Online (Sandbox Code Playgroud)

对于 中的文件/etc/sudoers.d,例如:/etc/sudoers.d/storeapp在目标服务器上。

这将允许您在sudo systemctl restart storeapp.service不提示输入密码的情况下运行该命令。


使用ufw目标主机(Ubuntu 18.04)的工作示例

sudo cat /etc/sudoers.d/ufw 
maulinglawns ALL = NOPASSWD: /bin/systemctl restart ufw
Run Code Online (Sandbox Code Playgroud)

在您的服务器上:

ssh -t maulinglawns@<remote> 'sudo /bin/systemctl restart ufw'
maulinglawns@<remote>'s password: 
Connection to <remote> closed.
echo $?
0
Run Code Online (Sandbox Code Playgroud)

正如你从上面看到的,我被提示一次(因为我不使用密钥),但不是sudo命令。退出状态告诉我们,我们在ufw没有密码的情况下成功重启。我也可以通过检查来验证/var/log/syslog


显然,这只适用于a) root访问目标服务器,否则b)询问希望友好的系统管理员这是否可行和/或可接受。如果c)visudo在编辑/创建 sudoer 文件时总是使用!

如果我运行ssh username@server "systemctl status storeapp.service"它,我可以看到我的服务的状态。

是的,status并不总是需要提升权限。