python用c/s实现服务器简单管理
背景:由于有大量的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:
[*] -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 : %s\nHOST : %sCOMMAND : %s\n" %(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:\n\n%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,'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 '
简单的实现了以上需求。大家可以一起讨论下,用更好的方法来实现以上的需求。
页:
[1]