如何在 Linux 中避免意外关机或重启

在这个简短的教程中,让我们学习如何避免在 Linux 和类 Unix 操作系统中通过 SSH 会话意外关闭或重启 莫莉卫士 效用。

有时,您可能会忘记系统上正在运行未完成的作业并关闭或重新启动它。 结果? 正在运行的作业被终止,您必须从头开始重新开始作业。 虽然有办法 将正在运行的作业从一个终端移动到另一个终端,我们只是经常忘记事情。 后来,我们后悔没有小心翼翼。 好吧,不再! 今天,我遇到了一个救生工具,叫做 莫莉卫士,用于防止Linux系统意外关机或重启。

molly-guard 安装一个 shell 脚本,覆盖现有的 shutdown/reboot/halt/poweroff/coldreboot/pm-hibernate/pm-suspend* 命令并首先运行一组脚本,这些脚本都必须在 molly-guard 调用之前成功退出真正的命令。 其中一个脚本检查现有的 SSH 会话。 如果您通过 SSH 会话运行上述四个命令中的任何一个,shell 脚本会要求您输入要关闭或重新启动的主机的名称。 这应该足以防止您意外关机和重新启动。 molly-guard 将真正的二进制文件转移到 /lib/莫莉卫士/. 当然,您可以通过直接运行这些二进制文件来绕过 molly-guard。

在 Linux 中安装 molly-guard

molly-guard 在 Debian、Ubuntu 和其他基于 DEB 的系统(如 Linux Mint、Elementary OS 等)的默认存储库中可用。

要在基于 DEB 的系统上安装 molly-guard,请运行:

$ sudo apt-get install molly-guard

对于基于 RPM 的发行版, 下载 molly-guard.deb 包,并按照以下指南中的说明转换为本机 Linux 包。 在以下指南中,转到标题为 “将 RPM 转换为 DEB 包,反之亦然” 并将 molly-guard deb 包转换为 RPM 包。

  • 如何轻松为多个平台构建 Linux 包

使用 molly-guard 在 Linux 中避免意外关机或重启

是时候测试 molly-guard 实用程序了。

现在,尝试通过 SSH 关闭或重新启动远程系统或 vps:

 $ sudo poweroff
 W: molly-guard: SSH session detected!
 Please type in hostname of the machine to poweroff: ^C
 Good thing I asked; I won't poweroff ubuntuserver ...

看? molly-guard 正在询问我的 Ubuntu 服务器的主机名。 我打 CTRL+C 以避免关机。

同样,我尝试了所有命令来关闭电源,重新启动系统。 molly-guard 不断询问我的 Ubuntu 系统的主机名以便继续。

[email protected]:~$ sudo reboot 
W: molly-guard: SSH session detected!
Please type in hostname of the machine to reboot: ^C
Good thing I asked; I won't reboot ubuntuserver ...

[email protected]:~$ sudo shutdown -r now
W: molly-guard: SSH session detected!
Please type in hostname of the machine to shutdown: ^C
Good thing I asked; I won't shutdown ubuntuserver ...

[email protected]:~$ sudo shutdown -h now
W: molly-guard: SSH session detected!
Please type in hostname of the machine to shutdown: ^C
Good thing I asked; I won't shutdown ubuntuserver ...

[email protected]:~$ sudo halt
W: molly-guard: SSH session detected!
Please type in hostname of the machine to halt: ^C
Good thing I asked; I won't halt ubuntuserver ...

避免通过 SSH 会话意外关机或重启

如果您真的想关闭或重新启动系统,只需输入您的主机名。

W: molly-guard: SSH session detected!
Please type in hostname of the machine to halt: ubuntuserver
Connection to 192.168.43.2 closed by remote host.
Connection to 192.168.43.2 closed.

正如您在上面的输出中看到的,我输入了我的 Ubuntu 系统的主机名(例如 ubuntuserver)。 现在,molly-guard 知道我真的很想关闭我的系统,所以让它关闭。

好的 Linux 管理员和用户,不要遭受意外关机或重启的困扰。 将此实用程序保留在您的武器库中,以防止您的生产 Linux 系统意外关闭和重新启动。