python实现简单ftp客户端的方法

本文实例讲述了python实现简单ftp客户端的方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import ftplib
import os
import socket
host = ‘ftp.mozilla.org’
dirn = ‘pub/mozilla.org/webtools’
file = ‘bugzilla-3.6.9-to-3.6.10-nodocs.diff.gz’
def writedata(data):
f = open(file,’wb’)
try:
f.write(data)
finally:
f.close()
def main():
try:
f = ftplib.ftp(host)
except (socket.error, socket.gaierror):
print ‘error:cannot reach ” %s”‘ % host
return
print ‘***connected to host “%s”‘ % host
try:
f.login()
except ftplib.error_perm:
print ‘error: cannot login anonymously’
f.quit()
return
print ‘*** logged in as “anonymously”‘
try:
f.cwd(dirn)
except ftplib.error_perm:
print ‘errorl cannot cd to “%s”‘ % dirn
f.quit()
return
print ‘*** changed to “%s” folder’ % dirn
try:
#传一个回调函数给retrbinary() 它在每接收一个二进制数据时都会被调用
f.retrbinary(‘retr %s’ %file, writedata)
except ftplib.error_perm:
print ‘error: cannot read file “%s”‘ %file
os.unlink(file)
else:
print ‘*** downloaded “%s” to cwd’ % file
f.quit()
return
if __name__ == ‘__main__’:
main()

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论