Python:利用pexpect库直接解压缩加密的zip文件。
其实 '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. 进入正题,代码如下:
1 #!/usr/bin/env python 2 ''' 3 @version: 1.0 4 @author: Nathan Huang 5 ''' 6 import pexpect 7 import os 8 import sys 9 import getopt 10 11 def unzip_encrypted_file(abspath='', filename='', mypassword=''): 12 # check the folder and file 13 if os.path.isdir(abspath) and os.path.isfile(os.path.join(abspath, filename)) and mypassword: 14 # go into the folder 15 os.chdir(abspath) 16 # unzip encrypted file 17 child=pexpect.spawn("unzip %s" % os.path.join(abspath, filename)) 18 try: 19 child.expect("password:") 20 child.sendline(mypassword) 21 child.wait() 22 except ExceptionPexpect: 23 print "Error" 24 else: 25 print "path or file does not exists!" 26 sys.exit(2) 27 28 def usage(): 29 print "unzipencryptedfile -h -d -n -p" 30 print "-h help" 31 print "-d path" 32 print "-n filename" 33 print "-p password" 34 35 def main(): 36 abspath='' 37 filename='' 38 mypassword='' 39 #get args from cmdline 40 try: 41 opts, args = getopt.getopt(sys.argv[1:], "hd:n:p:") 42 except getopt.GetoptError, err: 43 print str(err) 44 usage() 45 sys.exit(2) 46 47 for o, a in opts: 48 if o=='-h': 49 usage() 50 sys.exit(0) 51 elif o=='-d': 52 abspath=a 53 elif o=='-n': 54 filename=a 55 elif o=='-p': 56 mypassword=a 57 #execute unzip_encrypted_file() 58 unzip_encrypted_file(abspath, filename, mypassword) 59 60 if __name__=='__main__': 61 main()