如何查看Linux系统所有服务
如何查看Linux系统所有服务详细介绍
在 Linux 系统中查看所有服务的方法取决于系统使用的初始化系统(如 Systemd、SysVinit 等)。以下是针对不同场景的详细解决方案:
一、基于 Systemd 的系统(主流方案)
现代 Linux 发行版(如 Ubuntu 15.04+、CentOS 7+、Fedora 等)普遍使用 Systemd,其核心工具为systemctl。
1. 查看所有服务
bash
systemctl list-units service
systemctl list-units service
- 输出说明:
UNIT:服务单元名称(如nginx.service)。LOAD:配置是否加载到内存。ACTIVE:服务是否处于活动状态(如active表示运行中)。SUB:更详细的状态(如running表示正在运行,exited表示正常退出,failed表示启动失败)。
2. 查看服务启动状态(开机自启)
bash
systemctl list-unit-files service enabled
systemctl is-enabled nginx.service
3. 查看服务详细状态
bash
systemctl status nginx.service
- 输出示例:plaintext
● nginx.service - The nginx HTTP and reverse proxy serverLoaded: loaded (/etc/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2025-05-01 10:00:00 CST; 1h ago
Process: 12345 ExecStart=/usr/sbin/nginx -g daemon off; (code=exited, status=0/SUCCESS)
Main PID: 12346 (nginx)
Tasks: 2 (limit: 4915)
Memory: 20.5M
CPU: 0.012s
CGroup: /system.slice/nginx.service
├─12346 nginx: master process /usr/sbin/nginx -g daemon off;
└─12347 nginx: worker process
4. 实时监控服务资源占用
bash
systemd-cgtop
二、基于 SysVinit 的系统(旧版方案)
部分旧版系统(如 CentOS 6、Debian 7 等)使用 SysVinit,可通过以下命令查看服务:
1. 列出所有服务状态
bash
--status-all
2. 查看服务启动级别
bash
三、其他通用方法
1. 直接查看服务文件目录
bash
/etc/systemd/system/
/usr/lib/systemd/system/
/etc/init.d/
2. 搜索服务文件
bash
/etc/systemd
3. 图形化工具(适合新手)
- GNOME 系统监视器:在应用程序中搜索 “系统监视器”,切换到 “服务” 选项卡。
- KDE 系统服务管理器:通过 “系统设置” → “服务管理器” 访问。
四、进阶技巧
1. 按状态过滤服务
bash
systemctl list-units service failed
systemctl list-dependencies nginx.service
2. 实时日志监控
bash
journalctl nginx.service
3. 第三方工具
htop:实时查看进程和服务资源占用。glances:跨平台的系统监控工具,支持 Web 界面。
五、常见问题与注意事项
- 权限问题:部分命令(如
systemctl status)需要管理员权限,可通过sudo执行。 - 服务名称:Systemd 服务名称通常以
.service结尾,但执行命令时可省略后缀(如systemctl status nginx)。 - 状态解读:
active (running):服务正在运行。active (exited):服务已正常退出(如一次性任务)。inactive:服务未运行。failed:服务启动失败,需检查日志。
六、总结对比
| 初始化系统 | 典型发行版 | 核心命令 | 优点 |
|---|---|---|---|
| Systemd | Ubuntu 15.04+ | systemctl |
功能强大,支持动态管理 |
| SysVinit | CentOS 6 | service/chkconfig |
兼容性强,适合旧版系统 |
根据系统类型选择对应方法,优先使用systemctl处理现代 Linux 系统。若需进一步分析服务问题,可结合journalctl查看日志或使用图形化工具辅助排查。