首 页 行业热点 新车 试驾评测 养车用车 车型库

python怎么ftp上传文件

发布网友

我来回答

2个回答

懂视网

在Python中可以使用paramiko模块中的sftp登陆远程主机,实现上传和下载功能。接下来通过本文给大家介绍Python使用sftp实现上传和下载功能,需要的朋友参考下

1.功能实现

根据输入参数判断是文件还是目录,进行上传和下载

本地参数local需要与远程参数remote类型一致,文件以文件名结尾,目录以结尾

上传和下载的本地和远程目录需要存在

异常捕获

2.代码实现


#!/usr/bin/python
# coding=utf-8
import paramiko
import os
def sftp_upload(host,port,username,password,local,remote):
 sf = paramiko.Transport((host,port))
 sf.connect(username = username,password = password)
 sftp = paramiko.SFTPClient.from_transport(sf)
 try:
 if os.path.isdir(local):#判断本地参数是目录还是文件
 for f in os.listdir(local):#遍历本地目录
 sftp.put(os.path.join(local+f),os.path.join(remote+f))#上传目录中的文件
 else:
 sftp.put(local,remote)#上传文件
 except Exception,e:
 print('upload exception:',e)
 sf.close()
def sftp_download(host,port,username,password,local,remote):
 sf = paramiko.Transport((host,port))
 sf.connect(username = username,password = password)
 sftp = paramiko.SFTPClient.from_transport(sf)
 try:
 if os.path.isdir(local):#判断本地参数是目录还是文件
 for f in sftp.listdir(remote):#遍历远程目录
  sftp.get(os.path.join(remote+f),os.path.join(local+f))#下载目录中文件
 else:
 sftp.get(remote,local)#下载文件
 except Exception,e:
 print('download exception:',e)
 sf.close()
if name == 'main':
 host = '192.168.1.2'#主机
 port = 22 #端口
 username = 'root' #用户名
 password = '123456' #密码
 local = 'F:sftptest'#本地文件或目录,与远程一致,当前为windows目录格式,window目录中间需要使用双斜线
 remote = '/opt/tianpy5/python/test/'#远程文件或目录,与本地一致,当前为linux目录格式
 sftp_upload(host,port,username,password,local,remote)#上传
 #sftp_download(host,port,username,password,local,remote)#下载

3.总结

以上代码实现了文件和目录的上传和下载,可以单独上传和下载文件,也可以批量上传和下载目录中的文件,基本实现了所要的功能,但是针对目录不存在的情况,以及上传和下载到多台主机上的情况,还有待完善。

热心网友

 通过python下载FTP上的文件夹的实现代码:
  # -*- encoding: utf8 -*-
  import os
  import sys
  import ftplib
  class FTPSync(object):
  def __init__(self):
  self.conn = ftplib.FTP('10.22.33.46', 'user', 'pass')
  self.conn.cwd('/') # 远端FTP目录
  os.chdir('/data/') # 本地下载目录
  def get_dirs_files(self):
  u''' 得到当前目录和文件, 放入dir_res列表 '''
  dir_res = []
  self.conn.dir('.', dir_res.append)
  files = [f.split(None, 8)[-1] for f in dir_res if f.startswith('-')]
  dirs = [f.split(None, 8)[-1] for f in dir_res if f.startswith('d')]
  return (files, dirs)
  def walk(self, next_dir):
  print 'Walking to', next_dir
  self.conn.cwd(next_dir)
  try:
  os.mkdir(next_dir)
  except OSError:
  pass
  os.chdir(next_dir)
  ftp_curr_dir = self.conn.pwd()
  local_curr_dir = os.getcwd()
  files, dirs = self.get_dirs_files()
  print "FILES: ", files
  print "DIRS: ", dirs
  for f in files:
  print next_dir, ':', f
  outf = open(f, 'wb')
  try:
  self.conn.retrbinary('RETR %s' % f, outf.write)
  finally:
  outf.close()
  for d in dirs:
  os.chdir(local_curr_dir)
  self.conn.cwd(ftp_curr_dir)
  self.walk(d)
  def run(self):
  self.walk('.')
  def main():
  f = FTPSync()
  f.run()
  if __name__ == '__main__':
  main()

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com