要使用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/
目录下找到这些服务单元文件。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:怎样用Telnet管理Linux服务器