按计划和要求构建服务器,使其高效运行是运维的主要目标之一。 Linux 系统默认会安装和运行许多服务,一些不必要的服务应当予以禁用。
Systemctl 是一个 systemd 实用工具,负责控制 systemd 系统和服务管理器。 Systemd 是一组系统管理守护进程、实用工具和库的集合,用作 System V init 守护进程的替代品。Systemd 作为类 UNIX 系统的中央管理和配置平台。
在 Linux 生态系统中,Systemd 已在大多数标准 Linux 发行版中实现。

本文介绍如何在基于 systemd 的 Linux 发行版(如 Fedora、CentOS、Ubuntu、Debian 等)上识别和禁用不必要的服务。
systemctl --versionwhereis systemdwhereis systemctlps -eaf | grep [s]ystemdsystemd-analyzesystemd-analyze blamesystemd-analyze critical-chainsystemctl list-unit-filesSystemctl 接受服务(.service)、挂载点(.mount)、套接字(.socket)和设备(.device)作为单元。systemctl list-unitssystemctl --failedsystemctl is-enabled sshd.servicesystemctl status firewalld.servicesystemctl list-unit-files --type=servicesystemctl list-unit-files --type=mountsystemctl list-unit-files --type=socket使用 systemd,管理和检查服务很方便。
列出所有运行中的服务sudo systemctl list-units --type=service --state=running检查开放端口并识别监听服务sudo ss -tuln 或 sudo netstat -tuln禁用不必要的服务sudo systemctl disable avahi-daemon # 零配置网络(本地服务发现)sudo systemctl disable bluetooth # 蓝牙服务sudo systemctl disable iscsi # iSCSI网络存储sudo systemctl disable iscsid.socket # iSCSI网络存储sudo systemctl disable iscsiuio.socket # iSCSI网络存储sudo systemctl disable lvm2-monitor # 管理LVM卷sudo systemctl disable lvm2-lvmpolld.socket #管理LVM卷sudo systemctl disable mdmonitor # 软RAIDsudo systemctl disable raid-check.timer # 软RAIDsudo systemctl disable qemu-guest-agent # QEMU、KVM虚拟机sudo systemctl disable nfs-convert # NFS服务sudo systemctl disable nfs-client.target # NFS服务sudo systemctl disable cups # 打印服务sudo systemctl disable postfix # 邮件发送服务sudo systemctl disable sssd # 连接LDAP或AD域sudo systemctl disable hyperv-daemons # Hyper-V虚拟服务sudo systemctl disable apport # Ubuntu错误报告sudo systemctl disable zeitgeist # 桌面日志记录sudo systemctl disable telepathy # 桌面消息服务识别服务详情systemd-analyze blame # 检查哪个服务导致启动慢阻止/恢复服务被手动启动或作为依赖项sudo systemctl mask/unmask 服务名systemctl show -p CPUShares httpd.service获取服务(例如 httpd)当前的 CPU 份额systemctl set-property httpd.service CPUShares=2000服务的 CPU 份额(httpd.service)限制为 2000 CPUsystemctl show httpd检查服务的所有配置细节systemd-analyze critical-chain httpd.service分析服务的关键链systemctl list-dependencies httpd.service获取httpd服务的依赖列表systemd-cgls分层列出控制组systemd-cgtop根据 CPU、内存、输入和输出列出控制组每个服务默认的 CPUShare = 1024。可以增加/减少进程的 CPU 份额。为服务设置 CPUShare 时,会创建一个以服务名称命名的目录(httpd.service.d),其中包含一个文件 90-CPUShares.conf,该文件包含 CPUShare 限制信息。
systemctl rescue启动系统救援模式systemctl emergency进入紧急模式systemctl get-default当前正在使用的运行级别systemctl isolate runlevel5.targetsystemctl isolate graphical.target启动运行级别 5(即图形模式)systemctl isolate runlevel3.targetsystemctl isolate multiuser.target启动运行级别 3(多用户模式)systemctl rebootsystemctl haltsystemctl suspendsystemctl hibernatesystemctl hybrid-sleep重启、停止、挂起、休眠或将系统置于混合睡眠将以上禁用不必要的服务相关命令复制粘贴到VIM编辑器中,在VIM编辑器中按下 Esc 后输入以下命令,可以秒删除所有#注释内容,只保留命令。
:%s/\s*#.*//% 表示作用于整个文件(所有行)s 代表 substitute(替换)。/ 分隔符。\s*#.* 匹配模式\s* 匹配 # 号前的零个或多个空格(把命令结尾的空格一并删掉)# 匹配 # 字符本身.* 匹配 # 之后直到行尾的所有内容// 替换后的内容为空(即删除):%s/\s*#.*//删除注释及前面的空格:g/^$/d删除空行:%s/ */ /g将连续的多个空格压缩为一个