您的位置:首页 > 编程语言 > Python开发

Python:利用pexpect库直接解压缩加密的zip文件。

2012-05-02 20:15 661 查看
其实 'unzip -P password zipfile' 就可以自动解压缩加密文件。但是是为了熟悉一下python库pexpect。用python写了一个自动解压缩zip文件的代码。这样的代码可以被服务器端页面脚本调用,来解压缩上传的加密文件,等。

1. 因为pexpect库不是python自带的标准库,所以在使用的时候要先下载,fedora的用户可以直接yum下载。

su -c 'yum install pexpect'

或者下载gz文件自行安装:

http://pypi.python.org/pypi/pexpect/#downloads

关于pexpect库的介绍,这里是官方网站,里面有pexpect库结构和功能的详细介绍:

http://pexpect.sourceforge.net/pexpect.html

2. 进入正题,代码如下:

#!/usr/bin/env python
'''
@version: 1.0
@author: Nathan Huang
'''
import pexpect
import os
import sys
import getopt

def unzip_encrypted_file(abspath='', filename='', mypassword=''):
# check the folder and file
if os.path.isdir(abspath) and  os.path.isfile(os.path.join(abspath, filename)) and mypassword:
# go into the folder
os.chdir(abspath)
# unzip encrypted file
child=pexpect.spawn("unzip %s" % os.path.join(abspath, filename))
try:
child.expect("password:")
child.sendline(mypassword)
child.wait()
except ExceptionPexpect:
print "Error"
else:
print "path or file does not exists!"
sys.exit(2)

def usage():
print "unzipencryptedfile -h -d -n -p"
print "-h help"
print "-d path"
print "-n filename"
print "-p password"

def main():
abspath=''
filename=''
mypassword=''
#get args from cmdline
try:
opts, args = getopt.getopt(sys.argv[1:], "hd:n:p:")
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)

for o, a in opts:
if o=='-h':
usage()
sys.exit(0)
elif o=='-d':
abspath=a
elif o=='-n':
filename=a
elif o=='-p':
mypassword=a
#execute unzip_encrypted_file()
unzip_encrypted_file(abspath, filename, mypassword)

if __name__=='__main__':
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: