python用c/s實現服務器簡單管理

背景:

由於有大量的windows虛擬機用來做一些任務。這些windows上的機器程序要經常更新。每次部署升級,需要一臺臺的遠程桌面上去操作,進行簡單升級操作。這樣講花費大量時間。並且伴隨windows機器的增加,將更加難管理。

目標:

無需遠程桌面,即可完成基本操作,如:部署升級程序,遠程啓動及停止代理服務,重啓,關機等。

解決方法:

採用python socket 的C/S形式來實現,在管理端發送管理命令到被管理端執行,進行更新程序代碼等操作。需在windows機器上安裝python。實現代碼如下:

1、以下是server端,部署到被管理的windows或者linux機器

  1. #!/usr/bin/python 
  2. #Script Name : pyserver.py 
  3.  
  4. import os 
  5. import logging 
  6. import sys 
  7. import socket 
  8.  
  9. host='0.0.0.0' 
  10. port=4567 
  11. maxclient=10 
  12. if sys.platform == 'win32'
  13.     logfile='c:/server.log' 
  14. else
  15.     logfile='/tmp/server.log' 
  16.  
  17. def initlog(): 
  18.     logger=logging.getLogger() 
  19.     hdlr=logging.FileHandler(logfile) 
  20.     formatter=logging.Formatter('%(asctime)s %(levelname)s %(message)s'
  21.     hdlr.setFormatter(formatter) 
  22.     logger.addHandler(hdlr) 
  23.     logger.setLevel(logging.NOTSET) 
  24.     return logger 
  25.  
  26. def socketserver(): 
  27.     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
  28.     s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1
  29.     s.bind((host,port)) 
  30.     s.listen(maxclient) 
  31. #    print "Server is running on port %d; press ctrl-c to terminate." % port 
  32.     while True
  33.         clientsock,clientaddr=s.accept() 
  34. #        print "connect from %s" % str(clientaddr) 
  35.         message="connect from : %s" % str(clientaddr) 
  36.         lg.info(message) 
  37.         clientfile=clientsock.makefile('rw',0
  38.         data=clientsock.recv(1024
  39.         message="Execute command : %s" %data 
  40.         lg.info(message) 
  41.         command=os.popen(data).read() 
  42.         clientfile.write("%s" % command) 
  43.         clientfile.close() 
  44.         clientsock.close() 
  45.  
  46. try
  47.     lg=initlog() 
  48.     socketserver() 
  49. except KeyboardInterrupt: 
  50.     print "User Press Ctrl+C,Exit" 

2、以下是管理端,用於發送命令到被管理端

 

  1. #!/usr/bin/env python 
  2. #Script Name : pyclient.py 
  3.  
  4. import os 
  5. import sys 
  6. import getopt 
  7. import socket 
  8. import logging 
  9. import time 
  10.  
  11. port=4567 
  12. logfile='/tmp/client.log' 
  13. file='' 
  14. ip='' 
  15.  
  16. def initlog(): 
  17.     logger=logging.getLogger() 
  18.     hdlr=logging.FileHandler(logfile) 
  19.     formatter=logging.Formatter('%(asctime)s %(levelname)s %(message)s') 
  20.     hdlr.setFormatter(formatter) 
  21.     logger.addHandler(hdlr) 
  22.     logger.setLevel(logging.NOTSET) 
  23.     return logger 
  24.  
  25. def usage(): 
  26.     print ''' 
  27. Usage: python client.py [options...] 
  28. Options:  
  29.     -f : read host list from file 
  30.     -I : read host from this command line 
  31.     -c : command run at remote host 
  32.     -h : this help info 
  33.     python client.py -I 10.16.134.164 -c "/sbin/ifconfig"  
  34.     ''' 
  35.  
  36. def socketclient(IP,port,cmd): 
  37.     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
  38.     s.connect((IP,port)) 
  39.     ISOTIMEFORMAT = '%Y-%m-%d %X' 
  40.     date = time.strftime(ISOTIMEFORMAT, time.localtime()) 
  41.     result ="-------------------------------------------------------------------\n" 
  42.     result = "%sDATE    : %s\nHOST    : %sCOMMAND : %s\n" %(result,date,IP,cmd) 
  43.     while 1: 
  44.         if not cmd: 
  45.             break 
  46.         s.sendall(cmd) 
  47.         cmd=s.recv(1024) 
  48.         if not cmd: 
  49.             break 
  50.         #print cmd  
  51.         result = "%sRESULT  :\n\n%s" %(result,cmd) 
  52.         print result 
  53.         writeLog(logfile,result) 
  54.     s.close() 
  55.  
  56. def writeLog(file,message): 
  57.     logger = open(file, 'a+')  
  58.     logger.writelines(message)  
  59.     logger.close() 
  60.  
  61. try: 
  62.     opts,args = getopt.getopt(sys.argv[1:],'hI:f:c:') 
  63. except getopt.GetoptError: 
  64.     usage() 
  65.     sys.exit() 
  66.  
  67. if len(opts) == 0: 
  68.     usage() 
  69.     sys.exit() 
  70.  
  71. for opt,arg in opts: 
  72.     if opt in ('-h','--help'): 
  73.         usage() 
  74.         sys.exit() 
  75.     elif opt == '-f': 
  76.         #print 'read flie %s' %arg 
  77.         file = arg 
  78.     elif opt == '-I': 
  79.         #print 'server IP is %s' %arg 
  80.         ip = arg 
  81.     elif opt == '-c': 
  82.         #print 'command is %s' %arg 
  83.         command = arg 
  84.  
  85.  
  86. if file: 
  87.     for ip in os.popen('cat %s' %file).readlines(): 
  88.         socketclient(ip,port,command) 
  89. else: 
  90.     if ip : 
  91.         socketclient(ip,port,command) 
  92.     else: 
  93.         print 'Error ' 

 

簡單的實現了以上需求。大家可以一起討論下,用更好的方法來實現以上的需求。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章