【Python運維】最簡單的Python運維腳本

背景

最近在Windows 10上使用Linux子系統,發現它有一個很是坑爹的特色:Linux子系統是沒有開機關機狀態的,每次進入Bash shell就自動載入,退出後Linux子系統的全部進程都會被關閉,若是你撞了Mysql之類的服務要想隨時運行的話就要保持Bash shell的隨時開啓,更坑的是這些服務並不會隨之進入Bash shell而自動啓動, 我只好寫一個Python腳本用於管理這些服務。python

相關技術

Python3, argparse moduleweb

代碼

from os import system
from argparse import ArgumentParser

def start_service(service):
    system("service {} start".format(service))

def stop_service(service):
    system("service {} stop".format(service))

def restart_service(service):
    print(service)
    system("service {} restart".format(service))

def manage_service():
    services = []
    services.append("xinetd")
    services.append("lighttpd")
    return services

def set_args():
    parser = ArgumentParser()
    parser.add_argument("service", help = "the service to be managed.")
    parser.add_argument("-s", "--start", help = "start the service(s).", action = "store_true")
    parser.add_argument("-r", "--restart", help = "restart the service(s).", action = "store_true")
    parser.add_argument("-p", "--stop", help = "stop the service(s).", action = "store_true")
    return parser.parse_args()

def deal(args,services):
    global start_service, restart_service, stop_service
    services = services if not args.service else services if args.service == "all"else [args.service]
    operation = start_service if args.start else restart_service if args.restart else stop_service
    for  service in services:
       operation(service)

if __name__ == "__main__":
    deal(set_args(),manage_service())

運行

開啓服務

(env) root@DESKTOP-1DDIIV2:~# python pyops.py all -s
initctl: 沒法鏈接到 Upstart: Failed to connect to socket /com/ubuntu/upstart: 拒絕鏈接
 * Starting internet superserver xinetd                                                                                                                          [fail]
 * Starting web server lighttpd                                                                                                                                  [ OK ]
(env) root@DESKTOP-1DDIIV2:~#

關閉服務

(env) root@DESKTOP-1DDIIV2:~# python pyops.py xinetd -p
initctl: 沒法鏈接到 Upstart: Failed to connect to socket /com/ubuntu/upstart: 拒絕鏈接
 * Stopping internet superserver xinetd                                                                                                                          [ OK ]
(env) root@DESKTOP-1DDIIV2:~#

重啓服務

(env) root@DESKTOP-1DDIIV2:~# python pyops.py xinetd -r
xinetd
initctl: 沒法鏈接到 Upstart: Failed to connect to socket /com/ubuntu/upstart: 拒絕鏈接
 * Stopping internet superserver xinetd                                                                                                                          [ OK ]
 * Starting internet superserver xinetd                                                                                                                          [ OK ]
(env) root@DESKTOP-1DDIIV2:~#

感想

Python腳本仍是比shell腳本好寫不少啊。sql

相關文章
相關標籤/搜索