Systemctl是systemd用於管理系統和管理服務的工具。許多現代Linux發行版,如Ubuntu、Debian、Fedora、Linux Mint、OpenSuSE、Redhat都采用systemd作為默認的init系統。 |
使用systemctl,可以啟動、停止、重新加載、重啟服務、列出服務單元、檢查服務狀態、啟用/禁用服務、管理運行級別和電源管理。在本文中將展示如何在Linux中使用systemctl命令來管理systemd服務。
使用systemctl啟動服務時,命令格式:systemctl start [service-name]
。例如,啟動firewalld服務:
[root@localhost ~]# systemctl start firewalld
與以前老版本的linux中的service
命令相反,systemctl start命令不輸出任何內容。
要停止服務,請使用systemctl stop [service-name]
。例如,停止firewalld服務:
[root@localhost ~]# systemctl stop firewalld
要重新啟動服務,請使用systemctl restart [service-name]
,例如:
[root@localhost ~]# systemctl restart firewalld
要重新加載服務的配置(例如ssh)而不重新啟動它,請使用systemctl reload [service-name]
,例如:
[root@localhost ~]# systemctl reload sshd
為了查看服務是否正在運行,我們可以使用systemctl status [service-name]
來查看。
[root@localhost ~]# systemctl status firewalld
要在引導時啟用服務,請使用systemctl enable [service-name]
,例如:
[root@localhost ~]# systemctl enable httpd.service Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.
同樣,disable時取消引導時啟用服務:
[root@localhost ~]# systemctl disable httpd.service
可以使用is-enabled選項檢查開機是否啟動該服務,請運行:
[root@localhost ~]# systemctl is-enabled httpd.service
輸出的內容enabled
表示開機時啟動該服務,disabled
表示開機時不啟動該服務。
要列出所有激活的單元,使用list-units
選項。
[root@localhost ~]# systemctl list-units
要列出所有活動的服務,請運行:
[root@localhost ~]# systemctl list-units -t service
像poweroff
、shutdown
命令一樣,systemctl命令可以關閉系統,重啟或進入休眠狀態。
關機:
[root@localhost ~]# systemctl poweroff
重啟:
[root@localhost ~]# systemctl reboot
系統休眠:
[root@localhost ~]# systemctl hibernate
通常,上述所有systemctl命令都可以用於通過systemctl命令本身管理遠程主機。這將使用ssh與遠程主機進行通信。如下所示:
[root@localhost ~]# systemctl status httpd -H root@192.168.0.12
-H
選項,指定遠程主機的用戶名和密碼。
Systemd具有Targets的概念,這些Targets的目的與sysVinit系統中的運行級別相似。sysVinit中的運行級別主要是數字(0,1,2,-6)。以下是sysVinit中的運行級別及其對應的systemd中的target:
0 runlevel0.target, poweroff.target 1 runlevel1.target, rescue.target 2,3,4 runlevel2.target, runlevel3.target,runlevel4.target, multi-user.target 5 runlevel5.target, graphical.target 6 runlevel6.target, reboot.target
如果想要查看當前的運行級別,可以使用如下命令:
[root@localhost ~]# systemctl get-default multi-user.target
設置默認的運行級別為graphical,命令如下:
[root@localhost ~]# systemctl set-default graphical.target Removed symlink /etc/systemd/system/default.target. Created symlink from /etc/systemd/system/default.target to /usr/lib/systemd/system/graphical.target.
想要列出所有激活的target,可以使用下面命令:
[root@localhost ~]# systemctl list-units -t target
systemd有自己的日志系統,稱為journald。它替換了sysVinit中的syslogd。
[root@localhost ~]# journalctl
要查看所有引導消息,請運行命令journalctl -b
[root@localhost ~]# journalctl -b
以下命令實時跟蹤系統日志(類似於tail -f):
[root@localhost ~]# journalctl -f
[root@localhost ~]# systemd-analyze Startup finished in 497ms (kernel) + 1.836s (initrd) + 6.567s (userspace) = 8.901s
最后顯示系統啟動時間為8.901秒。
查看服務的啟動時間:
[root@localhost ~]# systemd-analyze blame
查看主機名稱:
[root@localhost ~]# hostnamectl
在本文學習了systemctl命令來管理Linux發行版中的系統服務。