通过 systemd 在启动时启用和禁用 sshd

Bee*_*ope 7 ssh openssh systemd 16.04

我已经openssh-server安装,但有时我想sshd在启动时默认关闭该服务,并且仅根据需要从终端启动它。

根据许多其他问题的建议,在我systemd使用 16.04 发行版时,在启动时启用和禁用服务应该很简单:

$sudo systemctl disable sshd.service
Run Code Online (Sandbox Code Playgroud)

这似乎有效。但是,此后我无法再在启动时启用该服务:

$sudo systemctl enable sshd.service 
Failed to execute operation: No such file or directory
Run Code Online (Sandbox Code Playgroud)

即使卸载和重新安装openssh-server也不能修复它,但purge可以。

sshd一旦通过 禁用它,systemd如何在启动时重新启用它?

请注意,即使在这种混乱的状态下,我仍然可以通过service ssh[start|stop]`手动启动和停止服务。

arr*_*yph 17

sshd 服务最初写成 ssh.service,sshd.service 被设置为别名。查看以下输出的最后一行。

arryph@localhost:~$ systemctl cat sshd.service 
# /lib/systemd/system/ssh.service
[Unit]
Description=OpenBSD Secure Shell server
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
EnvironmentFile=-/etc/default/ssh
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify

[Install]
WantedBy=multi-user.target
Alias=sshd.service
Run Code Online (Sandbox Code Playgroud)

因此,当ssh.service启用时,我们可以将其称为sshd.service. 但是当您禁用sshd.service并重新启动时,ssh.service不再加载,因此您不能将其称为sshd.service处于该状态。你必须参考 is as ssh.service。因此,如果您运行sudo systemctl enable ssh.service,它将成功启用ssh.service(别名为sshd.service)。

  • 太好了,它有效。这使得别名非常不可用,因为它们适用于某些命令而不适用于其他命令。 (2认同)
  • 这就是服务别名的工作方式,如果服务已加载,您可以使用它们。 (2认同)