要使 CentOS 上的 SSH 服务在意外停止或崩溃时自动重启,您可以使用 systemd(CentOS 7 及更高版本)或 init.d(CentOS 6 及更低版本)来实现。下面是两种方法的详细步骤:
对于 CentOS 7 及更高版本(使用 systemd):
sudo systemctl status sshd
sudo systemctl start sshd
sudo systemctl enable sshd
sudo vi /etc/systemd/system/sshd-monitor.service
[Unit]
Description=SSH Service Monitor
After=network.target sshd.service
[Service]
Type=oneshot
ExecStart=/bin/systemctl restart sshd
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable sshd-monitor.service
sudo systemctl start sshd-monitor.service
现在,如果 SSH 服务意外停止,systemd 将自动重启它。
对于 CentOS 6 及更低版本(使用 init.d):
sudo service sshd status
sudo service sshd start
sudo chkconfig sshd on
sudo yum install monit
sudo service monit start
sudo chkconfig monit on
sudo vi /etc/monit/conf.d/sshd
check process sshd with pidfile /var/run/sshd/sshd.pid
start program = "/etc/init.d/sshd start"
stop program = "/etc/init.d/sshd stop"
if failed host 127.0.0.1 port 22 protocol ssh then restart
sudo service monit reload
现在,如果 SSH 服务意外停止,monit 将自动重启它。