Systemctl和Unit file

Systemctl和Unit file的常见用法与区别

Systemctl基础

1、首先检查你的系统中是否安装有systemd并确定当前安装的版本

[root@servergroup ~]# systemctl --version
systemd 239
+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN2 -IDN +PCRE2 default-hierarchy=legacy

2、检查systemd和systemctl的二进制文件和库文件的安装位置

[root@servergroup ~]#  whereis systemd
systemd: /usr/lib/systemd /etc/systemd /usr/share/systemd /usr/share/man/man1/systemd.1.gz

3、 分析启动时各个进程花费的时间

[root@servergroup ~]# systemd-analyze blame
         22.243s dnf-makecache.service
          6.324s NetworkManager-wait-online.service
          4.585s tuned.service
          1.881s php-fpm.service
          1.611s vdo.service
          1.563s sssd.service
          1.536s firewalld.service
          1.434s dracut-initqueue.service
          1.399s lvm2-monitor.service
          1.023s httpd.service
           950ms polkit.service
           785ms initrd-switch-root.service
           549ms systemd-udev-trigger.service
           498ms chronyd.service
           426ms zabbix-agent.service
           423ms lvm2-pvscan@8:2.service
           341ms systemd-vconsole-setup.service
           270ms systemd-user-sessions.service
           246ms user@0.service
           232ms sshd.service
           206ms NetworkManager.service
           203ms boot.mount
           198ms kmod-static-nodes.service
           193ms systemd-journald.service
           183ms dev-mapper-cl/x2dswap.swap
           182ms nis-domainname.service
           177ms dev-mqueue.mount
           172ms plymouth-quit-wait.servic

4 分析启动时的关键链

[root@servergroup ~]# 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 @11.968s
└─rsyslog.service @11.872s +96ms
  └─network-online.target @11.861s
    └─NetworkManager-wait-online.service @5.536s +6.324s
      └─NetworkManager.service @5.325s +206ms
        └─network-pre.target @5.322s
          └─firewalld.service @3.784s +1.536s
            └─polkit.service @2.829s +950ms
              └─basic.target @2.724s
                └─sockets.target @2.724s
                  └─dbus.socket @2.724s
                    └─sysinit.target @2.721s
                      └─systemd-update-utmp.service @2.711s +9ms
                        └─auditd.service @2.652s +57ms
                          └─systemd-tmpfiles-setup.service @2.609s +42ms
                            └─import-state.service @2.550s +56ms
                              └─local-fs.target @2.549s
                                └─boot.mount @2.346s +203ms
                                  └─systemd-fsck@dev-disk-by/x2duuid-709a568a/x2d6be7/x2d4f96/x2da343/x2d2cad0cdbf3>
                                    └─local-fs-pre.target @2.204s
                                      └─lvm2-monitor.service @804ms +1.399s
                                        └─dm-event.socket @752ms
                                          └─-.mount
                                            └─system.slice
                                              └─-.slice

重要:Systemctl接受服务(.service),挂载点(.mount),套接口(.socket)和设备(.device)作为单元。

5. 列出所有可用单元

[root@servergroup ~]# systemctl list-unit-files
UNIT FILE                                   STATE    
proc-sys-fs-binfmt_misc.automount           static   
-.mount                                     generated
boot.mount                                  generated
dev-hugepages.mount                         static   
dev-mqueue.mount                            static   
home.mount                                  generated
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                                   static   
systemd-ask-password-console.path           static   
systemd-ask-password-plymouth.path          static   
systemd-ask-password-wall.path              static   
session-1.scope                             transient
arp-ethers.service                          disabled 
atd.service                                 enabled  
auditd.service                              enabled  
autovt@.service                             enabled  
blk-availability.service                    disabled 
chrony-dn***v@.service                      static   
chrony-wait.service                         disabled 
chronyd.service                             enabled  

…………………………

6. 列出所有运行中单元

  1. [root@servergroup ~]# systemctl list-units UNIT LOAD ACTIVE SUB DESCRIPTION proc-sys-fs-binfmt_misc.automount loaded active waiting Arbitrary Executable File> sys-devices-pci0000:00-0000:00:07.1-ata2-host1-target1:0:0-1:0:0:0-block-sr0.device loaded active plugged > sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda1.device loaded active plugged > sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda2.device loaded active plugged > sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda.device loaded active plugged VMw> sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb-sdb1.device loaded active plugged > sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb-sdb2.device loaded active plugged > sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb.device loaded active plugged VMw> sys-devices-pci0000:00-0000:00:11.0-0000:02:00.0-net-ens32.device loaded active plugged 82545EM Gigabit > sys-devices-platform-serial8250-tty-ttyS0.device loaded active plugged /sys/devices/platform/ser> sys-devices-platform-serial8250-tty-ttyS1.device loaded active plugged /sys/devices/platform/ser> sys-devices-platform-serial8250-tty-ttyS2.device loaded active plugged /sys/devices/platform/ser> sys-devices-platform-serial8250-tty-ttyS3.device loaded active plugged /sys/devices/platform/ser> sys-devices-virtual-block-dm/x2d0.device loaded active plugged /sys/devices/virtual/bloc> sys-devices-virtual-block-dm/x2d1.device loaded active plugged /sys/devices/virtual/bloc> sys-devices-virtual-block-dm/x2d2.device loaded active plugged /sys/devices/virtual/bloc> sys-module-configfs.device loaded active plugged /sys/module/configfs sys-subsystem-net-devices-ens32.device loaded active plugged 82545EM Gigabit Ethernet
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.

7. 列出所有失败单元

[root@servergroup ~]# 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'.

8. 检查某个单元(如 sshd.service)是否启用

[root@servergroup ~]# systemctl is-enabled sshd.service
enabled

使用Systemctl控制并管理服务

9. 列出所有服务(包括启用的和禁用的)

To show all installed unit files use 'systemctl list-unit-files'.
[root@servergroup ~]#  systemctl list-unit-files --type=service 
UNIT FILE                                   STATE   
arp-ethers.service                          disabled
atd.service                                 enabled 
auditd.service                              enabled 
autovt@.service                             enabled 
blk-availability.service                    disabled
chrony-dn***v@.service                      static  
chrony-wait.service                         disabled
chronyd.service                             enabled 
cockpit-motd.service                        static  
cockpit.service                             static  
console-getty.service                       disabled
container-getty@.service                    static  
cpupower.service                            disabled
crond.service                               enabled 
dbus-org.fedoraproject.FirewallD1.service   enabled 
dbus-org.freedesktop.hostname1.service      static  
dbus-org.freedesktop.locale1.service        static  
dbus-org.freedesktop.login1.service         static  
dbus-org.freedesktop.NetworkManager.service enabled 
dbus-org.freedesktop.nm-dispatcher.service  enabled 
dbus-org.freedesktop.portable1.service      static  
dbus-org.freedesktop.timedate1.service      enabled 
dbus.service                                static  

10. Linux中如何启动、重启、停止、重载服务以及检查服务(如chronyd.service)状态

[root@servergroup ~]#  systemctl start chronyd.service
[root@servergroup ~]#  systemctl restart chronyd.service
[root@servergroup ~]#  systemctl stop  chronyd.service
[root@servergroup ~]#  systemctl status  chronyd.service
● chronyd.service - NTP client/server
   Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Sat 2021-07-17 22:49:25 CST; 5s ago
     Docs: man:chronyd(8)
           man:chrony.conf(5)
  Process: 3379 ExecStartPost=/usr/libexec/chrony-helper update-daemon (code=exited, status=0/SUCCESS)
  Process: 3375 ExecStart=/usr/sbin/chronyd $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 3377 (code=exited, status=0/SUCCESS)

Jul 17 22:49:19 servergroup systemd[1]: Stopped NTP client/server.
Jul 17 22:49:19 servergroup systemd[1]: Starting NTP client/server...
Jul 17 22:49:19 servergroup chronyd[3377]: chronyd version 3.3 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCF>
Jul 17 22:49:19 servergroup chronyd[3377]: Frequency 4.010 +/- 1.814 ppm read from /var/lib/chrony/drift
Jul 17 22:49:19 servergroup chronyd[3377]: Using right/UTC timezone to obtain leap second data
Jul 17 22:49:19 servergroup systemd[1]: Started NTP client/server.
Jul 17 22:49:25 servergroup systemd[1]: Stopping NTP client/server...
Jul 17 22:49:25 servergroup systemd[1]: Stopped NTP client/server.

注意:当我们使用systemctl的start,restart,stop和reload命令时,我们不会从终端获取到任何输出内容,只有status命令可以打印输出。

11. 如何激活服务并在启动时启用或禁用服务(即系统启动时自动启动服务)

[root@servergroup ~]# systemctl is-active chronyd.service 
active
[root@servergroup ~]# systemctl disable chronyd.service 
Removed /etc/systemd/system/multi-user.target.wants/chronyd.service.
[root@servergroup ~]# systemctl enable chronyd.service 
Created symlink /etc/systemd/system/multi-user.target.wants/chronyd.service → /usr/lib/systemd/system/chronyd.service.

12. 如何屏蔽(让它不能启动)或显示服务(如 chronyd.service)

[root@servergroup ~]# systemctl mask chronyd.service 
Created symlink /etc/systemd/system/chronyd.service → /dev/null.
[root@servergroup ~]# systemctl unmask chronyd.service 
Removed /etc/systemd/system/chronyd.service.

13. 使用systemctl命令杀死服务

[root@servergroup ~]# systemctl kill chronyd
[root@servergroup ~]# systemctl status chronyd.service 
● chronyd.service - NTP client/server
   Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Sat 2021-07-17 22:51:55 CST; 5s ago
     Docs: man:chronyd(8)
           man:chrony.conf(5)
 Main PID: 3413 (code=exited, status=0/SUCCESS)

Jul 17 22:49:49 servergroup systemd[1]: Starting NTP client/server...
Jul 17 22:49:49 servergroup chronyd[3413]: chronyd version 3.3 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCF>
Jul 17 22:49:49 servergroup chronyd[3413]: Frequency 4.010 +/- 1.814 ppm read from /var/lib/chrony/drift
Jul 17 22:49:49 servergroup chronyd[3413]: Using right/UTC timezone to obtain leap second data
Jul 17 22:49:49 servergroup systemd[1]: Started NTP client/server.
Jul 17 22:49:58 servergroup chronyd[3413]: Selected source 69.89.207.199
Jul 17 22:49:58 servergroup chronyd[3413]: System clock TAI offset set to 37 seconds

使用Systemctl控制并管理挂载点

14. 列出所有系统挂载点

[root@servergroup ~]# systemctl list-unit-files --type=mount
UNIT FILE                     STATE    
-.mount                       generated
boot.mount                    generated
dev-hugepages.mount           static   
dev-mqueue.mount              static   
home.mount                    generated
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                     static   

15. 在启动时激活、启用或禁用挂载点(系统启动时自动挂载)

systemctl is-active tmp.mount
systemctl enable tmp.mount
systemctl disable tmp.mount

使用Systemctl控制并管理套接口

16. 列出所有可用系统套接口

[root@servergroup ~]# systemctl list-unit-files --type=socket
UNIT FILE                       STATE   
cockpit.socket                  disabled
dbus.socket                     static  
dm-event.socket                 enabled 
httpd.socket                    disabled
lvm2-lvmpolld.socket            enabled 
sshd.socket                     disabled
sssd-autofs.socket              disabled
sssd-kcm.socket                 enabled 
sssd-nss.socket                 disabled
sssd-pac.socket                 disabled
sssd-pam-priv.socket            disabled
sssd-pam.socket                 disabled
sssd-ssh.socket                 disabled
sssd-sudo.socket                disabled
syslog.socket                   static  
systemd-coredump.socket         static  
systemd-initctl.socket          static  
systemd-journald-dev-log.socket static  
systemd-journald.socket         static  
systemd-rfkill.socket           static  
systemd-udevd-control.socket    static  
systemd-udevd-kernel.socket     static  

17. 在Linux中启动、重启、停止、重载套接口并检查其状态

[root@servergroup ~]#systemctl start cups.socket
[root@servergroup ~]#systemctl restart cups.socket
[root@servergroup ~]#systemctl stop cups.socket
[root@servergroup ~]#systemctl reload cups.socket
[root@servergroup ~]#systemctl status cups.socket

18. 在启动时激活套接口,并启用或禁用它(系统启动时自启动)

[root@servergroup ~]#systemctl is-active cockpit.socket
[root@servergroup ~]#systemctl enable cockpit.socket
[root@servergroup ~]#systemctl disable cockpit.socket

服务的CPU利用率(分配额)

19. 获取当前某个服务的CPU分配额(如chronyd)

[root@servergroup ~]# systemctl show -p CPUShares chronyd.service 
CPUShares=[not set]

注意:各个服务的默认CPU分配份额=1024,你可以增加/减少某个进程的CPU分配份额。

20. 将某个服务(chronyd.service)的CPU分配份额限制为2000 CPUShares

[root@servergroup ~]# systemctl set-property chronyd.service CPUShares=2000
[root@servergroup ~]# 
[root@servergroup ~]# systemctl show -p CPUShares chronyd.service 
CPUShares=2000

21. 检查某个服务的所有配置细节

[root@servergroup ~]# systemctl show chrondy
Restart=no
NotifyAccess=none
RestartUSec=100ms
TimeoutStartUSec=1min 30s
TimeoutStopUSec=1min 30s
RuntimeMaxUSec=infinity
WatchdogUSec=0
WatchdogTimestampMonotonic=0
PermissionsStartOnly=no
RootDirectoryStartOnly=no
RemainAfterExit=no
GuessMainPID=yes
MainPID=0
ControlPID=0
FileDescriptorStoreMax=0
NFileDescriptorStore=0
StatusErrno=0
Result=success
UID=[not set]
GID=[not set]
NRestarts=0
ExecMainStartTimestampMonotonic=0
ExecMainExitTimestampMonotonic=0
ExecMainPID=0

22. 分析某个服务(chronyd)的关键链

[root@servergroup ~]# systemd-analyze critical-chain chronyd.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.

chronyd.service +32ms
└─basic.target @2.724s
  └─sockets.target @2.724s
    └─dbus.socket @2.724s
      └─sysinit.target @2.721s
        └─systemd-update-utmp.service @2.711s +9ms
          └─auditd.service @2.652s +57ms
            └─systemd-tmpfiles-setup.service @2.609s +42ms
              └─import-state.service @2.550s +56ms
                └─local-fs.target @2.549s
                  └─boot.mount @2.346s +203ms
                    └─systemd-fsck@dev-disk-by/x2duuid-709a568a/x2d6be7/x2d4f96/x2da343/x2d2cad0cdbf399.service @2.>
                      └─local-fs-pre.target @2.204s
                        └─lvm2-monitor.service @804ms +1.399s
                          └─dm-event.socket @752ms
                            └─-.mount
                              └─system.slice
                                └─-.slice

23. 获取某个服务(chronyd)的依赖性列表

[root@servergroup ~]# systemctl list-dependencies chronyd.service 
chronyd.service
● ├─-.mount
● ├─system.slice
● └─sysinit.target
●   ├─dev-hugepages.mount
●   ├─dev-mqueue.mount
●   ├─dracut-shutdown.service
●   ├─import-state.service
●   ├─kmod-static-nodes.service
●   ├─ldconfig.service
●   ├─loadmodules.service
●   ├─lvm2-lvmpolld.socket
●   ├─lvm2-monitor.service
●   ├─nis-domainname.service
●   ├─plymouth-read-write.service
●   ├─plymouth-start.service
●   ├─proc-sys-fs-binfmt_misc.automount
●   ├─rngd.service

24. 按等级列出控制组

root@servergroup ~]# systemd-cgls 
Control group /:
-.slice
├─user.slice
│ └─user-0.slice
│   ├─session-1.scope
│   │ ├─1696 sshd: root [priv]
│   │ ├─1722 sshd: root@pts/0,pts/1
│   │ ├─1723 -bash
│   │ ├─1744 man systemctl
│   │ ├─1754 less
│   │ ├─2184 -bash
│   │ ├─4484 systemd-cgls
│   │ └─4485 systemd-cgls
│   └─user@0.service
│     └─init.scope
│       ├─1706 /usr/lib/systemd/systemd --user
│       └─1713 (sd-pam)
├─init.scope
│ └─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 17
└─system.slice

控制系统运行等级

25. 启动系统救援模式

[root@servergroup ~]#systemctl rescue

26. 进入紧急模式

[root@servergroup ~]# systemctl emergency

27 列出当前使用的运行等级

[root@servergroup ~]# systemctl get-default 
multi-user.target

28. 启动运行等级3,即多用户模式(命令行)

[root@servergroup ~]# systemctl isolate multi-user.target 

29. 设置多用户模式或图形模式为默认运行等级

[root@servergroup ~]# systemctl set-default multi-user.target 

30. 重启、停止、挂起、休眠系统或使系统进入混合睡眠

[root@servergroup ~]# systemctl reboot
[root@servergroup ~]# systemctl halt
[root@servergroup ~]# systemctl suspend
[root@servergroup ~]# systemctl hibernate
[root@servergroup ~]# systemctl hybrid-sleep

Unit file的介绍

Service 段
主要字段如下:

【启动类型】

Type:                     定义启动时的进程行为。它有以下几种值。
Type=simple:        默认值,ExecStart字段启动的进程为主进程服务进程不会 fork,如果该服务要启动其他服务,不要使用此类型启动,除非该服务是 socket 激活型
Type=forking:       ExecStart字段将以fork()方式从父进程创建子进程启动,创建后父进程会立即退出,子进程成为主进程。通常需要指定PIDFile字段,以便 Systemd 能够跟踪服务的主进程对于常规的守护进程(daemon),除非你确定此启动方式无法满足需求,使用此类型启动即可
Type=oneshot:     只执行一次,Systemd 会等当前服务退出,再继续往下执行适用于只执行一项任务、随后立即退出的服务通常需要指定RemainAfterExit=yes字段,使得 Systemd 在服务进程退出之后仍然认为服务处于激活状态
Type=dbus:          当前服务通过 D-Bus 信号启动。当指定的 BusName 出现在 DBus 系统总线上时,Systemd认为服务就绪
Type=notify:         当前服务启动完毕会发出通知信号,通知 Systemd,然后 Systemd 再启动其他服务
Type=idle:             Systemd 会等到其他任务都执行完,才会启动该服务。一种使用场合是:让该服务的输出,不与其他服务的输出相混合
【启动行为】

ExecStart:              启动当前服务的命令

ExecStart=/bin/echo execstart1
ExecStart=
ExecStart=/bin/echo execstart2
顺序执行设定的命令,把字段置空,表示清除之前的值

ExecStartPre:        启动当前服务之前执行的命令

ExecStartPost:      启动当前服务之后执行的命令

ExecReload:         重启当前服务时执行的命令

ExecStop:             停止当前服务时执行的命令

ExecStopPost:      停止当前服务之后执行的命令

RemainAfterExit:当前服务的所有进程都退出的时候,Systemd 仍认为该服务是激活状态

参考文献:

©著作权归作者所有:来自51CTO博客作者Happy_Future的原创作品

Systemctl和Unit file
https://blog.51cto.com/u_15131458/3119541

给TA打赏
共{{data.count}}人
人已打赏
开发数据库电脑运维

js报错TypeError: Cannot find function match in object

2023-9-14 22:34:58

开发数据库电脑运维

Steam 更新游戏 PUBG 时提示可用磁盘空间不足的解决方法 无需卸载并重新下载游戏

2023-9-15 0:57:34

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索