import ftplib import os import socket import sys HOST=‘192.168.216.193‘ DIRN=‘c:\\ftp\FTP.123‘ FILE=‘FTP.123‘ USER_NAME=‘123‘ PWD=‘123‘ def Downloadfile(file_name): try: f=ftplib.FTP(HOST) except(sockt.error, socket.gaierror) as e: print (‘error: cannot reach %s‘ % HOST) return print (‘**** connected to host %s‘ % HOST) try: f.login(USER_NAME,PWD) except ftplib.error_perm: print(‘ERROR:cannot login USER_NAME=%s,PWD=%s‘%(USER_NAME,PWD)) f.quit() return print(‘*** logined in as %s ‘ % USER_name) try: f.cwd(DIRN) except ftplib.error_perm: print (‘error :cannot cd to %s‘% RIRN) f.quit() return try: file=open(file_name, ‘wb‘) f.retrbinary(‘RETR %s‘ %file_name,file.write) file.close() except ftplib.error_perm: print(‘error !!‘) os.unlink(filename) file.close() else: print (‘**** downloaded %s to %s‘%(file_name ,os.getcwd())) f.quit return Downloadfile(123.txt)
> import ftplib >>> f=ftplib.FTP(‘192.168.216.193‘) >>> f=ftplib.FTP(‘192.168.216.193‘) >>> f.login(‘123‘,‘123‘) ‘230 User successfully logged in.‘ >>> f.cwd(‘FTP.123‘) ‘250 "/ftp.123" is current directory.‘ >>> f.retrbinary(‘RETR 123.txt‘,open(‘c:\\123.txt‘,‘wb‘).write) ‘226 Transfer complete‘
网上其他人写的脚本
#!/usr/bin/env python # -*- coding: utf-8 -*- from ftplib import FTP def ftp_up(filename = "20120904.rar"): ftp=FTP() ftp.set_debuglevel(2) #打开调试级别2,显示详细信息;0为关闭调试信息 ftp.connect(‘192.168.0.1‘,‘21‘) #连接 ftp.login(‘admin‘,‘admin‘) #登录,如果匿名登录则用空串代替即可 #print ftp.getwelcome() #显示ftp服务器欢迎信息 #ftp.cwd(‘xxx/xxx/‘) #选择操作目录 bufsize = 1024 #设置缓冲块大小 file_handler = open(filename,‘rb‘) #以读模式在本地打开文件 ftp.storbinary(‘STOR %s‘ % os.path.basename(filename),file_handler,bufsize) #上传文件 ftp.set_debuglevel(0) file_handler.close() ftp.quit() print "ftp up OK" def ftp_down(filename = "20120904.rar"): ftp=FTP() ftp.set_debuglevel(2) ftp.connect(‘192.168.0.1‘,‘21‘) ftp.login(‘admin‘,‘admin‘) #print ftp.getwelcome() #显示ftp服务器欢迎信息 #ftp.cwd(‘xxx/xxx/‘) #选择操作目录 bufsize = 1024 filename = "20120904.rar" file_handler = open(filename,‘wb‘).write #以写模式在本地打开文件 ftp.retrbinary(‘RETR %s‘ % os.path.basename(filename),file_handler,bufsize) #接收服务器上文件并写入本地文件 ftp.set_debuglevel(0) file_handler.close() ftp.quit() print "ftp down OK
时间: 2024-10-14 05:31:56