systemctl 命令詳解及使用教程

在本教程中, 我們將向您介紹在運行 systemd 的 linux 系統上如何使用 systemctl 命令工具有效的控制系統和服務.

Systemctl 介紹

Systemctl 是一個 systemd 工具,主要負責控制 systemd 系統和服務管理器。

Systemd 是一個系統管理守護進程、工具和庫的集合,用於取代 System V 初始進程。Systemd 的功能是用於集中管理和配置類 UNIX 系統。

在 Linux 生態系統中,Systemd 被部署到了大多數的標準 Linux 發行版中,只有爲數不多的幾個發行版尚未部署。Systemd 通常是所有其它守護進程的父進程,但並非總是如此。

開始 Systemd 和 Systemctl 基礎工具之旅

01、首先檢查系統上是否安裝了 systemd 以及當前安裝的 Systemd 的版本是什麼?

# systemd --version
systemd 215
+PAM +AUDIT +SELINUX +IMA +SYSVINIT +LIBCRYPTSETUP +GCRYPT +ACL +XZ -SECCOMP -APPARMOR

從上面的例子可以清楚地看出,我們已經安裝了 systemd 215 版本。

  1. 檢查 systemd 和 systemctl 的二進制文件和庫的安裝位置。
# whereis systemd 
systemd: /usr/lib/systemd /etc/systemd /usr/share/systemd /usr/share/man/man1/systemd.1.gz
# whereis systemctl
systemctl: /usr/bin/systemctl /usr/share/man/man1/systemctl.1.gz
  1. 檢查 systemd 是否正在運行。
# ps -eaf | grep [s]ystemd
root         1     0  0 16:27 ?        00:00:00 /usr/lib/systemd/systemd --switched-root --system --deserialize 23
root       444     1  0 16:27 ?        00:00:00 /usr/lib/systemd/systemd-journald
root       469     1  0 16:27 ?        00:00:00 /usr/lib/systemd/systemd-udevd
root       555     1  0 16:27 ?        00:00:00 /usr/lib/systemd/systemd-logind
dbus       556     1  0 16:27 ?        00:00:00 /bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation

注意:systemd 作爲父守護進程運行(PID = 1)。 在上面的命令 ps 中使用(-e)選擇所有進程,( - a)選擇除會話前導之外的所有進程和(-f)選擇完整格式列表(即 - eaf)。

另請注意上面示例中的方括號以及其他示例。 Square Bracket 表達式是 grep 的字符類模式匹配的一部分。

  1. 分析 systemd 啓動過程
# systemd-analyze
Startup finished in 487ms (kernel) + 2.776s (initrd) + 20.229s (userspace) = 23.493s
  1. 分析每個進程在引導時花費的時間
# systemd-analyze blame
8.565s mariadb.service
7.991s webmin.service
6.095s postfix.service
4.311s httpd.service
3.926s firewalld.service
3.780s kdump.service
3.238s tuned.service
1.712s network.service
1.394s lvm2-monitor.service
1.126s systemd-logind.service
....
  1. 分析啓動時的關鍵鏈
# systemd-analyze critical-chain
The time after the unit is active or started is printed after the "@" character.
The time the unit takes to start is printed after the "+" character.
multi-user.target @20.222s
└─mariadb.service @11.657s +8.565s
└─network.target @11.168s
└─network.service @9.456s +1.712s
└─NetworkManager.service @8.858s +596ms
└─firewalld.service @4.931s +3.926s
└─basic.target @4.916s
└─sockets.target @4.916s
└─dbus.socket @4.916s
└─sysinit.target @4.905s
└─systemd-update-utmp.service @4.864s +39ms
└─auditd.service @4.563s +301ms
└─systemd-tmpfiles-setup.service @4.485s +69ms
└─rhel-import-state.service @4.342s +142ms
└─local-fs.target @4.324s
└─boot.mount @4.286s +31ms
└─systemd-fsck@dev-disk-by\x2duuid-79f594ad\x2da332\x2d4730\x2dbb5f\x2d85d19608096
└─dev-disk-by\x2duuid-79f594ad\x2da332\x2d4730\x2dbb5f\x2d85d196080964.device @4

重要:Systemctl 接受服務(.service),掛載點(.mount),套接字(.socket)和設備(.device)作爲單位。

07、列出所有可用的單位

systemctl list-unit-files

UNIT FILE                                   STATE   
proc-sys-fs-binfmt_misc.automount           static  
dev-hugepages.mount                         static  
dev-mqueue.mount                            static  
proc-sys-fs-binfmt_misc.mount               static  
sys-fs-fuse-connections.mount               static  
sys-kernel-config.mount                     static  
sys-kernel-debug.mount                      static  
tmp.mount                                   disabled
brandbot.path                               disabled
.....

08、列出所有運行單元

# systemctl list-units
UNIT                                        LOAD   ACTIVE SUB       DESCRIPTION
proc-sys-fs-binfmt_misc.automount           loaded active waiting   Arbitrary Executable File Formats File Syste
sys-devices-pc...0-1:0:0:0-block-sr0.device loaded active plugged   VBOX_CD-ROM
sys-devices-pc...:00:03.0-net-enp0s3.device loaded active plugged   PRO/1000 MT Desktop Adapter
sys-devices-pc...00:05.0-sound-card0.device loaded active plugged   82801AA AC'97 Audio Controller
sys-devices-pc...:0:0-block-sda-sda1.device loaded active plugged   VBOX_HARDDISK
sys-devices-pc...:0:0-block-sda-sda2.device loaded active plugged   LVM PV Qzyo3l-qYaL-uRUa-Cjuk-pljo-qKtX-VgBQ8
sys-devices-pc...0-2:0:0:0-block-sda.device loaded active plugged   VBOX_HARDDISK
sys-devices-pl...erial8250-tty-ttyS0.device loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS0
sys-devices-pl...erial8250-tty-ttyS1.device loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS1
sys-devices-pl...erial8250-tty-ttyS2.device loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS2
sys-devices-pl...erial8250-tty-ttyS3.device loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS3
sys-devices-virtual-block-dm\x2d0.device    loaded active plugged   /sys/devices/virtual/block/dm-0
sys-devices-virtual-block-dm\x2d1.device    loaded active plugged   /sys/devices/virtual/block/dm-1
sys-module-configfs.device                  loaded active plugged   /sys/module/configfs
...

09、列出所有失敗的單元

# systemctl --failed

UNIT          LOAD   ACTIVE SUB    DESCRIPTION
kdump.service loaded failed failed Crash recovery kernel arming
LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.
1 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

10、檢查單元 (cron.service) 是否啓用?

# systemctl is-enabled crond.service
enabled
  1. 檢查單元或服務是否正在運行?
 systemctl status firewalld.service
firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
Active: active (running) since Tue 2018-04-28 16:27:55 IST; 34min ago
Main PID: 549 (firewalld)
CGroup: /system.slice/firewalld.service
└─549 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
Apr 28 16:27:51 tecmint systemd[1]: Starting firewalld - dynamic firewall daemon...
Apr 28 16:27:55 tecmint systemd[1]: Started firewalld - dynamic firewall daemon.
  1. 列出所有服務(包括啓用和禁用)
# systemctl list-unit-files --type=service
UNIT FILE                                   STATE   
arp-ethers.service                          disabled
auditd.service                              enabled 
autovt@.service                             disabled
blk-availability.service                    disabled
brandbot.service                            static  
collectd.service                            disabled
console-getty.service                       disabled
console-shell.service                       disabled
cpupower.service                            disabled
crond.service                               enabled 
dbus-org.fedoraproject.FirewallD1.service   enabled 
....
  1. 如何在 Linux 中啓動,重新啓動,停止,重新加載和檢查服務(httpd.service)的狀態
# systemctl start httpd.service
# systemctl restart httpd.service
# systemctl stop httpd.service
# systemctl reload httpd.service
# systemctl status httpd.service
httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
Active: active (running) since Tue 2018-04-28 17:21:30 IST; 6s ago
Process: 2876 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
Main PID: 2881 (httpd)
Status: "Processing requests..."
CGroup: /system.slice/httpd.service
├─2881 /usr/sbin/httpd -DFOREGROUND
├─2884 /usr/sbin/httpd -DFOREGROUND
├─2885 /usr/sbin/httpd -DFOREGROUND
├─2886 /usr/sbin/httpd -DFOREGROUND
├─2887 /usr/sbin/httpd -DFOREGROUND
└─2888 /usr/sbin/httpd -DFOREGROUND
Apr 28 17:21:30 tecmint systemd[1]: Starting The Apache HTTP Server...
Apr 28 17:21:30 tecmint httpd[2881]: AH00558: httpd: Could not reliably determine the server's fully q...ssage
Apr 28 17:21:30 tecmint systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.

注意:當我們使用 systemctl 等啓動,重啓,停止和重載等命令時,我們將不會在終端上獲得任何輸出,只有 status 命令會打印輸出。

  1. 如何在引導時激活服務並啓用或禁用服務(系統引導時自動啓動服務)
# systemctl is-active httpd.service
# systemctl enable httpd.service
# systemctl disable httpd.service
  1. 如何屏蔽(使其無法啓動)或取消屏蔽服務(httpd.service)
ln -s '/dev/null' '/etc/systemd/system/httpd.service'
# systemctl unmask httpd.service
rm '/etc/systemd/system/httpd.service'
  1. 如何使用 systemctl 命令終止服務
# systemctl kill httpd
# systemctl status httpd
httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
Active: failed (Result: exit-code) since Tue 2018-04-28 18:01:42 IST; 28min ago
Main PID: 2881 (code=exited, status=0/SUCCESS)
Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
Apr 28 17:37:29 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:29 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:39 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:39 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:49 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:49 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:59 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 17:37:59 tecmint systemd[1]: httpd.service: Got notification message from PID 2881, but recepti...bled.
Apr 28 18:01:42 tecmint systemd[1]: httpd.service: control process exited, code=exited status=226
Apr 28 18:01:42 tecmint systemd[1]: Unit httpd.service entered failed state.
Hint: Some lines were ellipsized, use -l to show in full.

使用 Systemctl 控制和管理掛載點

  1. 列出所有系統安裝點
# systemctl list-unit-files --type=mount
UNIT FILE                     STATE   
dev-hugepages.mount           static  
dev-mqueue.mount              static  
proc-sys-fs-binfmt_misc.mount static  
sys-fs-fuse-connections.mount static  
sys-kernel-config.mount       static  
sys-kernel-debug.mount        static  
tmp.mount                     disabled
  1. 如何裝載,卸載,重新裝載,重新裝載系統裝載點,以及檢查系統上裝載點的狀態
# systemctl start tmp.mount
# systemctl stop tmp.mount
# systemctl restart tmp.mount
# systemctl reload tmp.mount
# systemctl status tmp.mount
tmp.mount - Temporary Directory
Loaded: loaded (/usr/lib/systemd/system/tmp.mount; disabled)
Active: active (mounted) since Tue 2018-04-28 17:46:06 IST; 2min 48s ago
Where: /tmp
What: tmpfs
Docs: man:hier(7)
http://www.freedesktop.org/wiki/Software/systemd/APIFileSystems
Process: 3908 ExecMount=/bin/mount tmpfs /tmp -t tmpfs -o mode=1777,strictatime (code=exited, status=0/SUCCESS)
Apr 28 17:46:06 tecmint systemd[1]: Mounting Temporary Directory...
Apr 28 17:46:06 tecmint systemd[1]: tmp.mount: Directory /tmp to mount over is not empty, mounting anyway.
Apr 28 17:46:06 tecmint systemd[1]: Mounted Temporary Directory.
  1. 如何在引導時激活,啓用或禁用裝入點(在系統引導時自動裝入)
# systemctl is-active tmp.mount
# systemctl enable tmp.mount
# systemctl disable  tmp.mount
  1. 如何在 Linux 中屏蔽(使其無法啓動)或取消屏蔽掛載點
# systemctl mask tmp.mount
ln -s '/dev/null' '/etc/systemd/system/tmp.mount'
# systemctl unmask tmp.mount
rm '/etc/systemd/system/tmp.mount'

使用 Systemctl 控制和管理套接字

  1. 列出所有可用的系統套接字。
# systemctl list-unit-files --type=socket
UNIT FILE                    STATE   
dbus.socket                  static  
dm-event.socket              enabled 
lvm2-lvmetad.socket          enabled 
rsyncd.socket                disabled
sshd.socket                  disabled
syslog.socket                static  
systemd-initctl.socket       static  
systemd-journald.socket      static  
systemd-shutdownd.socket     static  
systemd-udevd-control.socket static  
systemd-udevd-kernel.socket  static  
11 unit files listed.
  1. 如何在 Linux 中啓動,重新啓動,停止,重新加載和檢查套接字的狀態(例如:cups.socket)
# systemctl start cups.socket
# systemctl restart cups.socket
# systemctl stop cups.socket
# systemctl reload cups.socket
# systemctl status cups.socket
cups.socket - CUPS Printing Service Sockets
Loaded: loaded (/usr/lib/systemd/system/cups.socket; enabled)
Active: active (listening) since Tue 2015-04-28 18:10:59 IST; 8s ago
Listen: /var/run/cups/cups.sock (Stream)
Apr 28 18:10:59 tecmint systemd[1]: Starting CUPS Printing Service Sockets.
Apr 28 18:10:59 tecmint systemd[1]: Listening on CUPS Printing Service Sockets.
  1. 如何激活套接字並在引導時啓用或禁用(在系統引導時自動啓動套接字)
# systemctl is-active cups.socket
# systemctl enable cups.socket
# systemctl disable cups.socket
  1. 如何屏蔽(使其無法啓動)或取消屏蔽插座(cups.socket)
# systemctl mask cups.socket
ln -s '/dev/null' '/etc/systemd/system/cups.socket'
# systemctl unmask cups.socket
rm '/etc/systemd/system/cups.socket'

服務的 CPU 利用率(份額)

  1. 獲取服務的當前 CPU 份額(比如 httpd)
# systemctl show -p CPUShares httpd.service
CPUShares=1024

注意:每個服務的默認值都爲 CPUShare = 1024. 您可以增加 / 減少進程的 CPU 份額。

  1. 將服務的 CPU 份額(httpd.service)限制爲 2000 CPUShares /
# systemctl set-property httpd.service CPUShares=2000
# systemctl show -p CPUShares httpd.service
CPUShares=2000

注意:爲服務設置 CPUShare 時,會創建一個名爲 service 的目錄(httpd.service.d),其中包含一個包含 CPUShare Limit 信息的文件 90-CPUShares.conf。 您可以將文件視爲:

# vi /etc/systemd/system/httpd.service.d/90-CPUShares.conf 
[Service]
CPUShares=2000
  1. 檢查服務的所有配置詳細信息
# systemctl show httpd
Id=httpd.service
Names=httpd.service
Requires=basic.target
Wants=system.slice
WantedBy=multi-user.target
Conflicts=shutdown.target
Before=shutdown.target multi-user.target
After=network.target remote-fs.target nss-lookup.target systemd-journald.socket basic.target system.slice
Description=The Apache HTTP Server
LoadState=loaded
ActiveState=active
SubState=running
FragmentPath=/usr/lib/systemd/system/httpd.service
....
  1. 分析服務的關鍵鏈(httpd)
# systemd-analyze critical-chain httpd.service
The time after the unit is active or started is printed after the "@" character.
The time the unit takes to start is printed after the "+" character.
httpd.service +142ms
└─network.target @11.168s
└─network.service @9.456s +1.712s
└─NetworkManager.service @8.858s +596ms
└─firewalld.service @4.931s +3.926s
└─basic.target @4.916s
└─sockets.target @4.916s
└─dbus.socket @4.916s
└─sysinit.target @4.905s
└─systemd-update-utmp.service @4.864s +39ms
└─auditd.service @4.563s +301ms
└─systemd-tmpfiles-setup.service @4.485s +69ms
└─rhel-import-state.service @4.342s +142ms
└─local-fs.target @4.324s
└─boot.mount @4.286s +31ms
└─systemd-fsck@dev-disk-by\x2duuid-79f594ad\x2da332\x2d4730\x2dbb5f\x2d85d196080964.service @4.092s +149ms
└─dev-disk-by\x2duuid-79f594ad\x2da332\x2d4730\x2dbb5f\x2d85d196080964.device @4.092s
  1. 獲取服務的依賴項列表(httpd)
# systemctl list-dependencies httpd.service
httpd.service
├─system.slice
└─basic.target
├─firewalld.service
├─microcode.service
├─rhel-autorelabel-mark.service
├─rhel-autorelabel.service
├─rhel-configure.service
├─rhel-dmesg.service
├─rhel-loadmodules.service
├─paths.target
├─slices.target
│ ├─-.slice
│ └─system.slice
├─sockets.target
│ ├─dbus.socket
....
  1. 按層次列出控制組
# systemd-cgls
├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 23
├─user.slice
│ └─user-0.slice
│   └─session-1.scope
│     ├─2498 sshd: root@pts/0    
│     ├─2500 -bash
│     ├─4521 systemd-cgls
│     └─4522 systemd-cgls
└─system.slice
├─httpd.service
│ ├─4440 /usr/sbin/httpd -DFOREGROUND
│ ├─4442 /usr/sbin/httpd -DFOREGROUND
│ ├─4443 /usr/sbin/httpd -DFOREGROUND
│ ├─4444 /usr/sbin/httpd -DFOREGROUND
│ ├─4445 /usr/sbin/httpd -DFOREGROUND
│ └─4446 /usr/sbin/httpd -DFOREGROUND
├─polkit.service
│ └─721 /usr/lib/polkit-1/polkitd --no-debug
....
  1. 根據 CPU,內存,輸入和輸出列出控制組
# systemd-cgtop
Path                                                              Tasks   %CPU   Memory  Input/s Output/s
/                                                                    83    1.0   437.8M        -        -
/system.slice                                                         -    0.1        -        -        -
/system.slice/mariadb.service                                         2    0.1        -        -        -
/system.slice/tuned.service                                           1    0.0        -        -        -
/system.slice/httpd.service                                           6    0.0        -        -        -
/system.slice/NetworkManager.service                                  1      -        -        -        -
/system.slice/atop.service                                            1      -        -        -        -
/system.slice/atopacct.service                                        1      -        -        -        -
/system.slice/auditd.service                                          1      -        -        -        -
/system.slice/crond.service                                           1      -        -        -        -
/system.slice/dbus.service                                            1      -        -        -        -
/system.slice/firewalld.service                                       1      -        -        -        -
/system.slice/lvm2-lvmetad.service                                    1      -        -        -        -
/system.slice/polkit.service                                          1      -        -        -        -
/system.slice/postfix.service                                         3      -        -        -        -
/system.slice/rsyslog.service                                         1      -        -        -        -
/system.slice/system-getty.slice/getty@tty1.service                   1      -        -        -        -
/system.slice/systemd-journald.service                                1      -        -        -        -
/system.slice/systemd-logind.service                                  1      -        -        -        -
/system.slice/systemd-udevd.service                                   1      -        -        -        -
/system.slice/webmin.service                                          1      -        -        -        -
/user.slice/user-0.slice/session-1.scope                              3      -        -        -        -

控制系統運行級別

  1. 如何啓動系統救援模式
# systemctl rescue
Broadcast message from root@tecmint on pts/0 (Wed 2015-04-29 11:31:18 IST):
The system is going down to rescue mode NOW!
  1. 如何進入緊急模式。
# systemctl emergency
Welcome to emergency mode! After logging in, type "journalctl -xb" to view
system logs, "systemctl reboot" to reboot, "systemctl default" to try again
to boot into default mode.
  1. 列出當前使用的運行級別
# systemctl get-default
multi-user.target
  1. 如何啓動 Runlevel 5 aka 圖形模式。
# systemctl isolate runlevel5.target
OR
# systemctl isolate graphical.target
  1. 如何啓動 Runlevel 3 又稱多用戶模式(命令行)
# systemctl isolate runlevel3.target
OR
# systemctl isolate multiuser.target
  1. 如何將多用戶模式或圖形模式設置爲默認運行級別
# systemctl set-default runlevel3.target
# systemctl set-default runlevel5.target
  1. 如何重啓,暫停,暫停,休眠或將系統置於混合睡眠狀態
# systemctl reboot
# systemctl halt
# systemctl suspend
# systemctl hibernate
# systemctl hybrid-sleep

對於那些可能不瞭解跑步水平及其作用的人。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/lQHU-Gsm9xwoKWTUOijBDw