linux系统命令systemctl详解,管理系统服务的工具-控制systemd、管理unit、启动或禁止服务
目录
一、systemctl命令介绍
systemctl命令是Linux操作系统中用于管理系统服务的命令行工具,尤其在RHEL 7及更高版本上,它替代了之前的service和chkconfig命令,将两者的功能整合在一起。systemctl的主要功能包括查询或发送相应的控制命令给systemd、管理unit以及启动或禁止相应的服务等。
只有在CentOS 7及以上版本中才能使用systemctl命令来管理系统和服务。在早期的CentOS版本中,如CentOS 6及以下版本,使用的是SysV init系统,管理系统和服务的命令是service和chkconfig。
二、命令语法
1、基本语法
systemctl命令的基本语法为:
systemctl [OPTIONS...] COMMAND [UNIT]
其中OPTIONS是可选参数,用于指定systemctl的行为;COMMAND是必需参数,用于执行特定的systemd命令,例如启动、停止或重新启动服务;UNIT是可选参数,用于指定要操作的服务或单元。
2、常用选项
systemctl命令的一些常用选项包括:
`-H,--host`:指定要在远程主机上运行的systemd实例的主机名或IP地址。
`-a,--all`: 显示所有已加载的单位,而不仅仅是当前活动的单位。
`-t,--type`:根据指定的单元类型筛选单元列表,支持的单元类型包括service、socket、mount等。
`-u,--user`:执行与当前用户相关联的用户级服务。
3、常用操作
systemctl命令的一些常用操作包括:
(1)停止服务:使用`systemctl stop`命令,后跟服务名称,如`systemctl stop nginx.service`,这将停止名为nginx.service的服务。
(2)查看服务状态:使用`systemctl status`命令,后跟服务名称,如`systemctl status nginx.service`,这将显示服务的详细状态信息,包括是否正在运行、最近一次启动时间、进程ID等。
(3)重启服务:使用`systemctl restart`命令,后跟服务名称,以重启服务。
三、获取帮助
systemctl命令是一个强大且灵活的工具,可以帮助Linux系统管理员有效地管理系统服务。如需了解更多关于systemctl命令的详细信息和用法,建议查阅相关的Linux系统文档或手册。如下是两种便捷获取帮助的渠道:
1、通过help获取
systemctl --help
实验如下:
[root@ecs-52a1 vidisit]#
[root@ecs-52a1 vidisit]# systemctl --help
systemctl [OPTIONS...] {COMMAND} ...
Query or send control commands to the systemd manager.
-h --help Show this help
--version Show package version
--system Connect to system manager
--user Connect to user service manager
-H --host=[USER@]HOST
Operate on remote host
-M --machine=CONTAINER
Operate on local container
-t --type=TYPE List units of a particular type
--state=STATE List units with particular LOAD or SUB or ACTIVE state
-p --property=NAME Show only properties by this name
-a --all Show all properties/all units currently in memory,
including dead/empty ones. To list all units installed on
the system, use the 'list-unit-files' command instead.
--failed Same as --state=failed
-l --full Don't ellipsize unit names on output
-r --recursive Show unit list of host and local containers
--reverse Show reverse dependencies with 'list-dependencies'
--job-mode=MODE Specify how to deal with already queued jobs, when
queueing a new job
--show-types When showing sockets, explicitly show their type
--value When showing properties, only print the value
-i --ignore-inhibitors
When shutting down or sleeping, ignore inhibitors
--kill-who=WHO Who to send signal to
-s --signal=SIGNAL Which signal to send
--now Start or stop unit in addition to enabling or disabling it
--dry-run Only print what would be done
-q --quiet Suppress output
--wait For (re)start, wait until service stopped again
--no-block Do not wait until operation finished
--no-wall Don't send wall message before halt/power-off/reboot
--no-reload Don't reload daemon after en-/dis-abling unit files
--no-legend Do not print a legend (column headers and hints)
--no-pager Do not pipe output into a pager
--no-ask-password
Do not ask for system passwords
--global Enable/disable/mask unit files globally
--runtime Enable/disable/mask unit files temporarily until next
reboot
-f --force When enabling unit files, override existing symlinks
When shutting down, execute action immediately
--preset-mode= Apply only enable, only disable, or all presets
--root=PATH Enable/disable/mask unit files in the specified root
directory
-n --lines=INTEGER Number of journal entries to show
-o --output=STRING Change journal output mode (short, short-precise,
short-iso, short-iso-precise, short-full,
short-monotonic, short-unix,
verbose, export, json, json-pretty, json-sse, cat)
--firmware-setup Tell the firmware to show the setup menu on next boot
--plain Print unit dependencies as a list instead of a tree
Unit Commands:
list-units [PATTERN...] List units currently in memory
list-sockets [PATTERN...] List socket units currently in memory,
ordered by address
list-timers [PATTERN...] List timer units currently in memory,
ordered by next elapse
start UNIT... Start (activate) one or more units
stop UNIT... Stop (deactivate) one or more units
reload UNIT... Reload one or more units
restart UNIT... Start or restart one or more units
try-restart UNIT... Restart one or more units if active
reload-or-restart UNIT... Reload one or more units if possible,
otherwise start or restart
try-reload-or-restart UNIT... If active, reload one or more units,
if supported, otherwise restart
isolate UNIT Start one unit and stop all others
kill UNIT... Send signal to processes of a unit
freeze PATTERN... Freeze execution of unit processes
thaw PATTERN... Resume execution of a frozen unit
is-active PATTERN... Check whether units are active
is-failed PATTERN... Check whether units are failed
status [PATTERN...|PID...] Show runtime status of one or more units
show [PATTERN...|JOB...] Show properties of one or more
units/jobs or the manager
cat PATTERN... Show files and drop-ins of specified units
set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit
help PATTERN...|PID... Show manual for one or more units
reset-failed [PATTERN...] Reset failed state for all, one, or more
units
list-dependencies [UNIT] Recursively show units which are required
or wanted by this unit or by which this
unit is required or wanted
Unit File Commands:
list-unit-files [PATTERN...] List installed unit files
enable [UNIT...|PATH...] Enable one or more unit files
disable UNIT... Disable one or more unit files
reenable UNIT... Reenable one or more unit files
preset UNIT... Enable/disable one or more unit files
based on preset configuration
preset-all Enable/disable all unit files based on
preset configuration
is-enabled UNIT... Check whether unit files are enabled
mask UNIT... Mask one or more units
unmask UNIT... Unmask one or more units
link PATH... Link one or more units files into
the search path
revert UNIT... Revert one or more unit files to vendor
version
add-wants TARGET UNIT... Add 'Wants' dependency for the target
on specified one or more units
add-requires TARGET UNIT... Add 'Requires' dependency for the target
on specified one or more units
edit UNIT... Edit one or more unit files
get-default Get the name of the default target
set-default TARGET Set the default target
Machine Commands:
list-machines [PATTERN...] List local containers and host
Job Commands:
list-jobs [PATTERN...] List jobs
cancel [JOB...] Cancel all, one, or more jobs
Environment Commands:
show-environment Dump environment
set-environment VARIABLE=VALUE... Set one or more environment variables
unset-environment VARIABLE... Unset one or more environment variables
import-environment [VARIABLE...] Import all or some environment variables
Manager Lifecycle Commands:
daemon-reload Reload systemd manager configuration
daemon-reexec Reexecute systemd manager
System Commands:
is-system-running Check whether system is fully running
default Enter system default mode
rescue Enter system rescue mode
emergency Enter system emergency mode
halt Shut down and halt the system
poweroff Shut down and power-off the system
reboot [ARG] Shut down and reboot the system
kexec Shut down and reboot the system with kexec
exit [EXIT_CODE] Request user instance or container exit
switch-root ROOT [INIT] Change to a different root file system
suspend Suspend the system
hibernate Hibernate the system
hybrid-sleep Hibernate and suspend the system
suspend-then-hibernate Suspend the system, wake after a period of
time and put it into hibernate
[root@ecs-52a1 vidisit]#
2、通过man获取
[root@ecs-52a1 121yunwei]# man systemctl
四、应用举例
systemctl的应用涵盖了一些操作和功能,下面举几个例子来说明:
1. 查看系统状态和日志:
- `systemctl status`:此命令用于显示系统的当前状态,包括激活的单元、运行状态等信息。通过查看这些信息,管理员可以迅速了解系统的整体运行状况。
实际操作代码如下:
[root@ecs-52a1 vidisit]#
[root@ecs-52a1 vidisit]# systemctl status
● ecs-52a1
State: degraded
Jobs: 0 queued
Failed: 2 units
Since: Tue 2024-01-23 13:27:23 CST; 2 months 15 days ago
CGroup: /
├─user.slice
│ ├─user-1002.slice
│ │ ├─session-293.scope
│ │ │ ├─2404089 sshd: vidisit [priv]
│ │ │ ├─2404104 sshd: vidisit@pts/1
│ │ │ ├─2404107 -bash
│ │ │ ├─2404134 bash -c while [ -d /proc/$PPID ]; do sleep 1;head -v -n 8 /proc/meminfo; head -v -n 2 /proc/stat /proc/version>
│ │ │ ├─2413733 su
│ │ │ ├─2415766 bash
│ │ │ ├─3172028 sleep 1
│ │ │ ├─3172264 systemctl status
│ │ │ └─3172265 less
│ │ ├─user@1002.service
│ │ │ └─init.scope
│ │ │ ├─2404092 /usr/lib/systemd/systemd --user
│ │ │ └─2404094 (sd-pam)
│ │ └─session-295.scope
│ │ ├─2404105 sshd: vidisit [priv]
│ │ ├─2404152 sshd: vidisit@notty
│ │ └─2404543 /usr/libexec/openssh/sftp-server
│ └─user-1003.slice
│ ├─session-9.scope
│ │ └─236611 /usr/java/jdk1.8.0_112/bin/java -Djava.util.logging.config.file=/usr/java/apache-tomcat-9.0.37/conf/logging.pro>
│ ├─session-44.scope
│ │ └─1713136 /usr/libexec/platform-python -s /usr/sbin/firewalld
│ ├─session-285.scope
│ │ ├─3170475 sleep 5
│ │ ├─3170735 sleep 5
│ │ ├─3170956 sleep 5
│ │ ├─3171228 sleep 5
│ │ ├─3171491 sleep 5
│ │ ├─3171752 sleep 5
│ │ ├─3172003 sleep 5
│ │ ├─3172263 sleep 5
│ ├─session-4.scope
│ │ └─8024 ./redis-server 127.0.0.1:6379
│ ├─user@1003.service
│ │ └─init.scope
│ │ ├─7933 /usr/lib/systemd/systemd --user
│ │ └─7936 (sd-pam)
│ └─session-194.scope
│ ├─1423887 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/usr/local/mysql/data/ --pid-file=/usr/local/mysql/data/mys>
│ └─1424290 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/local>
├─init.scope
│ └─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 18
└─system.slice
├─rngd.service
│ └─864 /sbin/rngd -f --fill-watermark=0
├─irqbalance.service
│ └─773 /usr/sbin/irqbalance --foreground
├─uniagent.service
│ └─767 /usr/local/uniagent/bin/uniagent
├─systemd-udevd.service
│ └─628 /usr/lib/systemd/systemd-udevd
├─system-serial\x2dgetty.slice
│ └─serial-getty@ttyS0.service
│ └─7111 /sbin/agetty -o -p -- \u --keep-baud 115200,38400,9600 ttyS0 vt220
├─polkit.service
│ └─750 /usr/lib/polkit-1/polkitd --no-debug
├─chronyd.service
│ └─806 /usr/sbin/chronyd
├─auditd.service
│ └─648 /sbin/auditd
├─tuned.service
│ └─903 /usr/libexec/platform-python -Es /usr/sbin/tuned -l -P
├─systemd-journald.service
│ └─599 /usr/lib/systemd/systemd-journald
├─atd.service
│ └─7091 /usr/sbin/atd -f
├─sshd.service
│ └─7084 /usr/sbin/sshd -D -oCiphers=aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes256-cbc,aes128-gcm@o>
├─crond.service
│ └─7102 /usr/sbin/crond -n
├─NetworkManager.service
│ └─785 /usr/sbin/NetworkManager --no-daemon
├─rsyslog.service
│ └─1536 /usr/sbin/rsyslogd -n
├─firewalld.service
│ └─3263222 /usr/libexec/platform-python -s /usr/sbin/firewalld --nofork --nopid
├─sssd.service
│ ├─738 /usr/sbin/sssd -i --logger=files
│ ├─907 /usr/libexec/sssd/sssd_be --domain implicit_files --uid 0 --gid 0 --logger=files
│ └─916 /usr/libexec/sssd/sssd_nss --uid 0 --gid 0 --logger=files
├─cloudResetPwdUpdateAgent.service
│ ├─889 /CloudResetPwdUpdateAgent/bin/./wrapper /CloudResetPwdUpdateAgent/bin/../conf/wrapper.conf wrapper.syslog.ident=clou>
│ └─972 /CloudResetPwdUpdateAgent/depend/jre/bin/java -Dorg.tanukisoftware.wrapper.WrapperSimpleApp.maxStartMainWait=40 -Dja>
├─LiveVIS_Service.service
│ └─743 /usr/local/liveVIS/LiveVIS-linux-3.3.3-23032811/livevis
├─dbus.service
│ └─736 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
├─system-getty.slice
│ └─getty@tty1.service
│ └─7110 /sbin/agetty -o -p -- \u --noclear tty1 linux
└─systemd-logind.service
└─941 /usr/lib/systemd/systemd-logind
[root@ecs-52a1 vidisit]#
[root@ecs-52a1 vidisit]#
[root@ecs-52a1 vidisit]#
- `journalctl -u service-name`:通过指定服务名称,可以查看特定服务的日志信息。这对于了解服务的运行状态、问题排查等非常有帮助。
2. 管理系统单元:
- 批量启动或停止多个服务:`systemctl start service1 service2` 和 `systemctl stop service1 service2`。这种批量操作能够显著提高管理员的工作效率,尤其当需要同时管理多个服务时。
- 批量启用或禁用多个服务的自启动:`systemctl enable service1 service2` 和 `systemctl disable service1 service2`。通过启用或禁用服务的自启动,管理员可以更加灵活地控制服务的启动行为。
3. 设置单元的启动频率限制和重启策略:
- 设置单元的启动频率限制:在systemd的配置文件(如system.conf)中,可以设置`StartLimitIntervalSec`和`StartLimitBurst`两个参数,来限制单元在特定时间间隔内的启动次数。这有助于防止因服务频繁启动而导致的系统资源耗尽。
- 设置重启策略:在服务的单元文件中,可以通过`Restart=`选项来设置服务的重启策略。例如,可以设置服务在崩溃后自动重启,或者在特定条件下进行重启。这有助于确保服务的持续可用性。
4. 依赖管理:
- 当一个服务依赖于其他服务时,systemctl可以配置相应的依赖关系。例如,当一个服务所依赖的服务发生异常时,当前服务将尝试重启。这种依赖管理功能有助于确保服务的稳定性和可靠性。
5. 使用通配符进行批量操作:
- systemctl支持使用通配符(如*)来匹配多个服务或单元,从而进行批量操作。例如,`systemctl stop *.service` 将停止所有以.service结尾的服务。
这些应用例子展示了systemctl命令在Linux系统服务管理中的强大功能和灵活性。通过充分利用这些功能,管理员可以更加高效地管理系统服务,确保系统的稳定运行。
五、systemctl的应用场景
在Linux中,`systemctl`命令是一个强大的工具,用于管理`systemd`系统和服务管理器。以下是一些`systemctl`命令的常见应用场景:
1. 服务管理
启动服务
systemctl start service-name
停止服务
systemctl stop service-name
重启服务
systemctl restart service-name
查看服务状态
systemctl status service-name
操作如下:
[root@ecs-52a1 vidisit]# systemctl status mysqld
● mysqld.service - LSB: start and stop MySQL
Loaded: loaded (/etc/rc.d/init.d/mysqld; generated)
Active: active (exited) since Tue 2024-01-23 13:36:40 CST; 2 months 15 days ago
Docs: man:systemd-sysv-generator(8)
Process: 126387 ExecStart=/etc/rc.d/init.d/mysqld start (code=exited, status=0/SUCCESS)
Tasks: 0 (limit: 49519)
Memory: 0B
CGroup: /system.slice/mysqld.service
Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.
[root@ecs-52a1 vidisit]#
启用服务开机自启
systemctl enable service-name
禁用服务开机自启
systemctl disable service-name
2. 定时器管理
启用定时器
systemctl enable timer-name
禁用定时器
systemctl disable timer-name
立即触发定时器
systemctl start timer-name
3. 查看系统状态
查看所有活动单元
systemctl
查看所有已加载单元
systemctl list-units --type=service --all
查看系统日志
systemctl list-logs
4. 单元依赖管理
列出服务依赖
systemctl list-dependencies service-name
重新加载systemd配置
当修改了服务的单元文件后,需要重新加载systemd配置以使更改生效:
systemctl daemon-reload
5. 管理用户服务
对于用户级别的服务,可以使用`--user`选项:
查看用户服务状态
systemctl --user status service-name
启动用户服务
systemctl --user start service-name
6. 管理套接字和挂载点
除了服务,`systemctl`也可以用来管理套接字(sockets)和挂载点(mounts):
启动套接字
systemctl start socket-name
挂载文件系统
systemctl start mount-name
7. 隔离目标
`systemd`的目标(targets)代表系统运行的不同状态。可以使用`systemctl`来隔离到特定的目标:
切换到图形界面
systemctl isolate graphical.target
切换到多用户模式
systemctl isolate multi-user.target
8. 临时覆盖单元设置
使用`--property`选项可以临时覆盖单元文件的设置:
systemctl set-property service-name Restart=always
这些只是`systemctl`命令的一些常见应用场景。由于`systemd`的灵活性和功能丰富性,`systemctl`命令的应用范围非常广泛,几乎涵盖了Linux系统中所有与服务和系统初始化相关的任务。在实际使用中,管理员可以根据具体需求灵活应用这些命令来管理系统和服务。
篇幅有限,若想了解更多,文章正下方可以看到我的联系方式:鼠标“点击” 下面的 “威迪斯特-就是video system 微信名片”字样,就会出现我的二维码,欢迎沟通探讨。
更多推荐
所有评论(0)