標籤:python socketserver daemonize
由於用ntp經常會逾時,所以自己寫了一個簡單的時間同步伺服器,用戶端會同步服務端的系統時間:
服務端:
#!/usr/local/python27/bin/python#coding:utf-8import timeimport loggingimport SocketServerimport structfrom daemonize import DaemonizeSERVER_HOST = ‘0.0.0.0‘SERVER_PORT = 37123BUF_SIZE = 1024pid = ‘/tmp/TimeServer.pid‘logger = logging.getLogger(‘mylogger‘)logger.setLevel(logging.DEBUG)fh = logging.FileHandler(‘TimeServer.log‘)fh.setLevel(logging.DEBUG)formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)fh.setFormatter(formatter)logger.addHandler(fh)keep_fds = [fh.stream.fileno()]class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): while True: try: data = self.request.recv(BUF_SIZE) if not data: break logger.info("Received: IP:%s message: %s" % (self.client_address[0], data)) i1, i2, message = struct.unpack(‘!2b8s‘, data) if i1 == 3 and i2 == 7 and message == ‘get_time‘: cur_time = int(time.time()) response = struct.pack(‘>2bi‘, i1, i2, cur_time) self.request.sendall(response) logger.info("Send: IP:%s message: %s" % (self.client_address[0], cur_time)) else: logger.error("Message Error!") except Exception, e: logger.error("遇到錯誤:" + str(e)) break def finish(self): self.request.close()class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): passdef main(): server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT), ThreadedTCPRequestHandler) print "Server Loop Running..." server.serve_forever()#main()daemon = Daemonize(app="TimeServer", pid=pid, action=main, keep_fds=keep_fds)daemon.start()
daemonize這個是第三方模組,可以把指令碼變成守護進程,脫離終端,詳細參考:https://pypi.python.org/pypi/daemonize/2.3.1
struct模組是把資料轉換成二進位,一般是和別的程式互動用的,我這裡是寫著玩的
然後沒啥東西,就是拿網上的demo重寫了一下工作函數。
用戶端:
#!/usr/bin/python#coding:utf-8import subprocessimport socketimport timeimport sysimport structSERVER_HOST = ‘192.168.1.100‘SERVER_PORT = 37123BUF_SIZE = 1024def client(ip, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) message = struct.pack(‘>2b8s‘, 3, 7, ‘get_time‘) try: sock.sendall(message) response = sock.recv(BUF_SIZE) i1, i2, cur_time = struct.unpack(‘!2bi‘, response) formattime = time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime(int(cur_time))) ret = subprocess.call(‘‘‘ date -s "%s" ‘‘‘ % formattime, shell=True) print "client received: %s format: %s" % (response, formattime) except Exception, e: print "遇到錯誤:" + str(e) sys.exit(2) else: sock.close() return retif __name__ == "__main__": client(SERVER_HOST, SERVER_PORT)
用戶端更簡單,直接用socket串連服務端,擷取訊息後修改本地時間。
本文出自 “營運筆記” 部落格,請務必保留此出處http://lihuipeng.blog.51cto.com/3064864/1619797
利用Python SocketServer寫的時間同步服務端與用戶端