def __init__(self, t_name, scriptPath, qHeartHeats, qMonitor, qRepaire, backup, check, sessionDic): threading.Thread.__init__(self, name=t_name) self.ACTIONS = { 1: "Created", # 增 2: "Deleted", # 删 3: "Updated", # 该 4: "Renamed from something", # 重命名之前 5: "Renamed to something" # 重命名之后 } FILE_LIST_DIRECTORY = win32con.GENERIC_READ | win32con.GENERIC_WRITE self.qHeartHeats = qHeartHeats self.qMonitor = qMonitor self.qRepaire = qRepaire self.backup = backup self.check = check self.hDir = win32file.CreateFile( sessionDic['targetPath'], FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None) self.monitorPath = sessionDic['targetPath'] self.projectName = self.monitorPath.split(os.sep)[-1] self.whiteList = sessionDic['whiteList'] self.blackList = sessionDic['blackList'] self.mode = sessionDic['mode'] self.doBak = sessionDic['doBak'] self.bakPath = confdeal.getConfPath(scriptPath)['bakPath'] self.remoteDic = confdeal.getConfRemote(scriptPath) self.flagName = sessionDic['flagName'] self.runFlag = 1
def run(self): # 开始备份 if os.path.exists(self.bakPath): # 判断项目是否存在,不存在则创建文件夹 shutil.rmtree(self.bakPath) #如果存在,则删除 ,然后重建 os.mkdir(self.bakPath) if os.path.exists(self.cashPath): # 判断项目是否存在,不存在则创建文件夹 shutil.rmtree(self.cashPath) #如果存在,则删除 ,然后重建 os.mkdir(self.cashPath) self.runCompress(self.sessionDic['targetPath'], self.bakPath) # 开始备份 self.runFlagTree(self.bakPath) filedeal.comZip(self.cashPath, self.rarPath + '_flag') # 压缩文件夹,并且上传,之后删除 filedeal.comZip(self.bakPath, self.rarPath) # shutil.rmtree(self.rarPath) shutil.rmtree(self.cashPath) if not self.runFlag: #终止递归的判断条件 return if self.runFlag: # 从临时模式切换至安全模式 self.qHeartHeats.put( ['信息', self.sessionDic['projectName'] + '切至安全模式 ...', 0]) # 通知监控线程,备份完毕,令其转换成safe 模式 self.qMonitor.put('True') remoteDic = confdeal.getConfRemote(self.scriptPath) netrequest.upload(remoteDic['remoteHost'], remoteDic['remotePort'], self.rarTopPath, self.sessionDic['sessionName'] + '_flag', 1) netrequest.upload(remoteDic['remoteHost'], remoteDic['remotePort'], self.rarTopPath, self.sessionDic['sessionName'], 0)
def working(self): self.heartBeat.start() remoteDic = confdeal.getConfRemote(self.scriptPath) time.sleep(4) try: s = socket.socket() s.bind(("0.0.0.0", remoteDic['localPort'])) s.listen(1) #指定最多允许多少个客户连接到服务器。 except: self.heartBeat.stopRun() print 'Socker init error ! \nPlease check port\nExit!' sys.exit() if not self.bakOrCheck(): print 'No config ! \nWaiting for server\'s command !' # self.test() # 测试 while 1: # 接受指令 try: conn, addr = s.accept() conn.settimeout(5) if addr != remoteDic['remoteHost']: # 判断IP是否合法 print "IP($s)illegal connection !\nAuto reject ..." % ( addr) conn.close() continue messageJson = conn.recv(4096) # 接收服务器消息 message = json.loads(messageJson) command = message['command'] if command == 'start': # 开始监控和备份 slash, bslash = special.getSlash() common.dicStringReplace(message, bslash, slash) if os.path.exists(message['targetPath']): message['projectName'] = message['targetPath'][ message['targetPath'].rfind(os.sep) + 1:] message['sessionName'] = common.getMd5( message['projectName'] + remoteDic['localHost'] + str(remoteDic['localPort'])) message['flagName'] = common.getRandom() self.startMonitor(message, 1) else: print "The monitor path is not exists !" elif command == 'stop': # 停止监控和备份 message['projectName'] = message['targetPath'][ message['targetPath'].rfind(os.sep) + 1:] message['sessionName'] = common.getMd5( message['projectName'] + remoteDic['localHost'] + str(remoteDic['localPort'])) self.stopMonitor(message) elif command == 'getPath' or command == 'getWhitePath': # 遍历返回所有目录信息 infoJson = self.getPath(message) conn.sendall(infoJson) conn.close() # 关闭连接 except: print 'Illegal command !' time.sleep(5)
def SvcStop(self): with open('C:\\filemonitor', 'r') as f: scriptPath=f.read() if os.path.exists(scriptPath): remoteDic = confdeal.getConfRemote(scriptPath) if remoteDic: ret = os.popen('netstat -ano | findstr \":'+str(remoteDic['localPort'])+' \"') strList = list(set(ret.read().split('\n'))) for pidStr in strList: if pidStr != '': pidStr = pidStr[pidStr.rfind(' ')+1:] os.system("taskkill /F /T /PID "+pidStr) else : exit() self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def __init__(self, scriptPath, qHeartHeats, qMonitor, qRepaire, backup, check, sessionDic): self.qHeartHeats = qHeartHeats self.qMonitor = qMonitor self.qRepaire = qRepaire self.backup = backup self.check = check self.monitorPath = sessionDic['targetPath'] self.projectName = self.monitorPath.split(os.sep)[-1] self.whiteList = sessionDic['whiteList'] self.blackList = sessionDic['blackList'] self.mode = sessionDic['mode'] self.doBak = sessionDic['doBak'] self.bakPath = confdeal.getConfPath(scriptPath)['bakPath'] self.remoteDic = confdeal.getConfRemote(scriptPath) self.flagName = sessionDic['flagName']
def __init__(self, t_name, scriptPath, qHeartbeats): threading.Thread.__init__(self, name=t_name) self.qHeartbeats = qHeartbeats self.pathDic = confdeal.getConfPath(scriptPath) self.heartbeatsLogPath = self.pathDic[ 'logPath'] + os.sep + 'heartbeats.log' self.monitorLogPath = self.pathDic['logPath'] + os.sep + 'monitor.log' self.cashLogPath = self.pathDic['logPath'] + os.sep + 'cash.log' self.cashList = [] # 日志缓存 self.clog = open(self.cashLogPath, 'a+') self.remoteDic = confdeal.getConfRemote(scriptPath) self.timeDelay = confdeal.getConfHeartbeats(scriptPath)['delayTime'] self.runFlag = 1 # 线程运行标志 self.portFlag = 1 # 连通标志 self.differentFlag = 1 self.lastTime = None self.nowTime = None
def stop(self): #从pid文件中获取pid try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: #重启不报错 message = 'pidfile %s does not exist. Daemon not running!\n' sys.stderr.write(message % self.pidfile) return #杀进程 remoteDic = confdeal.getConfRemote(self.scriptPath) if remoteDic: ret = os.popen('netstat -antup | grep \":' + str(remoteDic['localPort']) + ' \"') strList = list(set(ret.read().split('\n'))) for pidStr in strList: if pidStr != '': pidStr = pidStr.split('/')[0] pidStr = pidStr[pidStr.rfind(' ') + 1:] os.system("kill " + pidStr) try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) #os.system('hadoop-daemon.sh stop datanode') #os.system('hadoop-daemon.sh stop tasktracker') #os.remove(self.pidfile) except OSError, err: err = str(err) if err.find('No such process') > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print str(err) sys.exit(1)
def handle(self): confdeal.initConf(self.scriptPath) args = self.parser.parse_args() # 有输入参数的情况: if args.LHOST != None or args.LPORT !=None or args.RHOST !=None or args.RPORT !=None : if confdeal.setConfRemote(self.scriptPath,args.RHOST,args.RPORT,args.LHOST,args.LPORT): remoteDic = { 'localHost': args.RHOST, 'localPort': args.RPORT, 'remoteHost': args.LHOST, 'remotePort': args.LPORT, } self.flag = True # 没输入参数 读取配置文件 else: remoteDic = confdeal.getConfRemote(self.scriptPath) if remoteDic : self.flag = True
def test(self): remoteDic = confdeal.getConfRemote(self.scriptPath) message = { 'command': 'start', 'targetPath': '/home/gmfork/Desktop/test', 'mode': 'safe', 'doBak': 1, 'whiteList': ['/home/gmfork/Desktop/test/python/other'], 'blackList': ['php', 'asp'], 'timeDelay': '1', } command = message['command'] # 开始监控和备份 if command == 'start': slash, bslash = special.getSlash() common.dicStringReplace(message, bslash, slash) if os.path.exists(message['targetPath']): message['projectName'] = message['targetPath'][ message['targetPath'].rfind(os.sep) + 1:] message['sessionName'] = common.getMd5( message['projectName'] + remoteDic['localHost'] + str(remoteDic['localPort'])) message['flagName'] = common.getRandom() self.startMonitor(message, 1) else: print "The monitor path is not exists !" # 停止监控和备份 elif command == 'stop': message['projectName'] = message['targetPath'][ message['targetPath'].rfind(os.sep) + 1:] message['sessionName'] = common.getMd5(message['projectName'] + remoteDic['localHost'] + str(remoteDic['localPort'])) self.stopMonitor(message) # 遍历返回所有目录信息 elif command == 'getPath' or command == 'getWhitePath': self.getPath(message)
def run(self): if os.path.exists(self.cashPath): # 判断项目是否存在,不存在则创建文件夹 shutil.rmtree(self.cashPath) #如果存在,则删除 ,然后重建 os.mkdir(self.cashPath) remoteDic = confdeal.getConfRemote(self.scriptPath) if self.decomZiptoDir(remoteDic, self.cashTopPath, 1): if self.checkBakFold(): # 检查备份文件是否正常 if not self.checkWebSource(): # 如果网站源码不正常 if not self.runFlag: # 终止、 special.echo("自检失败 !") return special.echo("网站源文件出现异常 ! 正在还原 ...") self.runRepair(self.sessionDic['targetPath']) # 还原项目 if not self.runFlag: # 终止 special.echo("自检失败 !") return if not self.runFlag: #终止递归的判断条件 return elif self.runFlag: # 从临时模式切换至安全模式 self.qRepaire.put(['safe', 'safe', 'safe']) else: # 如果备份文件是不正常 special.echo("备份文件出现异常 !正在还原 ...") if self.decomZiptoDir(remoteDic, self.bakTopPath, 0): self.runRepair(self.sessionDic['targetPath']) #还原项目 if not self.runFlag: #终止递归的判断条件 return elif self.runFlag: # 从临时模式切换至安全模式 self.qRepaire.put(['safe', 'safe', 'safe']) else: special.echo("没有找到备份文件 !\n开启备份模式 !") self.backup.start() else: special.echo("没有找到备份文件 !\n开启备份模式 !") self.backup.start() if not self.runFlag: #终止 special.echo("自检失败 !")