由于用ntp经常会超时,所以自己写了一个简单的时间同步服务器,客户端会同步服务端的系统时间:
服务端:
#!/usr/local/python27/bin/python #coding:utf-8 import time import logging import SocketServer import struct from daemonize import Daemonize SERVER_HOST = '0.0.0.0' SERVER_PORT = 37123 BUF_SIZE = 1024 pid = '/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): pass def 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-8 import subprocess import socket import time import sys import struct SERVER_HOST = '192.168.1.100' SERVER_PORT = 37123 BUF_SIZE = 1024 def 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 ret if __name__ == "__main__": client(SERVER_HOST, SERVER_PORT)
客户端更简单,直接用socket连接服务端,获取消息后修改本地时间。