【Python運維】最簡單的Pytho

背景

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

相關技術

Python3, argparse module

程式碼

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腳本好寫很多啊。