Python-network-programming-python-ftp

提供:Dev Guides
移動先:案内検索

Python-FTP

*FTP* またはFile Transfer Protocolは、ネットワーク内のコンピューター間でファイルを転送するために使用されるよく知られたネットワークプロトコルです。 クライアントサーバーアーキテクチャで作成され、ユーザー認証と一緒に使用できます。 認証なしでも使用できますが、安全性は低下します。 現在の作業ディレクトリと他のフラグを維持するFTP接続、および各転送には、データが転送されるセカンダリ接続が必要です。 最も一般的なWebブラウザは、FTPサーバーでホストされているファイルを取得できます。

FTPクラスのメソッド

Pythonでは、ファイルを転送するときにファイルをリストするために、以下に必要なメソッドを持つモジュール ftplib を使用します。

Method Description
pwd() Current working directory.
cwd() Change current working directory to path.
dir([path[,…​[,cb]]) Displays directory listing of path. Optional call-back cb passed to retrlines().
storlines(cmd, f) Uploads text file using given FTP cmd - for example, STOR file name.
storbinary(cmd,f[, bs=8192]) Similar to storlines() but is used for binary files.
delete(path) Deletes remote file located at path.
mkd(directory) Creates remote directory.
exception ftplib.error_temp Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received..
exception ftplib.error_perm Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received..
connect(host[, port[, timeout]]) Connects to the given host and port. The default port number is 21, as specified by the FTP protocol..
quit() Closes connection and quits.

以下は、上記のメソッドのいくつかの例です。

ファイルのリスト

以下の例では、ftpサーバーへの匿名ログインを使用し、現在のディレクトリのコンテンツを一覧表示します。 ファイルとディレクトリの名前を処理し、リストとして保存します。 次に、それらを印刷します。

import ftplib

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.dir(data.append)

ftp.quit()

for line in data:
    print "-", line

上記のプログラムを実行すると、次の出力が得られます-

- lrwxrwxrwx    1 0        0               1 Nov 13  2012 ftp -> .
- lrwxrwxrwx    1 0        0               3 Nov 13  2012 mirror -> pub
- drwxr-xr-x   23 0        0            4096 Nov 27  2017 pub
- drwxr-sr-x   88 0        450          4096 May 04 19:30 site
- drwxr-xr-x    9 0        0            4096 Jan 23  2014 vol

ディレクトリを変更する

以下のプログラムは、ftplibモジュールで利用可能なcwdメソッドを使用してディレクトリを変更し、必要なコンテンツを取得します。

import ftplib

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.cwd('/pub/')          change directory to/pub/
ftp.dir(data.append)

ftp.quit()

for line in data:
    print "-", line

上記のプログラムを実行すると、次の出力が得られます-

- lrwxrwxrwx    1 504      450            14 Nov 02  2007 FreeBSD -> os/BSD/FreeBSD
- lrwxrwxrwx    1 504      450            20 Nov 02  2007 ImageMagick -> graphics/ImageMagick
- lrwxrwxrwx    1 504      450            13 Nov 02  2007 NetBSD -> os/BSD/NetBSD
- lrwxrwxrwx    1 504      450            14 Nov 02  2007 OpenBSD -> os/BSD/OpenBSD
- -rw-rw-r--    1 504      450           932 Jan 04  2015 README.nluug
- -rw-r--r--    1 504      450          2023 May 03  2005 WhereToFindWhat.txt
- drwxr-sr-x    2 0        450          4096 Jan 26  2008 av
- drwxrwsr-x    2 0        450          4096 Aug 12  2004 comp

ファイルの取得

上記のファイルのリストを取得した後、 getfile メソッドを使用して特定のファイルを取得できます。 このメソッドは、ファイルのコピーをリモートシステムからFTP接続が開始されたローカルシステムに移動します。

import ftplib
import sys

def getFile(ftp, filename):
    try:
        ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
    except:
        print "Error"


ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

ftp.cwd('/pub/')          change directory to/pub/
getFile(ftp,'README.nluug')

ftp.quit()

上記のプログラムを実行すると、接続が開始されたローカルシステムにファイルREADME.nlugが存在することがわかります。