CentOS7.9:系统服务管理结构化实战 一、项目概述1.1 业务场景说明CentOS 7 全部服务采用 systemd 进行管理使用 systemctl 命令管控服务启动、停止、开机自启、查看状态用来管理 DHCP、TFTP、vsftpd、named、ntpd、network 等服务保障 PXE 批量装机环境所有服务开机自动运行完成服务器自动化部署。1.2 环境参数项目参数值操作系统CentOS Linux release 7.9‑2009服务管理工具systemctlsystemd服务文件目录系统服务/usr/lib/systemd/system/用户自定义服务/etc/systemd/system/测试服务dhcpdvsftpdnamedntpdNetworkManager二、systemctl 基础操作命令2.1 启停服务命令启动服务systemctl start dhcpd停止服务systemctl stop dhcpd重启服务systemctl restart dhcpd重新加载配置文件不中断进程systemctl reload dhcpd2.2 查看服务运行状态查看服务详细状态systemctl status dhcpd只查看运行状态active/inactivesystemctl is‑active dhcpd2.3 设置开机自启与关闭开机自启设置开机自动启动systemctl enable dhcpd关闭开机自启systemctl disable dhcpd一条命令启动服务并设置开机自启systemctl enable --now dhcpd查看是否开机自启systemctl is‑enabled dhcpd三、查看系统服务列表3.1 查看所有已经运行的服务systemctl list‑units --typeservice --staterunning3.2 查看全部服务包括未启动服务systemctl list‑unit‑files --typeservice3.3 查看开机启动项分类enabled开机启动disabled开机禁止启动systemctl list‑unit‑files --typeservice | grep enabled四、运行级别target 模式CentOS7 放弃传统 runlevel使用 target 模式。查看当前默认运行级别systemctl get‑default切换到字符模式multi‑user.targetsystemctl set‑default multi‑user.target切换图形模式graphical.targetsystemctl set‑default graphical.targetmulti‑user.target字符界面机房服务器标准模式graphical.target图形桌面模式。五、自定义服务文件实战案例创建自定义脚本服务示例pxe‑server.service。5.1 编写 service 文件vi /etc/systemd/system/pxe-server.service写入配置[Unit]DescriptionPXE‑Server ServiceAfternetwork.target[Service]TypeforkingExecStart/root/pxe_start.shExecStop/root/pxe_stop.sh[Install]WantedBymulti‑user.target5.2 加载新服务配置新建或修改 service 文件后刷新 systemd 配置systemctl daemon-reload启动自定义服务并设置开机自启systemctl enable --now pxe-server六、屏蔽服务彻底禁用服务部分服务即使设置 disable软件安装脚本依旧会触发启动使用 mask 彻底屏蔽。屏蔽服务无法手动启动systemctl mask firewalld解除屏蔽systemctl unmask firewalld七、ks.cfg 批量装机配置适配 PXE 项目在 % post 脚本批量开启服务开机自启装机完成自动启动整套 PXE 服务。%postsystemctl enable --now dhcpdsystemctl enable --now vsftpdsystemctl enable --now namedsystemctl enable --now ntpd%end八、高频故障总结故障 1设置 enable 开机自启后重启服务器服务没有启动原因 1service 配置语法错误原因 2依赖服务network启动顺序出错解决systemctl status xxx查看日志检查 [Unit] 段 After 字段。故障 2reload 命令执行失败只能 restart原因该程序不支持热加载配置解决改用 restart 重启服务。故障 3服务 disable 之后软件更新又自动开启开机项原因rpm 包脚本重新修改启动项解决使用 systemctl mask 彻底屏蔽服务。故障 4自定义 service 文件修改之后配置不生效原因没有执行 daemon‑reload 刷新配置解决执行systemctl daemon-reload再重启服务。