#! /usr/bin/python -tt
import os
def searchFile(path1,ext1,fileName1):
pathList = []
for root, dirs, files in os.walk(path1):
for file in files:
if file.endswith(ext1):
pathList.append(os.path.join(root,file))
print "-----The file is present under the below path------\n"
for ele in pathList:
if fileName1 in ele:
print ele
def main():
path = raw_input("Please enter the path you wish to spider. Also make sure that the files/subfolders have the correct permissions.\n")
ext = raw_input("Enter the extension you wish to search/ find. Eg: For class files enter .class / For text file enter .txt \n")
fileName = raw_input("Enter the filename without extension. Eg For example.class, input only 'example'\n")
searchFile(path,ext,fileName)
if __name__ == '__main__':
main()
使用普通的文件/子文件夹,它可以正确获取路径/文件名,但是当通过'jars'进行搜索时,python脚本不会返回任何内容。 如何让上面的脚本扫描Jars?
答案 0 :(得分:4)
Jars类似于Zip档案。要扫描jar文件,您可以使用pyhton模块zipfile获取其内容列表,或者您甚至可以阅读内容。您可以使用Zipfile.namelist()方法获取jar中的内容列表,然后使用此列表检查您要搜索的文件是否存在。 下面是一个示例代码,它获取jar中存在的文件列表。
import zipfile
archive = zipfile.ZipFile('<path to jar file>/test.jar', 'r')
list = archive.namelist()
如果你在comaand line或terminal中运行它,你会得到如下输出:
['file1.class','file2.class']
其中file1和file2是我在jar文件中的两个.class文件
答案 1 :(得分:0)
#! /usr/bin/python -tt
import os
import time
import zipfile
def searchFile(path1,ext1,fileName1):
pathList1 = []
list = []
for root, dirs, files in os.walk(path1):
for file in files:
if file.endswith(ext1):
pathList1.append(os.path.join(root,file))
print "-----All The jar files present got collected------\n"
for ele in pathList1:
archive = zipfile.ZipFile(ele,'r')
list1 = archive.namelist()
newList1 = [ele+item for item in list1]
list = list + newList1
print "-----Jar files unzip done------\n"
print "----- Now fetching filename along with the path------\n"
for ele in list:
if fileName1 in ele:
print ele
def main():
path = raw_input("Please enter the path you wish to spider. Also make sure that the files/subfolders have the correct permissions.\n")
fileName = raw_input("Enter the filename '\n")
fileName = "/" + fileName
searchFile(path,".jar",fileName)
if __name__ == '__main__':
main()
@bonney @heinst ..为你们干杯,我终于写了上面的剧本来做最后的工作。
答案 2 :(得分:0)
文件名:searchForFiles.py
import os, zipfile, glob, sys
def main():
searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see batch file code in second code section)
listOfFilesInJar = []
for file in glob.glob("*.jar"):
archive = zipfile.ZipFile(file, 'r')
for x in archive.namelist():
if str(searchFile) in str(x):
listOfFilesInJar.append(file)
for something in listOfFilesInJar:
print("location of "+str(searchFile)+": ",something)
if __name__ == "__main__":
sys.exit(main())
您可以通过使用以下文本制作.bat文件来轻松运行此文件(将“ AddWorkflows.class”替换为要搜索的文件):
(文件:CallSearchForFiles.bat)
@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause
您可以双击CallSearchForFiles.bat轻松运行它。