问题根因:
操作系统是Windows,IDE是默认UTF-8编码的。
现在想通过cmd打开具有中文路径的文件,用os.system(command)打不开,返回的错误是乱码看不懂。
cmd的默认编码是cp936,也就是gb2312,我尝试改为utf-8。
解决办法:
前提要pychram的文件编码要设置成gbk,亲测有用,设置成utf-8就执行失败。
将你的命令也就是字符串编码成gb2312,执行结果貌似没用,使用python执行sqlmap批量扫描时,文件路径包含中文,命令启动执行失败。
#_*_conding:utf-8
import os
import shutil
import re
import locale
class SearchFile(object):
def __init__(self,path='.'):
self._path=path
self.abspath=os.path.abspath(self._path) # 默认当前目录
#搜索包含keword关键字的文件完整路径
def findfile(self,keyword,root1):
filelist=[]
for root,dirs,files in os.walk(root1):
print(len(files),root,files)
for name in files:
filelist.append(os.path.join(root, name))
print('...........................................')
for path in filelist:
if os.path.isfile(path) :
if keyword in os.path.split(path)[1] :#如果你要搜索的关键字存在
if os.path.getsize(path)==0:#如果这个文件的大小为0,则删除对应的上级文件夹,否则把文件路径打印出来
shutil.rmtree(os.path.split(path)[0])
else:
print('疑似存在注入的SQLMAP执行结果的log文件路径:', path) # 绝对路径
#将整理后的存在注入的网站的target文件的内容整合(待完善)
def InterFile(self,filepath, b="target"):
filepath_new=filepath+'/'+'疑似存在注入汇总.txt'
p = open(filepath_new,'w')#先将要汇总的文件先清空
p.write("")
p.close()
filelist = []
for root, dirs, files in os.walk(filepath):
for name in files:
filelist.append(os.path.join(root, name))
print('...........................................')
for path in filelist:
if os.path.isfile(path) and b in os.path.split(path)[1]:
fopen = open(path, 'r',encoding='UTF-8')
fileread = fopen.readlines()
fopen.close()
pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') # 匹配模式
for line in fileread:
#print("这是那个链接:",line)
url = re.findall(pattern, line)
#print("这个url:", url)
p=open(filepath_new,'a')
if url[0]!="":
p.write(url[0]+'\r')
else:
p.write(url[1] + '\r')
p.close()
#启动执行sqlmap批量扫描,文件中存在中文,命令执行有编码问题
def Cmd_Sqlmap(self,path,b="疑似存在注入汇总.txt"):
filename = os.path.join(path,b)
os.chdir("E:\Python27\sqlmap")
cmd="python sqlmap.py -m "+filename+' --random-agent --level=3 --threads="3" --batch --users --tables'
print(cmd)
p = os.popen(cmd.encode('gb2312').decode('gb2312'))
print(p.read())
def __call__(self):
while True:
workpath=input('你想更改运行目录吗?回车直接退出 Y/N:')
if(workpath == ''):
break
if workpath=='y' or workpath=='Y':
root=self.abspath # 把当前工作目录作为工作目录
print('当前工作目录:',root)
dirlist=os.listdir() # 列出工作目录下的文件和目录
print(dirlist)
else:
root=input('请输入你要获取的文件目录:')
print('当前工作目录:',root)
keyword=input('输入你要搜索的关键字符:')
if(keyword==''):
break
self.findfile(keyword,root) # 查找带指定字符的文件
print("文件外的root:",root)
self.InterFile(root)
self.Cmd_Sqlmap(root)
if __name__ == '__main__':
search = SearchFile()
search()
command = XXX
os.system(command.encode('gb2312'))
#然后报错说byte不能转为str
#这时你再decode一下
os.system(command.encode('gb2312').decode('gb2312')) # 有encode就有decode
#这样就行了