给我转为python3的代码
时间: 2024-10-19 16:16:34 浏览: 14
Python3将jpg转为pdf文件的方法示例
将给定的Python 2代码转换为Python 3代码需要进行一些语法和函数调用的调整。以下是转换后的代码:
```python
import os
import hashlib
import shutil
import ntpath
import time
CWD = os.getcwd()
FILE_MD5_DICT = {} # 文件MD5字典
ORIGIN_FILE_LIST = []
Special_path_str = 'drops_JWI96TY7ZKNMQPDRUOSG0FLH41A3C5EXVB82'
bakstring = 'bak_EAR1IBM0JT9HZ75WU4Y3Q8KLPCX26NDFOGVS'
logstring = 'log_WMY4RVTLAJFB28960SC3KZX7EUP1IHOQN5GD'
webshellstring = 'webshell_WMY4RVTLAJFB28960SC3KZX7EUP1IHOQN5GD'
difffile = 'diff_UMTGPJO17F82K35Z0LEDA6QB9WH4IYRXVSCN'
Special_string = 'drops_log' # 免死金牌
UNICODE_ENCODING = "utf-8"
INVALID_UNICODE_CHAR_FORMAT = r"\?%02x"
spec_base_path = os.path.realpath(os.path.join(CWD, Special_path_str))
Special_path = {
'bak': os.path.realpath(os.path.join(spec_base_path, bakstring)),
'log': os.path.realpath(os.path.join(spec_base_path, logstring)),
'webshell': os.path.realpath(os.path.join(spec_base_path, webshellstring)),
'difffile': os.path.realpath(os.path.join(spec_base_path, difffile)),
}
def isListLike(value):
return isinstance(value, (list, tuple, set))
def getUnicode(value, encoding=None, noneToNull=False):
if noneToNull and value is None:
return None
if isListLike(value):
value = [getUnicode(_, encoding, noneToNull) for _ in value]
return value
if isinstance(value, str):
return value
elif isinstance(value, bytes):
while True:
try:
return value.decode(encoding or UNICODE_ENCODING)
except UnicodeDecodeError as ex:
try:
return value.decode(UNICODE_ENCODING)
except:
value = value[:ex.start] + "".join(INVALID_UNICODE_CHAR_FORMAT % ord(_) for _ in value[ex.start:ex.end]) + value[ex.end:]
else:
try:
return str(value)
except UnicodeDecodeError:
return str(value).encode(errors="ignore").decode()
def mkdir_p(path):
import errno
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def getfilelist(cwd):
filelist = []
for root, subdirs, files in os.walk(cwd):
for filepath in files:
originalfile = os.path.join(root, filepath)
if Special_path_str not in originalfile:
filelist.append(originalfile)
return filelist
def calcMD5(filepath):
try:
with open(filepath, 'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
return hash
except Exception as e:
print(f'[!] getmd5_error : {getUnicode(filepath)}')
print(getUnicode(e))
try:
ORIGIN_FILE_LIST.remove(filepath)
FILE_MD5_DICT.pop(filepath, None)
except KeyError as e:
pass
def getfilemd5dict(filelist=[]):
filemd5dict = {}
for ori_file in filelist:
if Special_path_str not in ori_file:
md5 = calcMD5(os.path.realpath(ori_file))
if md5:
filemd5dict[ori_file] = md5
return filemd5dict
def backup_file(filelist=[]):
for filepath in filelist:
if Special_path_str not in filepath:
shutil.copy2(filepath, Special_path['bak'])
if __name__ == '__main__':
print(u'---------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
print(u'[*] pre work end!')
while True:
file_list = getfilelist(CWD)
# 移除新上传文件
diff_file_list = list(set(file_list) ^ set(ORIGIN_FILE_LIST))
if len(diff_file_list) != 0:
for filepath in diff_file_list:
try:
f = open(filepath, 'r').read()
except Exception as e:
break
if Special_string not in f:
try:
print(f'[*] webshell find : {getUnicode(filepath)}')
shutil.move(filepath, os.path.join(Special_path['webshell'], ntpath.basename(filepath) + '.txt'))
except Exception as e:
print(f'[!] move webshell error, "{getUnicode(filepath)}" maybe is webshell.')
try:
with open(os.path.join(Special_path['log'], 'log.txt'), 'a') as f:
f.write(f'newfile: {getUnicode(filepath)} : {time.ctime()}\n')
except Exception as e:
print(f'[-] 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.get(filekey):
try:
f = open(filekey, 'r').read()
except Exception as e:
break
if Special_string not in f:
try:
print(f'[*] 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:
print(f'[!] move webshell error, "{getUnicode(filekey)}" maybe is webshell.')
try:
with open(os.path.join(Special_path['log'], 'log.txt'), 'a') as f:
f.write(f'diff_file: {getUnicode(filekey)} : {time.ctime()}\n')
except Exception as e:
print(f'[-] log error : done_diff: {getUnicode(filekey)}')
time.sleep(2)
# print('[*] ' + getUnicode(time.ctime()))
```
### 主要改动点:
1. **字符串编码**:将 `unicode` 和 `basestring` 替换为 `str` 和 `bytes`。
2. **异常处理**:将 `except Exception, e` 改为 `except Exception as e`。
3. **文件操作**:使用 `with open(...)` 来打开文件,以确保文件正确关闭。
4. **打印语句**:将 `print u'...'` 改为 `print(f'...')`。
5. **其他小改动**:如 `NULL` 改为 `None`,`list(getUnicode(...))` 改为列表推导式等。
希望这些改动能帮助你顺利运行Python 3版本的代码。如果有任何问题,请随时告诉我!
阅读全文