예제 #1
0
def unzip_file(rar_file_path, dir_path):
    type, ext = get_file_type(rar_file_path)
    # 获取压缩包中的文件列表
    rar = None
    if ext == FILE_EXT_RAR:
        try:
            rar = rarfile.RarFile(rar_file_path)
        except rarfile.BadRarFile:
            rar = zipfile.ZipFile(rar_file_path)
    elif ext == FILE_EXT_ZIP:
        try:
            rar = zipfile.ZipFile(rar_file_path)
        except zipfile.BadZipfile:
            rar = rarfile.RarFile(rar_file_path)
    else:
        logger.error("file ext is not zip or rar %s" % rar_file_path)

    # 解压文件
    if not os.path.exists(dir_path):
        logger.error("unzip_file() dir_path %s not exists" % dir_path)

    if isinstance(rar, rarfile.RarFile):
        rar.extractall(dir_path)
    else:
        zip_extract_all(rar_file_path, dir_path)
    os.remove(rar_file_path)

    for parent, dir_names, file_names in os.walk(dir_path):  # 三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
        for file_name in file_names:
            file_path = os.path.join(parent, file_name)  # 输出文件路径信息
            type, ext = get_file_type(file_name)
            if type == FILE_TYPE_ZIP[0]:
                unzip_file(file_path, parent)
예제 #2
0
def unZip(filepath):
    path = __temp__ + '/subtitles/'
    if os.path.isdir(path): shutil.rmtree(path)
    if not os.path.isdir(path): os.mkdir(path)

    if filepath.lower().endswith('zip'):
        zip_file = zipfile.ZipFile(filepath, 'r')
        for names in zip_file.namelist():
            if type(names) == str and names[-1] != '/':
                utf8name = names.decode('gbk')
                data = zip_file.read(names)
                fo = open(path + utf8name, "w")
                fo.write(data)
                fo.close()
            else:
                zip_file.extract(names, path)
        return getFileList(path)
    if filepath.lower().endswith('rar'):
        zip_file = rarfile.RarFile(filepath, 'r')
        for names in zip_file.namelist():
            if type(names) == str and names[-1] != '/':
                utf8name = names.decode('gbk')
                data = zip_file.read(names)
                fo = open(path + utf8name, "w")
                fo.write(data)
                fo.close()
            else:
                zip_file.extract(names, path)
        return getFileList(path)
예제 #3
0
    def uncompress(self):
        """解压缩文件"""
        self.uncompressDir = os.path.join(self.tempDir, self.basename)
        if zipfile.is_zipfile(self.inputPath):
            print("压缩文件格式为zip,开始解压...")
            zFile = zipfile.ZipFile(self.inputPath, 'r')
            for f in zFile.namelist():
                zFile.extract(f, self.uncompressDir)
                self.uncompressFileList.append(
                    os.path.join(self.uncompressDir, f))

        elif tarfile.is_tarfile(self.inputPath):
            print("压缩文件格式为tar,开始解压...")
            tFile = tarfile.open(self.inputPath)
            for f in tFile.getnames():
                tFile.extract(f, self.uncompressDir)
                self.uncompressFileList.append(
                    os.path.join(self.uncompressDir, f))

        elif rarfile.is_rarfile(self.inputPath):
            print("压缩文件格式为rar,开始解压...")
            rFile = rarfile.RarFile(self.inputPath, mode='r')
            for f in rFile.namelist():
                rFile.extract(f, self.uncompressDir)
                self.uncompressFileList.append(
                    os.path.join(self.uncompressDir, f))
        else:
            print("无法识别的压缩文件格式!")
            return False

        self.classifyUncompressFile()  # 整理解压缩文件

        print("解压缩文件成功.")
예제 #4
0
def unrar_operation(ta_path):
    print("\n>>> Judge_rar_version_pkg")
    print("doing unrar, please wait...")

    files = os.listdir(ta_path)
    for file in files:
        if file.endswith(".zip"):
            return 0
        elif file.endswith(".rar"):
            ver_dir = os.path.splitext(file)[0]
            ver_rar = os.path.join(ta_path, ver_dir + '.rar')
            #cmd = "start winrar x -y -ibck " + ver_rar + " " + ta_path
            #file_news = os.path.splitext(file)[0] + '.zip'
            #small_board = os.path.splitext(file)[0] + '_small_board' #_Smallboard
            #main_board  = os.path.splitext(file)[0] + '_main_board'  #_Mainboard
            print("ver dir    name: {}".format(ver_dir))
            print("ver rar    name: {}".format(ver_rar))
            print("ta path    name: {}".format(ta_path))
            rf = rarfile.RarFile(ver_rar)
            rf.extractall(ta_path)

            #print ("cmd            : {}".format(cmd))
            #print ("smallboard name: {}".format(small_board))
            #print ("mainboard  name: {}".format(main_board))

            rar_file = os.path.join(ta_path, file)
            cmd = "del " + rar_file
            os.system(cmd)
            print("cmd: {}".format(cmd))
            print("unrar success, delete .rar success.")
        else:
            print("No such files of .zip or .rar package!!!")
            exit
예제 #5
0
def unrar_file(rar_path, year):
    year_ru = year[2:]
    unrar_path = "D:\\金融数据\\data\\testdir11-18\\ru" + year_ru + "01" + "_" + str(
        int(year) - 1)

    isExists = os.path.exists(unrar_path)
    if isExists:
        pass
    else:
        unrar_path = os.mkdir(unrar_path)
    print(unrar_path)
    rar = rarfile.RarFile(rar_path)
    rar.setpassword("www.jinshuyuan.net")

    #     print('jfasdl;fldjksa;')
    name_list = rar.namelist()
    for name in name_list:
        if name.startswith('sc\\ru' + str(year_ru) + '01') or name.startswith(
                'sc\\ru' + str(int(year_ru) + 1) + '01'):
            file_name = name
            if os.path.exists(unrar_path):

                print(file_name + unrar_path)
                rar.extract(member=file_name, path=unrar_path)
            else:
                print("文件夹创建失败!")
예제 #6
0
def un_rar(file_path):
    """ unrar file """
    file_basename = os.path.basename(file_path)
    dir_path = os.path.splitext(file_path)[0]
    # outFile = CreatDir.creat_dir(dir_path, 1)
    outFile = "/Users/silence/Desktop/Temp/test/test/"
    file_list = []
    index = 0

    with rarfile.RarFile(file_path, 'r') as rar:
        file_name_list = rar.namelist()
        file_list = list(file_name_list)
        # os.chdir(outFile)
        # rar.extractall()
        # rar.close()
        # return
        # 需要密码
        if rar.needs_password():
            file_list = list(file_name_list)
            os.chdir(outFile)
            rar.extractall()
            pass
        # 不需要密码
        else:
            for file_name in file_name_list:
                index += 1
                file_list.append(file_name)
                print "==== {}".format(file_name)
                rar.extract(file_name, './')
    # os.chdir(outFile)
    # rar.extractall()
    # rarFile.close()
    print "已解压文件 {} 中: {}个文件, 目标文件夹为: {}".format(file_basename, len(file_list),
                                                 os.path.basename(outFile))
예제 #7
0
def Extractrar(rf):
    rfs = rarfile.RarFile(rf)
    nl = rfs.namelist()
    namedir = os.path.splitext(os.path.basename(rf))[0]
    if len(nl) > 0:
        rfs.extractall(namedir + '/')
    return
예제 #8
0
def ExtractArchive(archive, dest, current_folder, overwrite, go_to_folder):
    response = {'path': current_folder}
    try:
        if archive.endswith('.rar'):
            from unrar import rarfile
            rar = rarfile.RarFile(archive)
            members = rar.namelist()
            errors, extracted = _extract_members(rar, dest, members, overwrite)
        elif archive.endswith('.zip'):
            import zipfile
            zip = zipfile.ZipFile(archive, 'r')
            members = zip.namelist()
            errors, extracted = _extract_members(zip, dest, members, overwrite)
        elif archive.endswith('.tar.gz'):
            import tarfile
            tar = tarfile.open(archive, 'r:gz')
            members = tar.getnames()
            errors, extracted = _extract_members(tar, dest, members, overwrite)
        else:
            return False, "File %s not an archive" % archive
        if go_to_folder:
            response['path'] = dest
        folders = ""
        if 'root_folder' in session and session['root_folder'] not in (None,
                                                                       'None',
                                                                       ''):
            folders = DrawFolderTree(session['root_folder'])
        response['folders'] = folders
        response['errors'] = errors
        response['extracted'] = extracted
        return True, response
    except Exception as ex:
        return False, str(ex)
예제 #9
0
 def unrar_movie(movie_to_unrar: str):
     try:
         rar = rarfile.RarFile(movie_to_unrar)
         rar.extractall()
         positive_outcome("Successfully extracted!")
     except:
         negative_outcome("Exception has occurred!")
예제 #10
0
def get_csv_from_rar():
    """将rar文件解压到本地tmp文件目录下"""
    # TODO 筛选文件
    file_list = list(
        filter(lambda x: date_pattern.findall(x)[0] and x.endswith('.rar'),
               files))

    global stock_code_pattern, logger, file_status
    while 1:
        try:
            file = file_list.pop()
            try:
                rar = rarfile.RarFile(file, pwd=r'www.licai668.cn')
            except:
                logger.info("{} rar failed".format(file))
                continue
            date = long_date_pattern.findall(file)[0] if len(long_date_pattern.findall(file)) else \
            date_pattern.findall(file)[0]
            rar_csv = list(
                filter(
                    lambda x: stock_code_pattern.findall(x)[0] in
                    target_file_codes, rar.namelist()))
            tmp_dir = r'tmp\\%s' % date
            if not os.path.exists(tmp_dir):
                os.mkdir(tmp_dir)
        except IndexError:
            print('file over')
            logger.info('rar file read over!!!')
            break
        for csv in rar_csv:
            rar.extract(csv, tmp_dir)
    file_status = True
예제 #11
0
    def create(self, validated_data):
        regiontask = RegionTask.objects.create(**validated_data)
        file_path = regiontask.file.path
        print file_path

        # 需要进入celery进行空间库操作
        # 解压zip文件
        file_dir = os.path.dirname(file_path)
        # r = zipfile.is_zipfile(file_path)
        # if r:
        #     fz = zipfile.ZipFile(file_path, 'r')
        #     for file in fz.namelist():
        #         fz.extract(file,file_dir)
        # else:
        #     print('This is not zip')
        #
        # filename = file_path.split("\\")[-1].split(".zip")[0]
        # unzipfile = os.path.join(file_dir,filename)
        # print unzipfile

        # 解压rar文件
        f = rarfile.is_rarfile(file_path)
        if f:
            fz = rarfile.RarFile(file_path, 'r')
            for file in fz.namelist():
                fz.extract(file, file_dir)
        else:
            print('This is not rar')
        filename = file_path.split("\\")[-1].split(".rar")[0]
        unrarfile = os.path.join(file_dir, filename)
        print unrarfile

        return regiontask
예제 #12
0
def main():
    pwds = []
    try:
        passwords = open(pwd_file, 'r')
        for pwd in passwords:
            pwd = pwd.strip()
            pwds.append(pwd)
    except:
        print("\033[41;1mCan't use the password file %s\033[0m" % pwd_file)

    if zip_file:
        try:
            zfile = zipfile.ZipFile(zip_file, 'r')
            for pwd in pwds:
                t = threading.Thread(target=ZipBrute, args=(zfile, pwd))
                t.start()
                t.join()
        except Exception:
            print("\033[41;1mCan't use the zip file %s\033[0m" % zip_file)

    if rar_file:
        try:
            rfile = rarfile.RarFile(rar_file, 'r')
            for pwd in pwds:
                t = threading.Thread(target=RarBrute, args=(rfile, pwd))
                t.start()
                t.join()
        except:
            print("\033[41;1mCan't use the rar file %s\033[0m" % rar_file)
예제 #13
0
def main(argv):
    inputfile = ''
    wordfile = ''
    try:
        opts, args = getopt.getopt(argv, "hi:w:", ["ifile=", "wfile="])
    except getopt.GetoptError:
        print('fcrackrar.py -i <inputfile> -w <wordlistfile>')
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print('fcrackrar.py -i <inputfile> -w <wordlistfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-w", "--wfile"):
            wordfile = arg

    if inputfile == '' or wordfile == '':
        print('fcrackrar.py -i <inputfile> -w <wordlistfile>')
        sys.exit(2)

    rar = rarfile.RarFile(inputfile)
    names = rar.namelist()
    filename = ".".join(rar.filename.split(".")[0:-1])

    wordlist = open(wordfile, "r")
    password = find_pass(rar, names[0], wordlist)

    if password == "":
        print("!!! KEY CANNOT BE FOUND IN WORDLIST !!!")
    else:
        extract_files(rar, password, names, filename)
예제 #14
0
def test_cover_hashing():

    # Find the archive
    test_path = path.dirname(path.realpath(__file__))
    cbr_path = path.join(
        test_path,
        'data/Injustice - Year Zero 006 (2020) (digital) (Son of Ultron-Empire).cbr'
    )
    cbr_path = path.abspath(cbr_path)

    rar = rarfile.RarFile(cbr_path)

    files = rar.namelist()

    images = [
        x for x in files
        if x.lower().endswith('jpg') or x.lower().endswith('jpeg')
        or x.lower().endswith('png') or x.lower().endswith('gif')
    ]
    images.sort()

    cover_file = images[0]

    image_data = rar.read(cover_file)

    img = Image.open(io.BytesIO(image_data))
    img.save('out.jpg', 'PNG')

    cover_img_hash = imagehash.phash(img)
    cover_hash = str(cover_img_hash)

    pass
예제 #15
0
def extractAll():
    count = 0
    for file in os.listdir(cpy_path):
        fileName = cpy_path + '/' + file

        # check is the zip file name is in correct format
        x = re.search(
            "(^IT|it|It|iT)([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])",
            file)
        if (x != None):

            ID = file[
                0:
                10]  # take first 10 charactors of file name, which is the student ID

            mkdir_command = "mkdir " + ext_path + "/" + ID
            os.system(mkdir_command)

            ext_dir = ext_path + "/" + ID

            if file.endswith(tuple(arc_ext)):
                Archive(fileName).extractall(ext_dir)

            elif file.endswith(".rar"):
                rar = rarfile.RarFile(fileName)
                rar.extractall(ext_dir)

            else:
                shutil.copy2(fileName, rjc_path)
        else:
            count = count + 1
            shutil.copy2(fileName, rjc_path)

    print("Total rejected files : ", count)
예제 #16
0
def un_rar(filename):
    rar=rarfile.RarFile(filename)
    if os.path.isdir(os.path.splitext(filename)[0]):
        pass
    else:
        os.mkdir(os.path.splitext(filename)[0])
    rar.extractall(os.splitext(filename)[0])
예제 #17
0
 def uncompress(self):
     """解压缩文件"""
     self.uncompressDir = os.path.join(self.tempDir, self.basename)
     if zipfile.is_zipfile(self.inputPath):
         self.logObj.info("压缩文件格式为zip,开始解压...")
         zFile = zipfile.ZipFile(self.inputPath, 'r')
         for f in zFile.namelist():
             zFile.extract(f, self.uncompressDir)
             self.uncompressFile[f] = {'path': os.path.join(self.uncompressDir, f),
                                       'ext': os.path.splitext(f)[1],
                                       'type': f.replace(self.basename, '').replace(os.path.splitext(f)[1], '')
                                       }
     elif tarfile.is_tarfile(self.inputPath):
         self.logObj.info("压缩文件格式为tar,开始解压...")
         tFile = tarfile.open(self.inputPath)
         for f in tFile.getnames():
             tFile.extract(f, self.uncompressDir)
             self.uncompressFile[f] = {'path': os.path.join(self.uncompressDir, f),
                                       'ext': os.path.splitext(f)[1],
                                       'type': f.replace(self.basename, '').replace(os.path.splitext(f)[1], '')
                                       }
     elif rarfile.is_rarfile(self.inputPath):
         self.logObj.info("压缩文件格式为rar,开始解压...")
         rFile = rarfile.RarFile(self.inputPath, mode='r')
         for f in rFile.namelist():
             rFile.extract(f, self.uncompressDir)
             self.uncompressFile[f] = {'path': os.path.join(self.uncompressDir, f),
                                       'ext': os.path.splitext(f)[1],
                                       'type': f.replace(self.basename, '').replace(os.path.splitext(f)[1], '')
                                       }
     else:
         self.logObj.error("无法识别的压缩文件格式!")
         return False
     self.logObj.info("解压缩文件成功.")
예제 #18
0
def jieyarar(localfile, destpath):
    basefile = os.path.basename(localfile)
    dirname = os.path.splitext(basefile)
    destpath = destpath + dirname[0]
    unrfile = rarfile.RarFile(localfile)
    unrfile.extractall(destpath)
    print("%s   已完成解压" % localfile)
예제 #19
0
def Un_rar(rardir,rarname,Archiverar):
    """
    解压rar文件
    rardir: 压缩包的存放路径
    rarname: 要解压压缩包的文件名
    Archiverar: 解压缩后的存放路径.
    filestat: 判断文件后缀
    """

    try:
        Unrar_path = os.path.join(rardir,rarname)
        r = rarfile.RarFile(Unrar_path)

        if r:
            if os.path.isdir(Archiverar):
                shutil.rmtree(Archiverar)
                print("如果存放目录已存在,就删除该存放目录.")

                os.mkdir(Archiverar)
                print("解压后的存放目录已经成功创建.")
                
                r.extractall(Archiverar)
                print("解压完成,请查看解压后的存放目录")  

            else:
                os.mkdir(Archiverar)
                print("解压后的存放目录已经成功创建.")
                
                r.extractall(Archiverar)
                print("解压完成,请查看解压后的存放目录")        
    except Exception as e:
        return e
예제 #20
0
 def rarTest(self):
     try:
         rarc = rarfile.RarFile(self.path)
     except:  # InvalidRARArchive:
         return False
     else:
         return True
예제 #21
0
def crack(rfName, pfName):
    rf = rarfile.RarFile(rfName)
    cnt = 0
    with open(pfName, 'rb') as pf:
        for line in pf:
            cnt += 1
            password = line.strip('\r\n')
            print '[*] testing: %s' % password
            try:
                rf.extractall(pwd=password)
                print '[+] password is %s' % password
                return True
            except RuntimeError as e:
                errMessage = e.args[0]
                if 'Bad' in errMessage:
                    print '[-] bad'
                else:
                    print '[-] unknown error'
            except rarfile.BadRarFile as e:
                errMessage = e.args[0]
                if 'Bad RAR archive data' in errMessage:
                    print '[-] bad'
                else:
                    print '[-] unknown error'
            finally:
                print '[*] %d attempts' % cnt
예제 #22
0
def append_mapnums():
    conn = psycopg2.connect(dbname=u"mmanageV8.0",
                            user=u"postgres",
                            password=u"Lantucx2018",
                            host=u"localhost",
                            port=u"5432")
    cur = conn.cursor()
    SQL = "SELECT name,file FROM taskpackages_taskpackage"
    cur.execute(SQL)
    name_file = cur.fetchall()
    print name_file
    file_path = ''

    file_dir = os.path.dirname(file_path)         # 解压后文件保存路径
    file_name = os.path.basename(file_path)       # 文件名

    z = zipfile.is_zipfile(file_path)
    r = rarfile.is_rarfile(file_path)
    if z:
        # -ibck: 后台运行; -o+:覆盖已存在文件
        rar_command = '"C:\Program Files\WinRAR\WinRAR.exe" x %s %s -ibck -o+' % (file_path, file_dir)
        rar_command = rar_command.encode('gbk')
        os.system(rar_command)
        print rar_command.decode('gbk')
        print u"解压成功"
    elif r:
        fz = rarfile.RarFile(file_path, 'r')
        for file in fz.namelist():
            fz.extract(file, file_dir)
        print u"解压成功"
    else:
        print(u'This is not zip or rar')
        return False


    taskpath =u"E:\\RGSManager\\celery_app\\测试融合\\Source"
    path = os.path.join(taskpath, u"接图表.gdb", u"DLG_50000", u"GBmaprange")
    # 查找任务包名字和图号
    cursor = arcpy.da.SearchCursor(path, ["new_jbmapn"])
    taskpackage_name = "任务包1号"
    try:

        for row in cursor:
            SQL = "SELECT mapnums from taskpackages_taskpackage where name='{0}'".format(taskpackage_name)  # 按任务包名字查询原mapnums
            cur.execute(SQL)
            mapnums = cur.fetchall()
            old_mapnum = mapnums[0][0]      # 提取原有mapnums

            if old_mapnum is None:
                SQL = "UPDATE taskpackages_taskpackage set mapnums='{0}' where name='{1}'".format(row[0], taskpackage_name)
            else:
                SQL = "UPDATE taskpackages_taskpackage set mapnums='{0}' where name='{1}'".format(old_mapnum +","+ row[0], taskpackage_name)
            print SQL                       # 添加mapnums
            cur.execute(SQL)
            conn.commit()
        conn.close()
    except Exception as e:
        # e = str(e).decode('gbk')
        print [e, ]
예제 #23
0
def un_rar(filename):
    rar = rarfile.RarFile(filename)
    #判断同名文件夹是否存在,若不存在则创建同名文件夹
    if os.path.isdir(os.path.splitext(filename)[0]):
        pass
    else:
        os.mkdir(os.path.splitext(filename)[0])
        rar.extractall(os.path.splitext(filename)[0])
예제 #24
0
def un_rar(filename):  # filename是文件的绝对路径
    rar = rarfile.RarFile(filename)
    # 判断是否存在同名文件夹,若不存在则创建同名文件夹:
    if os.path.isdir(os.path.splitext(filename)[0]):
        pass
    else:
        os.mkdir(os.path.splitext(filename)[0])
    rar.extractall(os.path.splitext(filename)[0])
예제 #25
0
 def rarTest(self):
     try:
         rarfile.RarFile(self.path)
     except Exception as e:
         # logging.exception(e)
         return False
     else:
         return True
예제 #26
0
def extract_rar(f, d):
    try:
        from unrar import rarfile
    except LookupError:
        print("[Error]Please install unrar library")
        sys.exit(1)
    rar_file = rarfile.RarFile(f)
    rar_file.extractall(d)
예제 #27
0
def getFileStream(filename):
    if filename.endswith('.zip'):
        fp = zipfile.ZipFile(filename)
    elif filename.endswith('.rar'):
        fp = rarfile.RarFile(filename)
    else:
        fp = None
    return fp
예제 #28
0
 def unpackRar(self, comicFile, dirPath):
     if rarfile.is_rarfile(comicFile):
         rar = rarfile.RarFile(comicFile)
         os.mkdir(dirPath)
         rar.extractall(dirPath)
     else:
         comicError(comicFile, "rarErr")
         return
예제 #29
0
def jieyarar(localfile,destpath):
    basefile = os.path.basename(localfile)
    dirname = os.path.splitext(basefile)
    destpath = destpath  + dirname[0]
    print(destpath)
    #os.mkdir(destpath)

    unrfile = rarfile.RarFile(localfile)
    unrfile.extractall(destpath)
예제 #30
0
 def archive(self):
     try:
         archive = rarfile.RarFile(self.archive_file, "r")
         yield archive
     except Exception:
         self.logger.error("Failed to complete archive op for %s" %
                           self.archive_file,
                           exc_info=True)
         raise exceptions.UnknownArchiveError()