python使用ftplib作ftp操做

转自:http://blog.chinaunix.net/uid-200142-id-3910549.htmlphp

 

ftplib是 Python的内置的一个标准模块,它提供了极强大的对FTP服务器的操做,经过它咱们能够链接并操做FTP服务端,开始练习:html

1、导入模块并进行链接服务器

>>> from ftplib import FTP >>> ftp = FTP(‘ftp.yabogo.com’) >>> ftp.login(‘yourloginname’,'password’) 

 

FTP登陆成功ui

链接到FTP可还有以下形式:url

一、实例化并直接链接,ftp=FTP(host=”, user=”, passwd=”, acct=”, timeout=”)spa

二、先实例ftp=FTP(), 再使用 connect(host=”, port=0, timeout=-999)链接,最后login(user=”, passwd=”).net

2、查看目录文件或更改目录unix

>>> ftp.retrlines(‘LIST’)

一、retrlines(cmd)是以文本形式查看当前目录文件,可用cmd:RETR, LIST, NLST, MLSDrest

二、若是要指定查看某个目录的文件列表,能够用dir(dirname) ,dirname是可选参数,默认是当前目录;code

三、cwd(dirname), 更改目录! Change to a directory.

3、查看文件的大小

>>> ftp.size(‘yabogo_logo.gif’) 2452

 

4、ftp上传一个文件

>>> fp=open(‘F:/test.php’,'rb’)
>>> ftp.storbinary(‘STOR test.php’,fp)

 

二进上传文件成功

storbinary( cmd, fp, blocksize=8192, callback=None, rest=None)
Args:
          cmd: A STOR command.
          fp: A file-like object with a read(num_bytes) method.
          blocksize: The maximum data size to read from fp and send over
                     the connection at once.  [default: 8192]
          callback: An optional single parameter callable that is called on
                    on each block of data after it is sent.  [default: None]
          rest: Passed to transfercmd().  [default: None]

        Returns:
          The response code.

 

5、退出关闭,并退出FTP

>>> ftp.quit() ’221 Goodbye, logging out.’

 

ftplib有不少可用的方法,导入模块后可经过help()查看帮助信息。

相关文章
相关标签/搜索