"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**.

Availability: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは
、WebAssembly プラットフォーム を見てください。

"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.'


リファレンス
============


FTP オブジェクト
----------------

class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8')

   Return a new instance of the "FTP" class.

   パラメータ:
      * **host** (*str*) -- The hostname to connect to. If given,
        "connect(host)" is implicitly called by the constructor.

      * **user** (*str*) -- The username to log in with (default:
        "'anonymous'"). If given, "login(host, passwd, acct)" is
        implicitly called by the constructor.

      * **passwd** (*str*) -- The password to use when logging in. If
        not given, and if *passwd* is the empty string or ""-"", a
        password will be automatically generated.

      * **acct** (*str*) -- Account information to be used for the
        "ACCT" FTP command. Few systems implement this. See RFC-959
        for more details.

      * **timeout** (*float** | **None*) -- A timeout in seconds for
        blocking operations like "connect()" (default: the global
        default timeout setting).

      * **source_address** (*tuple** | **None*) -- A 2-tuple "(host,
        port)" for the socket to bind to as its source address before
        connecting.

      * **encoding** (*str*) -- The encoding for directories and
        filenames (default: "'utf-8'").

   "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 "ValueError" to 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**.

   Several "FTP" methods are available in two flavors: one for
   handling text files and another for binary files. The methods are
   named for the command which is used followed by "lines" for the
   text version or "binary" for the binary version.

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

   set_debuglevel(level)

      Set the instance's debugging level as an "int". This controls
      the amount of debugging output printed. The debug levels are:

      * "0" (default): No debug output.

      * "1": Produce a moderate amount of debug output, generally a
        single line per request.

      * "2" or higher: Produce the maximum amount of debugging output,
        logging each line sent and received on the control connection.

   connect(host='', port=0, timeout=None, source_address=None)

      Connect to the given host and port. This function should be
      called only once for each instance; it should not be called if a
      *host* argument was given when the "FTP" instance was created.
      All other "FTP" methods can only be called after a connection
      has successfully been made.

      パラメータ:
         * **host** (*str*) -- The host to connect to.

         * **port** (*int*) -- The TCP port to connect to (default:
           "21", as specified by the FTP protocol specification). It
           is rarely needed to specify a different port number.

         * **timeout** (*float** | **None*) -- A timeout in seconds
           for the connection attempt (default: the global default
           timeout setting).

         * **source_address** (*tuple** | **None*) -- 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* 引数が追加されました。

   getwelcome()

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

   login(user='anonymous', passwd='', acct='')

      Log on to the connected FTP server. This function should be
      called only once for each instance, after a connection has been
      established; it should not be called if the *host* and *user*
      arguments were given when the "FTP" instance was created. Most
      FTP commands are only allowed after the client has logged in.

      パラメータ:
         * **user** (*str*) -- The username to log in with (default:
           "'anonymous'").

         * **passwd** (*str*) -- The password to use when logging in.
           If not given, and if *passwd* is the empty string or ""-"",
           a password will be automatically generated.

         * **acct** (*str*) -- Account information to be used for the
           "ACCT" FTP command. Few systems implement this. See RFC-959
           for more details.

   abort()

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

   sendcmd(cmd)

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

      引数 "self", "cmd" を指定して 監査イベント "ftplib.sendcmd" を送
      出します。

   voidcmd(cmd)

      Send a simple command string to the server and handle the
      response.  Return the response string if the response code
      corresponds to success (codes in the range 200--299).  Raise
      "error_reply" otherwise.

      引数 "self", "cmd" を指定して 監査イベント "ftplib.sendcmd" を送
      出します。

   retrbinary(cmd, callback, blocksize=8192, rest=None)

      Retrieve a file in binary transfer mode.

      パラメータ:
         * **cmd** (*str*) -- An appropriate "RETR" command: ""RETR
           *filename*"".

         * **callback** (*callable*) -- A single parameter callable
           that is called for each block of data received, with its
           single argument being the data as "bytes".

         * **blocksize** (*int*) -- The maximum chunk size to read on
           the low-level "socket" object created to do the actual
           transfer. This also corresponds to the largest size of data
           that will be passed to *callback*. Defaults to "8192".

         * **rest** (*int*) -- A "REST" command to be sent to the
           server. See the documentation for the *rest* parameter of
           the "transfercmd()" method.

   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 "RETR" command (see "retrbinary()") or a command
      such as "LIST" or "NLST" (usually just the string "'LIST'").
      "LIST" retrieves a list of files and information about those
      files. "NLST" retrieves 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".

   set_pasv(val)

      *val* が真の場合 "パッシブ" モードを有効化し、偽の場合は無効化し
      ます。 デフォルトではパッシブモードです。

   storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)

      Store a file in binary transfer mode.

      パラメータ:
         * **cmd** (*str*) -- An appropriate "STOR" command: ""STOR
           *filename*"".

         * **fp** (*file object*) -- A file object (opened in binary
           mode) which is read until EOF, using its "read()" method in
           blocks of size *blocksize* to provide the data to be
           stored.

         * **blocksize** (*int*) -- The read block size. Defaults to
           "8192".

         * **callback** (*callable*) -- A single parameter callable
           that is called for each block of data sent, with its single
           argument being the data as "bytes".

         * **rest** (*int*) -- A "REST" command to be sent to the
           server. See the documentation for the *rest* parameter of
           the "transfercmd()" method.

      バージョン 3.2 で変更: The *rest* parameter was added.

   storlines(cmd, fp, callback=None)

      Store a file in line mode.  *cmd* should be an appropriate
      "STOR" command (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.

   transfercmd(cmd, rest=None)

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

      If optional *rest* is given, a "REST" command 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 "REST"
      command, an "error_reply" exception will be raised.  If this
      happens, simply call "transfercmd()" without a *rest* argument.

   ntransfercmd(cmd, rest=None)

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

   mlsd(path='', facts=[])

      List a directory in a standardized format by using "MLSD"
      command (**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.

      Added in version 3.3.

   nlst(argument[, ...])

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

      注釈:

        If your server supports the command, "mlsd()" offers a better
        API.

   dir(argument[, ...])

      Produce a directory listing as returned by the "LIST" command,
      printing it to standard output.  The optional *argument* is a
      directory to list (default is the current server directory).
      Multiple arguments can be used to pass non-standard options to
      the "LIST" command.  If the last argument is a function, it is
      used as a *callback* function as for "retrlines()"; the default
      prints to "sys.stdout".  This method returns "None".

      注釈:

        If your server supports the command, "mlsd()" offers a better
        API.

   rename(fromname, toname)

      サーバ上のファイルのファイル名 *fromname* を *toname* へ変更しま
      す。

   delete(filename)

      サーバからファイル *filename* を削除します。成功したら応答のテキ
      ストを返し、そうでないならパーミッションエラーでは "error_perm"
      を、他のエラーでは "error_reply" を返します。

   cwd(pathname)

      サーバのカレントディレクトリを設定します。

   mkd(pathname)

      サーバ上に新たにディレクトリを作ります。

   pwd()

      サーバ上のカレントディレクトリのパスを返します。

   rmd(dirname)

      サーバ上のディレクトリ *dirname* を削除します。

   size(filename)

      サーバ上のファイル *filename* のサイズを尋ねます。成功したらファ
      イルサイズが整数で返され、そうでないなら "None" が返されます。
      "SIZE" コマンドは標準化されていませんが、多くの普通のサーバで実
      装されていることに注意して下さい。

   quit()

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

   close()

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


FTP_TLS オブジェクト
--------------------

class ftplib.FTP_TLS(host='', user='', passwd='', acct='', *, context=None, timeout=None, source_address=None, encoding='utf-8')

   An "FTP" subclass which adds TLS support to FTP as described in
   **RFC 4217**. Connect to port 21 implicitly securing the FTP
   control connection before authenticating.

   注釈:

     The user must explicitly secure the data connection by calling
     the "prot_p()" method.

   パラメータ:
      * **host** (*str*) -- The hostname to connect to. If given,
        "connect(host)" is implicitly called by the constructor.

      * **user** (*str*) -- The username to log in with (default:
        "'anonymous'"). If given, "login(host, passwd, acct)" is
        implicitly called by the constructor.

      * **passwd** (*str*) -- The password to use when logging in. If
        not given, and if *passwd* is the empty string or ""-"", a
        password will be automatically generated.

      * **acct** (*str*) -- Account information to be used for the
        "ACCT" FTP command. Few systems implement this. See RFC-959
        for more details.

      * **context** ("ssl.SSLContext") -- An SSL context object which
        allows bundling SSL configuration options, certificates and
        private keys into a single, potentially long-lived, structure.
        Please read セキュリティで考慮すべき点 for best practices.

      * **timeout** (*float** | **None*) -- A timeout in seconds for
        blocking operations like "connect()" (default: the global
        default timeout setting).

      * **source_address** (*tuple** | **None*) -- A 2-tuple "(host,
        port)" for the socket to bind to as its source address before
        connecting.

      * **encoding** (*str*) -- The encoding for directories and
        filenames (default: "'utf-8'").

   Added in version 3.2.

   バージョン 3.3 で変更: Added the *source_address* parameter.

   バージョン 3.4 で変更: このクラスは "ssl.SSLContext.check_hostname"
   と *Server Name Indication* でホスト名のチェックをサポートしました
   。("ssl.HAS_SNI" を参照してください)。

   バージョン 3.9 で変更: If the *timeout* parameter is set to be
   zero, it will raise a "ValueError" to 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**.

   バージョン 3.12 で変更: 非推奨の *keyfile* と *certfile* 引数を削除
   しました。

   "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']

   "FTP_TLS" class inherits from "FTP", defining these additional
   methods and attributes:

   ssl_version

      The SSL version to use (defaults to "ssl.PROTOCOL_SSLv23").

   auth()

      "ssl_version" 属性で指定されたものに従って、 TLS または SSL を使
      い、セキュアコントロール接続をセットアップします。

      バージョン 3.4 で変更: The method now supports hostname check
      with "ssl.SSLContext.check_hostname" and *Server Name
      Indication* (see "ssl.HAS_SNI").

   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.

      Added in version 3.3.

   prot_p()

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

   prot_c()

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


モジュール変数
--------------

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接続で (プログラミングのエラ
   ーと考えられるメソッドの実行によって) 発生する全ての例外 (タプル形
   式)。この例外には以上の４つのエラーはもちろん、 "OSError" と
   "EOFError" も含まれます。

参考:

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