ftplib --- FTPプロトコルクライアント¶
ソースコード: Lib/ftplib.py
このモジュールでは FTP クラスと、それに関連するいくつかの項目を定義しています。 FTP クラスは、FTPプロトコルのクライアント側の機能を備えています。このクラスを使うとFTPのいろいろな機能の自動化、例えば他のFTPサーバのミラーリングといったことを実行するPythonプログラムを書くことができます。また、 urllib.request モジュールもFTPを使うURLを操作するのにこのクラスを使っています。 FTP (File Transfer Protocol)についての詳しい情報はInternet RFC 959 を参照して下さい。
The default encoding is UTF-8, following RFC 2640.
ftplib モジュールを使ったサンプルを以下に示します:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org')  # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd anonymous@
'230 Login successful.'
>>> ftp.cwd('debian')               # change into "debian" directory
'250 Directory successfully changed.'
>>> ftp.retrlines('LIST')           # list directory contents
-rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
...
drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
'226 Directory send OK.'
>>> with open('README', 'wb') as fp:
>>>     ftp.retrbinary('RETR README', fp.write)
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
このモジュールは以下の項目を定義しています:
- 
class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8')¶
- Return a new instance of the - FTPclass. When host is given, the method call- connect(host)is made. When user is given, additionally the method call- login(user, passwd, acct)is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used). source_address is a 2-tuple- (host, port)for the socket to bind to as its source address before connecting. The encoding parameter specifies the encoding for directories and filenames.- FTPクラスは- with文をサポートしています。例えば:- >>> from ftplib import FTP >>> with FTP("ftp1.at.proftpd.org") as ftp: ... ftp.login() ... ftp.dir() ... '230 Anonymous login ok, restrictions apply.' dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora >>> - バージョン 3.2 で変更: - with構文のサポートが追加されました。- バージョン 3.3 で変更: source_address 引数が追加されました。 - バージョン 3.9 で変更: If the timeout parameter is set to be zero, it will raise a - ValueErrorto prevent the creation of a non-blocking socket. The encoding parameter was added, and the default was changed from Latin-1 to UTF-8 to follow RFC 2640.
- 
class ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8')¶
- RFC 4217 に記述されている TLS サポートを FTP に加えた - FTPのサブクラスです。認証の前に FTP コントロール接続を暗黙にセキュアにし、通常通りに port 21 に接続します。データ接続をセキュアにするには、ユーザが- prot_p()メソッドを呼び出してそれを明示的に要求しなければなりません。 context は SSL 設定オプション、証明書、秘密鍵を一つの(潜在的に長生きの)構造にまとめた- ssl.SSLContextオブジェクトです。ベストプラクティスについての セキュリティで考慮すべき点 をお読みください。- keyfile と certfile は context のレガシー版です -- これらは、SSL 接続のための、 PEM フォーマットの秘密鍵と証明書チェーンファイル名(前者が keyfile 、後者が certfile )を含むことができます。 - バージョン 3.2 で追加. - バージョン 3.3 で変更: source_address 引数が追加されました。 - バージョン 3.4 で変更: このクラスは - ssl.SSLContext.check_hostnameと Server Name Indication でホスト名のチェックをサポートしました。(- ssl.HAS_SNIを参照してください)。- バージョン 3.6 で非推奨: keyfile および certfile は非推奨となったので、 context を使ってください。 代わりに - ssl.SSLContext.load_cert_chain()を使うか、または- ssl.create_default_context()にシステムが信頼する CA 証明書を選んでもらうかしてください。- バージョン 3.9 で変更: If the timeout parameter is set to be zero, it will raise a - ValueErrorto prevent the creation of a non-blocking socket. The encoding parameter was added, and the default was changed from Latin-1 to UTF-8 to follow RFC 2640.- FTP_TLSクラスを使ったサンプルセッションはこちらです:- >>> ftps = FTP_TLS('ftp.pureftpd.org') >>> ftps.login() '230 Anonymous user logged in' >>> ftps.prot_p() '200 Data protection level set to "private"' >>> ftps.nlst() ['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp'] 
- 
exception ftplib.error_reply¶
- サーバから想定外の応答があったときに送出される例外。 
- 
exception ftplib.error_temp¶
- 一時的エラーを表すエラーコード(400--499の範囲の応答コード)を受け取った時に発生する例外。 
- 
exception ftplib.error_perm¶
- 永久エラーを表すエラーコード(500--599の範囲の応答コード)を受け取った時に発生する例外。 
- 
exception ftplib.error_proto¶
- File Transfer Protocol の応答仕様に適合しない、すなわち1--5の数字で始まらない応答コードをサーバから受け取った時に発生する例外。 
- 
ftplib.all_errors¶
- FTPインスタンスのメソッド実行時、FTP接続で (プログラミングのエラーと考えられるメソッドの実行によって) 発生する全ての例外 (タプル形式)。この例外には以上の4つのエラーはもちろん、- OSErrorと- EOFErrorも含まれます。
参考
- netrcモジュール
- .netrcファイルフォーマットのパーザ。- .netrcファイルは、 FTPクライアントがユーザにプロンプトを出す前に、ユーザ認証情報をロードするのによく使われます。
FTP オブジェクト¶
いくつかのコマンドは2つのタイプについて実行します:1つはテキストファイルで、もう1つはバイナリファイルを扱います。これらのメソッドのテキストバージョンでは lines 、バイナリバージョンでは binary の語がメソッド名の終わりについています。
FTP インスタンスには以下のメソッドがあります:
- 
FTP.set_debuglevel(level)¶
- インスタンスのデバッグレベルを設定します。この設定によってデバッグ時に出力される量を調節します。デフォルトは - 0で、何も出力されません。- 1なら、一般的に1つのコマンドあたり1行の適当な量のデバッグ出力を行います。- 2以上なら、コントロール接続で受信した各行を出力して、最大のデバッグ出力をします。
- 
FTP.connect(host='', port=0, timeout=None, source_address=None)¶
- Connect to the given host and port. The default port number is - 21, as specified by the FTP protocol specification. It is rarely needed to specify a different port number. This function should be called only once for each instance; it should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection attempt. If no timeout is passed, the global default timeout setting will be used. source_address is a 2-tuple- (host, port)for the socket to bind to as its source address before connecting.- 引数 - self,- host,- portを指定して 監査イベント- ftplib.connectを送出します。- バージョン 3.3 で変更: source_address 引数が追加されました。 
- 
FTP.getwelcome()¶
- サーバに最初に接続した際に送信される応答中のウェルカムメッセージを返します。(このメッセージには時に、ユーザにとって重要な免責事項や ヘルプ情報が入っています。) 
- 
FTP.login(user='anonymous', passwd='', acct='')¶
- 与えられた user でログインします。 passwd と acct のパラメータは省略可能で、デフォルトでは空文字列です。もし user が指定されないなら、デフォルトで - 'anonymous'になります。もし user が- 'anonymous'なら、デフォルトの passwd は- 'anonymous@'になります。この関数は各インスタンスについて一度だけ、接続が確立した後に呼び出さなければなりません。インスタンスが作られた時にホスト名とユーザ名が与えられていたら、このメソッドを実行すべきではありません。ほとんどのFTPコマンドはクライアントがログインした後に実行可能になります。 acct 引数は "accounting information" を提供します。ほとんどのシステムはこれを実装していません。
- 
FTP.abort()¶
- 実行中のファイル転送を中止します。これはいつも機能するわけではありませんが、やってみる価値はあります。 
- 
FTP.sendcmd(cmd)¶
- シンプルなコマンド文字列をサーバに送信して、受信した文字列を返します。 - 引数 - self,- cmdを指定して 監査イベント- ftplib.sendcmdを送出します。
- 
FTP.voidcmd(cmd)¶
- シンプルなコマンド文字列をサーバに送信して、その応答を扱います。応答コードが成功に関係するもの(200--299の範囲にあるコード)なら何も返しません。それ以外は - error_replyを発生します。- 引数 - self,- cmdを指定して 監査イベント- ftplib.sendcmdを送出します。
- 
FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)¶
- バイナリ転送モードでファイルを受信します。 cmd は適切な - RETRコマンド:- 'RETR filename'でなければなりません。関数 callback は、受信したデータブロックのそれぞれに対して、データブロックを1つの bytes の引数として呼び出されます。省略可能な引数 blocksize は、実際の転送を行うのに作られた低レベルのソケットオブジェクトから読み込む最大のチャンクサイズを指定します(これは callback に与えられるデータブロックの最大サイズにもなります)。妥当なデフォルト値が設定されます。 rest は、- transfercmd()メソッドと同じものです。
- 
FTP.retrlines(cmd, callback=None)¶
- Retrieve a file or directory listing in the encoding specified by the encoding parameter at initialization. cmd should be an appropriate - RETRcommand (see- retrbinary()) or a command such as- LISTor- NLST(usually just the string- 'LIST').- LISTretrieves a list of files and information about those files.- NLSTretrieves a list of file names. The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped. The default callback prints the line to- sys.stdout.
- 
FTP.set_pasv(val)¶
- val が真の場合 "パッシブ" モードを有効化し、偽の場合は無効化します。 デフォルトではパッシブモードです。 
- 
FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)¶
- バイナリ転送モードでファイルを転送します。 cmd は適切な - STORコマンド:- "STOR filename"でなければなりません。 fp は (バイナリモードで開かれた) ファイルオブジェクト で、- read()メソッドで EOFまで読み込まれ、ブロックサイズ blocksize でデータが転送されます。引数 blocksize のデフォルト値は8192です。 callback はオプションの引数で、引数を1つとる呼び出し可能オブジェクトを渡します。各データブロックが送信された後に、そのブロックを引数にして呼び出されます。 rest は、- transfercmd()メソッドにあるものと同じ意味です。- バージョン 3.2 で変更: rest パラメタが追加されました。 
- 
FTP.storlines(cmd, fp, callback=None)¶
- Store a file in line mode. cmd should be an appropriate - STORcommand (see- storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its- readline()method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent.
- 
FTP.transfercmd(cmd, rest=None)¶
- データ接続中に転送を初期化します。もし転送中なら、 - EPRTあるいは- PORTコマンドと、cmd で指定したコマンドを送信し、接続を続けます。サーバがパッシブなら、- EPSVあるいは- PASVコマンドを送信して接続し、転送コマンドを開始します。どちらの場合も、接続のためのソケットを返します。- If optional rest is given, a - RESTcommand is sent to the server, passing rest as an argument. rest is usually a byte offset into the requested file, telling the server to restart sending the file's bytes at the requested offset, skipping over the initial bytes. Note however that the- transfercmd()method converts rest to a string with the encoding parameter specified at initialization, but no check is performed on the string's contents. If the server does not recognize the- RESTcommand, an- error_replyexception will be raised. If this happens, simply call- transfercmd()without a rest argument.
- 
FTP.ntransfercmd(cmd, rest=None)¶
- transfercmd()と同様ですが、データと予想されるサイズとのタプルを返します。もしサイズが計算できないなら、サイズの代わりに- Noneが返されます。 cmd と rest は- transfercmd()のものと同じです。
- 
FTP.mlsd(path="", facts=[])¶
- List a directory in a standardized format by using - MLSDcommand (RFC 3659). If path is omitted the current directory is assumed. facts is a list of strings representing the type of information desired (e.g.- ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary containing facts about the file name. Content of this dictionary might be limited by the facts argument but server is not guaranteed to return all requested facts.- バージョン 3.3 で追加. 
- 
FTP.nlst(argument[, ...])¶
- NLSTコマンドで返されるファイル名のリストを返します。省略可能な argument は、リストアップするディレクトリです(デフォルトではサーバのカレントディレクトリです)。- NLSTコマンドに非標準である複数の引数を渡すことができます。- 注釈 - If your server supports the command, - mlsd()offers a better API.
- 
FTP.dir(argument[, ...])¶
- LISTコマンドで返されるディレクトリ内のリストを作り、標準出力へ出力します。省略可能な argument は、リストアップするディレクトリです(デフォルトではサーバのカレントディレクトリです)。- LISTコマンドに非標準である複数の引数を渡すことができます。もし最後の引数が関数なら、- retrlines()のように callback として使われます; デフォルトでは- sys.stdoutに印字します。このメソッドは- Noneを返します。- 注釈 - If your server supports the command, - mlsd()offers a better API.
- 
FTP.rename(fromname, toname)¶
- サーバ上のファイルのファイル名 fromname を toname へ変更します。 
- 
FTP.delete(filename)¶
- サーバからファイル filename を削除します。成功したら応答のテキストを返し、そうでないならパーミッションエラーでは - error_permを、他のエラーでは- error_replyを返します。
- 
FTP.cwd(pathname)¶
- サーバのカレントディレクトリを設定します。 
- 
FTP.mkd(pathname)¶
- サーバ上に新たにディレクトリを作ります。 
- 
FTP.pwd()¶
- サーバ上のカレントディレクトリのパスを返します。 
- 
FTP.rmd(dirname)¶
- サーバ上のディレクトリ dirname を削除します。 
- 
FTP.size(filename)¶
- サーバ上のファイル filename のサイズを尋ねます。成功したらファイルサイズが整数で返され、そうでないなら - Noneが返されます。- SIZEコマンドは標準化されていませんが、多くの普通のサーバで実装されていることに注意して下さい。
FTP_TLS オブジェクト¶
FTP_TLS クラスは FTP を継承し、さらにオブジェクトを定義します:
- 
FTP_TLS.ssl_version¶
- 使用する SSL のバージョン (デフォルトは - ssl.PROTOCOL_SSLv23) です。
- 
FTP_TLS.auth()¶
- ssl_version属性で指定されたものに従って、 TLS または SSL を使い、セキュアコントロール接続をセットアップします。- バージョン 3.4 で変更: このメソッドは - ssl.SSLContext.check_hostnameと Server Name Indication でホスト名のチェックをサポートしました。(- ssl.HAS_SNIを参照してください)。
- 
FTP_TLS.ccc()¶
- Revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports. - バージョン 3.3 で追加. 
- 
FTP_TLS.prot_p()¶
- セキュアデータ接続をセットアップします。 
- 
FTP_TLS.prot_c()¶
- 平文データ接続をセットアップします。