"ftplib" — FTPプロトコルクライアント
************************************

**ソースコード:** Lib/ftplib.py

======================================================================

This module defines the class "FTP" and a few related items. The "FTP"
class implements the client side of the FTP protocol.  You can use
this to write Python programs that perform a variety of automated FTP
jobs, such as mirroring other FTP servers.  It is also used by the
module "urllib" to handle URLs that use FTP.  For more information on
FTP (File Transfer Protocol), see Internet **RFC 959**.

"ftplib" モジュールを使ったサンプルを以下に示します:

   >>> from ftplib import FTP
   >>> ftp = FTP('ftp.debian.org')     # connect to host, default port
   >>> ftp.login()                     # user anonymous, passwd anonymous@
   '230 Login successful.'
   >>> ftp.cwd('debian')               # change into "debian" directory
   >>> 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.'
   >>> ftp.retrbinary('RETR README', open('README', 'wb').write)
   '226 Transfer complete.'
   >>> ftp.quit()

このモジュールは以下の項目を定義しています:

class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])

   Return a new instance of the "FTP" class.  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).

   バージョン 2.6 で変更: *timeout* was added.

class ftplib.FTP_TLS([host[, user[, passwd[, acct[, keyfile[, certfile[, context[, timeout]]]]]]]])

   **RFC 4217** に記述されている TLS サポートを FTP に加えた "FTP" の
   サブクラスです。認証の前に FTP コントロール接続を暗黙にセキュアにし
   、通常通りに port 21 に接続します。データ接続をセキュアにするには、
   ユーザが "prot_p()" メソッドを呼び出してそれを明示的に要求しなけれ
   ばなりません。 *context* は SSL 設定オプション、証明書、秘密鍵を一
   つの(潜在的に長生きの)構造にまとめた "ssl.SSLContext" オブジェクト
   です。ベストプラクティスについての セキュリティで考慮すべき点 をお
   読みください。

   *keyfile* と *certfile* は *context* のレガシー版です – これらは、
   SSL 接続のための、 PEM フォーマットの秘密鍵と証明書チェーンファイル
   名(前者が *keyfile* 、後者が *certfile* )を含むことができます。

   バージョン 2.7 で追加.

   バージョン 2.7.10 で変更: The *context* parameter was added.

   Here’s a sample session using the "FTP_TLS" class:

   >>> from ftplib import FTP_TLS
   >>> ftps = FTP_TLS('ftp.python.org')
   >>> ftps.login()           # login anonymously before securing control channel
   >>> ftps.prot_p()          # switch to secure data connection
   >>> ftps.retrlines('LIST') # list directory content securely
   total 9
   drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
   drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
   drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
   drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
   d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
   drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
   drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
   drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
   -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
   '226 Transfer complete.'
   >>> ftps.quit()
   >>>

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

   The set of all exceptions (as a tuple) that methods of "FTP"
   instances may raise as a result of problems with the FTP connection
   (as opposed to programming errors made by the caller).  This set
   includes the four exceptions listed above as well as "socket.error"
   and "IOError".

参考:

  "netrc" モジュール
     ".netrc" ファイルフォーマットのパーザ。 ".netrc" ファイルは、 FTP
     クライアントがユーザにプロンプトを出す前に、ユーザ認証情報をロー
     ドするのによく使われます。

  The file "Tools/scripts/ftpmirror.py" in the Python source
  distribution is a script that can mirror FTP sites, or portions
  thereof, using the "ftplib" module. It can be used as an extended
  example that applies this module.


FTP オブジェクト
================

いくつかのコマンドは２つのタイプについて実行します：１つはテキストファ
イルで、もう１つはバイナリファイルを扱います。これらのメソッドのテキス
トバージョンでは "lines" 、バイナリバージョンでは "binary" の語がメソ
ッド名の終わりについています。

"FTP" インスタンスには以下のメソッドがあります:

FTP.set_debuglevel(level)

   インスタンスのデバッグレベルを設定します。この設定によってデバッグ
   時に出力される量を調節します。デフォルトは "0" で、何も出力されませ
   ん。 "1" なら、一般的に１つのコマンドあたり１行の適当な量のデバッグ
   出力を行います。 "2" 以上なら、コントロール接続で受信した各行を出力
   して、最大のデバッグ出力をします。

FTP.connect(host[, port[, timeout]])

   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.

   バージョン 2.6 で変更: *timeout* was added.

FTP.getwelcome()

   サーバに最初に接続した際に送信される応答中のウェルカムメッセージを
   返します。(このメッセージには時に、ユーザにとって重要な免責事項や
   ヘルプ情報が入っています。)

FTP.login([user[, passwd[, acct]]])

   与えられた *user* でログインします。 *passwd* と *acct* のパラメー
   タは省略可能で、デフォルトでは空文字列です。もし *user* が指定され
   ないなら、デフォルトで "'anonymous'" になります。もし *user* が
   "'anonymous'" なら、デフォルトの *passwd* は "'anonymous@'" になり
   ます。この関数は各インスタンスについて一度だけ、接続が確立した後に
   呼び出さなければなりません。インスタンスが作られた時にホスト名とユ
   ーザ名が与えられていたら、このメソッドを実行すべきではありません。
   ほとんどのFTPコマンドはクライアントがログインした後に実行可能になり
   ます。 *acct* 引数は 「accounting information」 を提供します。ほと
   んどのシステムはこれを実装していません。

FTP.abort()

   実行中のファイル転送を中止します。これはいつも機能するわけではあり
   ませんが、やってみる価値はあります。

FTP.sendcmd(command)

   シンプルなコマンド文字列をサーバに送信して、受信した文字列を返しま
   す。

FTP.voidcmd(command)

   シンプルなコマンド文字列をサーバに送信して、その応答を扱います。応
   答コードが成功に関係するもの(200–299の範囲にあるコード)なら何も返し
   ません。それ以外は "error_reply" を発生します。

FTP.retrbinary(command, callback[, maxblocksize[, rest]])

   Retrieve a file in binary transfer mode.  *command* should be an
   appropriate "RETR" command: "'RETR filename'". The *callback*
   function is called for each block of data received, with a single
   string argument giving the data block. The optional *maxblocksize*
   argument specifies the maximum chunk size to read on the low-level
   socket object created to do the actual transfer (which will also be
   the largest size of the data blocks passed to *callback*).  A
   reasonable default is chosen. *rest* means the same thing as in the
   "transfercmd()" method.

FTP.retrlines(command[, callback])

   Retrieve a file or directory listing in ASCII transfer mode.
   *command* should be an appropriate "RETR" command (see
   "retrbinary()") or a command such as "LIST", "NLST" or "MLSD"
   (usually just the string "'LIST'").  "LIST" retrieves a list of
   files and information about those files. "NLST" retrieves a list of
   file names.  On some servers, "MLSD" retrieves a machine readable
   list of files and information about those files.  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)

   Enable 「passive」 mode if *val* is true, otherwise disable passive
   mode.  (In Python 2.0 and before, passive mode was off by default;
   in Python 2.1 and later, it is on by default.)

FTP.storbinary(command, fp[, blocksize, callback, rest])

   Store a file in binary transfer mode.  *command* should be an
   appropriate "STOR" command: ""STOR filename"". *fp* is an open file
   object which is read until EOF using its "read()" method in blocks
   of size *blocksize* to provide the data to be stored.  The
   *blocksize* argument defaults to 8192. *callback* is an optional
   single parameter callable that is called on each block of data
   after it is sent. *rest* means the same thing as in the
   "transfercmd()" method.

   バージョン 2.1 で変更: default for *blocksize* added.

   バージョン 2.6 で変更: *callback* parameter added.

   バージョン 2.7 で変更: *rest* パラメタが追加されました。

FTP.storlines(command, fp[, callback])

   Store a file in ASCII transfer mode.  *command* should be an
   appropriate "STOR" command (see "storbinary()").  Lines are read
   until EOF from the open file object *fp* 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.

   バージョン 2.6 で変更: *callback* parameter added.

FTP.transfercmd(cmd[, rest])

   データ接続中に転送を初期化します。もし転送中なら、"EPRT" あるいは
   "PORT" コマンドと、*cmd* で指定したコマンドを送信し、接続を続けます
   。サーバがパッシブなら、"EPSV" あるいは "PASV" コマンドを送信して接
   続し、転送コマンドを開始します。どちらの場合も、接続のためのソケッ
   トを返します。

   省略可能な *rest* が与えられたら、 "REST" コマンドがサーバに送信さ
   れ、 *rest* を引数として与えます。 *rest* は普通、要求したファイル
   のバイトオフセット値で、最初のバイトをとばして指定したオフセット値
   からファイルのバイト転送を再開するよう伝えます。しかし、RFC 959では
   *rest* が印字可能なASCIIコード33から126の範囲の文字列からなることを
   要求していることに注意して下さい。したがって、 "transfercmd()" メソ
   ッドは *rest* を文字列に変換しますが、文字列の内容についてチェック
   しません。もし "REST" コマンドをサーバが認識しないなら、例外
   "error_re ply" が発生します。この例外が発生したら、引数 *rest* なし
   に "transfercmd()" を実行します。

FTP.ntransfercmd(cmd[, rest])

   "transfercmd()" と同様ですが、データと予想されるサイズとのタプルを
   返します。もしサイズが計算できないなら、サイズの代わりに "None" が
   返されます。 *cmd* と *rest* は "transfercmd()" のものと同じです。

FTP.nlst(argument[, ...])

   "NLST" コマンドで返されるファイル名のリストを返します。省略可能な
   *argument* は、リストアップするディレクトリです（デフォルトではサー
   バのカレントディレクトリです）。 "NLST" コマンドに非標準である複数
   の引数を渡すことができます。

FTP.dir(argument[, ...])

   "LIST" コマンドで返されるディレクトリ内のリストを作り、標準出力へ出
   力します。省略可能な *argument* は、リストアップするディレクトリで
   す（デフォルトではサーバのカレントディレクトリです）。 "LIST" コマ
   ンドに非標準である複数の引数を渡すことができます。もし最後の引数が
   関数なら、 "retrlines()" のように *callback* として使われます; デフ
   ォルトでは "sys.stdout" に印字します。このメソッドは "None" を返し
   ます。

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.quit()

   サーバに "QUIT" コマンドを送信し、接続を閉じます。これは接続を閉じ
   るのに」礼儀正しい」方法ですが、 "QUIT" コマンドに反応してサーバの
   例外が発生するかもしれません。この例外は、 "close()" メソッドによっ
   て "FTP" インスタンスに対するその後のコマンド使用が不可になっている
   ことを示しています（下記参照）。

FTP.close()

   接続を一方的に閉じます。既に閉じた接続に対して実行すべきではありま
   せん（例えば "quit()" を呼び出して成功した後など）。この実行の後、
   "FTP" インスタンスはもう使用すべきではありません（ "close()" あるい
   は "quit()" を呼び出した後で、 "login()" メソッドをもう一度実行して
   再び接続を開くことはできません）。


FTP_TLS オブジェクト
====================

"FTP_TLS" クラスは "FTP" を継承し、さらにオブジェクトを定義します:

FTP_TLS.ssl_version

   使用する SSL のバージョン (デフォルトは "ssl.PROTOCOL_SSLv23") です
   。

FTP_TLS.auth()

   Set up secure control connection by using TLS or SSL, depending on
   what specified in "ssl_version()" attribute.

FTP_TLS.prot_p()

   セキュアデータ接続をセットアップします。

FTP_TLS.prot_c()

   平文データ接続をセットアップします。
