linux下进行ftp上传下载的python代码-python
最近需要频繁的在windows和linux下进行文件传输,但是linux下又没有像飞鸽传书那样方便的软件,参阅网上的一些例子,自己写了个上传下载的python代码:
上传:1、设置好服务器的ip,登录服务器的用户名、密码,
2、设置好准备上传到服务器的位置:ftpdir
3、设置好待上传的文件的目录:filedir_client
4、运行:python upload.py ,按照程序提示输入要上传的文件名,回车等待。
5、完成。
#!/usr/bin/env python
#upload file
from ftplib import FTP
#ip = raw_input("enter ip or tick enter for default: ")
#port = raw_input("enter port or tick enter for default: ")
#username = raw_input("enter username or tick enter for default: ")
#password = raw_input("enter password or tick enter for default: ")
#ftpdir = raw_input("enter uploaddir or tick enter for default: ")
ip='192.168.1.101'
port='21'
username='yangchuang'
password='.'
ftpdir='filesystem/dsplinktest/'
filedir_client='dsp/export/BIN/DspBios/DAVINCIHD/DM6467GEM_0/DEBUG/'
bufsize=1024
try:
ftp=FTP()
ftp.set_debuglevel(2)
ftp.connect(ip,port)
ftp.login(username,password)
print ftp.getwelcome()
except:
print "can't login to the server"
exit
while 1:
filename = raw_input("enter upload filename or tick enter for default,q for exit: ")
if filename=='':
filename='avinfo.out'
if filename=='q':
break
try:
file_handler=open(filedir_client+filename,'rb')
except:
print 'no such files,please check the filename'
continue
cmd='STOR '+ftpdir+filename
ftp.storbinary(cmd,file_handler,bufsize)
ftp.set_debuglevel(0)
ftp.quit()
下载:设置步骤同上传。
#!\usr\bin\env python
#upload file
import os
from ftplib import FTP
#ip = raw_input("enter ip or tick enter for default: ")
#port = raw_input("enter the port or tick enter for default: ")
#username = raw_input("enter username or tick enter for default: ")
#password = raw_input("enter password or tick enter for default: ")
#ftpdir = raw_input("enter the download dir or tick enter for default: ")
ip='192.168.1.101'
port='21'
username='yangchuang'
password='.'
ftpdir='filesystem//dsplinktest//' # where 's the file on the server
filedir_client='..//' #where do you want to save the file
bufsize=1024
try:
ftp=FTP()
ftp.set_debuglevel(2)
ftp.connect(ip,port)
ftp.login(username,password)
print ftp.getwelcome()
except:
print "can't login to the server"
exit
while 1:
filename = raw_input("enter download filename or tick enter for default, q for exit: ")
if filename=='':
filename='o.264'
if filename=='q':
break
try:
file_handler=open(filedir_client+filename,'wb').write
except:
print "cann't create such files"
continue
cmd='RETR '+ftpdir+filename
try:
ftp.retrbinary(cmd,file_handler,bufsize)
except:
print '----------ERROR-----------:no such files on server'
continue
ftp.set_debuglevel(0)
ftp.quit()
也可以把*.py文件再linux和windows下编译成可直接执行的文件:*.pyc *.exe文件,以后运行起来更方便了。
浙公网安备 33010602011771号