python用c/s实现服务器简单管理

发布时间:2019-08-26 07:19:24编辑:auto阅读(1540)

    背景:

    由于有大量的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 ' 

     

    简单的实现了以上需求。大家可以一起讨论下,用更好的方法来实现以上的需求。

     

关键字