# 获取所有文件MD5 defgetfilemd5dict(filelist = []): filemd5dict = {} for ori_file in filelist: if Special_path_str notin ori_file: md5 = calcMD5(os.path.realpath(ori_file)) if md5: filemd5dict[ori_file] = md5 return filemd5dict
# 备份所有文件 defbackup_file(filelist=[]): # if len(os.listdir(Special_path['bak'])) == 0: for filepath in filelist: if Special_path_str notin filepath: shutil.copy2(filepath, Special_path['bak'])
if __name__ == '__main__': printu'---------start------------' for value in Special_path: mkdir_p(Special_path[value]) # 获取所有文件路径,并获取所有文件的MD5,同时备份所有文件 ORIGIN_FILE_LIST = getfilelist(CWD) FILE_MD5_DICT = getfilemd5dict(ORIGIN_FILE_LIST) backup_file(ORIGIN_FILE_LIST) # TODO 备份文件可能会产生重名BUG printu'[*] pre work end!' whileTrue: file_list = getfilelist(CWD) # 移除新上传文件 diff_file_list = list(set(file_list) ^ set(ORIGIN_FILE_LIST)) iflen(diff_file_list) != 0: # import pdb;pdb.set_trace() for filepath in diff_file_list: try: f = open(filepath, 'r').read() except Exception, e: break if Special_string notin f: try: printu'[*] webshell find : ' + getUnicode(filepath) shutil.move(filepath, os.path.join(Special_path['webshell'], ntpath.basename(filepath) + '.txt')) except Exception as e: printu'[!] move webshell error, "%s" maybe is webshell.'%getUnicode(filepath) try: f = open(os.path.join(Special_path['log'], 'log.txt'), 'a') f.write('newfile: ' + getUnicode(filepath) + ' : ' + str(time.ctime()) + '\n') f.close() except Exception as e: printu'[-] log error : file move error: ' + getUnicode(e)
# 防止任意文件被修改,还原被修改文件 md5_dict = getfilemd5dict(ORIGIN_FILE_LIST) for filekey in md5_dict: if md5_dict[filekey] != FILE_MD5_DICT[filekey]: try: f = open(filekey, 'r').read() except Exception, e: break if Special_string notin f: try: printu'[*] file had be change : ' + getUnicode(filekey) shutil.move(filekey, os.path.join(Special_path['difffile'], ntpath.basename(filekey) + '.txt')) shutil.move(os.path.join(Special_path['bak'], ntpath.basename(filekey)), filekey) except Exception as e: printu'[!] move webshell error, "%s" maybe is webshell.'%getUnicode(filekey) try: f = open(os.path.join(Special_path['log'], 'log.txt'), 'a') f.write('diff_file: ' + getUnicode(filekey) + ' : ' + getUnicode(time.ctime()) + '\n') f.close() except Exception as e: printu'[-] log error : done_diff: ' + getUnicode(filekey) pass time.sleep(2) # print '[*] ' + getUnicode(time.ctime())