如何在 Linux 服务器上的 CLI 和 GUI 之间切换
如果您的服务器启动到图形用户界面 (GUI),但出于安全和性能原因,您需要它启动到命令行界面 (CLI),您会怎么做?在过去,您会编辑文件/etc/inittab
,以便它启动到运行级别 3 (CLI),而不是启动到运行级别 5 (GUI)。然而,随着 systemd 系统管理器的出现,您必须做一些不同的事情。
首先,您不再使用运行级别术语。相反,您将引导选项称为目标。此场景的两个主要目标是多用户目标(CLI)和图形目标(GUI)。多用户目标可能与传统的运行级别 3 概念松散相关,而图形目标类似于运行级别 5。
可以手动切换目标,也可以配置自动或默认启动目标。本文旨在解释这两种选择。
确定当前目标
当您启动系统时,您可能很清楚哪个目标是默认目标。但是,要确认默认目标,请使用以下命令systemctl
以及get-default
子命令:
$ sudo systemctl get-default
结果可能会显示多用户.目标或图形.目标。
手动更改目标
您可以使用子命令在目标之间进行动态切换isolate
。也许您有一长串的管理任务,最简单的方法是在 GUI 中完成这些任务,但您的服务器启动到 CLI。您可以切换到 GUI,执行任务,然后将系统切换回更高效的 CLI。
以下是从 multi-user.target 启动 GUI 的命令:
$ sudo systemctl isolate graphical.target
通过使用以下命令指定 multi-user.target 来切换回来:
$ sudo systemctl isolate multi-user.target
这些命令对于当前运行时很有用,但是如何在系统启动时配置默认命令呢?
设置默认目标
默认目标表示系统首次启动时显示的界面。将服务器启动到 CLI 以提高效率和安全性是很常见的。CLI 消耗的资源少得多,包含的需要修补和担心的软件也更少。较新的管理员或从其他服务器平台迁移的管理员可能对Bash不够熟悉,无法在命令行上有效地工作。最终用户工作站很少启动到 CLI,因为用户通常需要基于图形的软件,例如生产力套件和 Web 浏览器。对于这些用户来说,性能损失值得获得便利。
Use the following systemctl
command to configure the default startup target as the CLI:
$ sudo systemctl set-default multi-user.target
Use the graphical.target argument to set the GUI as the default.
Try it
Try the following exercise if you have a systemd-based distribution available, such as Red Hat Enterprise Linux (RHEL).
Check the current default target:
$ sudo systemctl get-default
Switch to the opposite target (for example, if your system boots to the GUI, switch to the CLI):
$ sudo systemctl set-default multi-user.target
Reboot and confirm the appropriate target launched:
$ sudo systemctl reboot
Manually switch targets:
$ sudo systemctl isolate graphical.target
Configure the system back to the original target:
$ sudo systemctl set-default graphical.target
Reboot and then confirm the default target:
$ sudo systemctl reboot
If you don't have access to a system to experiment with, I encourage you to create a simple lab environment for these types of learning opportunities.
Understand target files
Targets are managed by .target files that simply group units and dependencies into a convenient format. It's really the .unit files that define exactly what services and other features start when the target is initiated. Enabling and disabling services and daemons adds and removes these components from the startup options:
$ sudo systemctl enable sshd
$ sudo systemctl disable sshd
Wrap up
This article covers the mechanics of identifying, switching, and setting targets on the system. These targets are managed via .target files. You can configure automatic startup options by using the set-default
subcommand or manually switch targets with the isolate
subcommand. I encourage you to walk through the exercise above; hands-on experience is essential for day-to-day administration and certification exams such as the Red Hat Certified System Administrator (RHCSA).