­

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

  • 2020 年 1 月 13 日
  • 筆記

背景:

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

目標:

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

解決方法:

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

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

#!/usr/bin/python  #Script Name : pyserver.py    import os  import logging  import sys  import socket    host='0.0.0.0'  port=4567  maxclient=10  if sys.platform == 'win32':      logfile='c:/server.log'  else:      logfile='/tmp/server.log'    def initlog():      logger=logging.getLogger()      hdlr=logging.FileHandler(logfile)      formatter=logging.Formatter('%(asctime)s %(levelname)s %(message)s')      hdlr.setFormatter(formatter)      logger.addHandler(hdlr)      logger.setLevel(logging.NOTSET)      return logger    def socketserver():      s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)      s.bind((host,port))      s.listen(maxclient)  #    print "Server is running on port %d; press ctrl-c to terminate." % port      while True:          clientsock,clientaddr=s.accept()  #        print "connect from %s" % str(clientaddr)          message="connect from : %s" % str(clientaddr)          lg.info(message)          clientfile=clientsock.makefile('rw',0)          data=clientsock.recv(1024)          message="Execute command : %s" %data          lg.info(message)          command=os.popen(data).read()          clientfile.write("%s" % command)          clientfile.close()          clientsock.close()    try:      lg=initlog()      socketserver()  except KeyboardInterrupt:      print "User Press Ctrl+C,Exit" 

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

#!/usr/bin/env python  #Script Name : pyclient.py    import os  import sys  import getopt  import socket  import logging  import time    port=4567  logfile='/tmp/client.log'  file=''  ip=''    def initlog():      logger=logging.getLogger()      hdlr=logging.FileHandler(logfile)      formatter=logging.Formatter('%(asctime)s %(levelname)s %(message)s')      hdlr.setFormatter(formatter)      logger.addHandler(hdlr)      logger.setLevel(logging.NOTSET)      return logger    def usage():      print '''  Usage: python client.py [options...]  Options:      -f : read host list from file      -I : read host from this command line      -c : command run at remote host      -h : this help info      python client.py -I 10.16.134.164 -c "/sbin/ifconfig"      '''    def socketclient(IP,port,cmd):      s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      s.connect((IP,port))      ISOTIMEFORMAT = '%Y-%m-%d %X'      date = time.strftime(ISOTIMEFORMAT, time.localtime())      result ="-------------------------------------------------------------------n"      result = "%sDATE    : %snHOST    : %sCOMMAND : %sn" %(result,date,IP,cmd)      while 1:          if not cmd:              break          s.sendall(cmd)          cmd=s.recv(1024)          if not cmd:              break          #print cmd          result = "%sRESULT  :nn%s" %(result,cmd)          print result          writeLog(logfile,result)      s.close()    def writeLog(file,message):      logger = open(file, 'a+')      logger.writelines(message)      logger.close()    try:      opts,args = getopt.getopt(sys.argv[1:],'hI:f:c:')  except getopt.GetoptError:      usage()      sys.exit()    if len(opts) == 0:      usage()      sys.exit()    for opt,arg in opts:      if opt in ('-h','--help'):          usage()          sys.exit()      elif opt == '-f':          #print 'read flie %s' %arg          file = arg      elif opt == '-I':          #print 'server IP is %s' %arg          ip = arg      elif opt == '-c':          #print 'command is %s' %arg          command = arg      if file:      for ip in os.popen('cat %s' %file).readlines():          socketclient(ip,port,command)  else:      if ip :          socketclient(ip,port,command)      else:          print 'Error ' 

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