要使用Python管理Linux服务,您可以使用systemd
库
pip install systemd-python
以下是一些使用Python和systemd
库管理Linux服务的示例:
- 启动一个服务:
import systemd.daemon import time def start_service(): unit = "your_service.service" # 替换为您的服务单元名称 systemd.daemon.start_unit(unit) print(f"{unit} started.") if __name__ == "__main__": start_service() while True: time.sleep(1)
- 停止一个服务:
import systemd.daemon def stop_service(): unit = "your_service.service" # 替换为您的服务单元名称 systemd.daemon.stop_unit(unit) print(f"{unit} stopped.") if __name__ == "__main__": stop_service()
- 重启一个服务:
import systemd.daemon def restart_service(): unit = "your_service.service" # 替换为您的服务单元名称 systemd.daemon.restart_unit(unit) print(f"{unit} restarted.") if __name__ == "__main__": restart_service()
- 检查服务状态:
import systemd.daemon def check_service_status(unit): status = systemd.daemon.get_unit_status(unit) print(f"{unit} status: {status}") if __name__ == "__main__": unit = "your_service.service" # 替换为您的服务单元名称 check_service_status(unit)
请注意,您需要将your_service.service
替换为您要管理的实际服务单元名称。您可以在/etc/systemd/system/
目录下找到这些服务单元文件。