循环遍历共享文件夹,不需要知道目录深度拷贝上传

# _*_ coding: utf-8 _*_
__author__ = 'pythonwu'
__date__ = "2018/8/21 17:10"

import shutil
import os
import sys
import paramiko
from datetime import datetime


hostname = 'xxx'
username = 'xxx'
password = 'xxx'
port = 22

def upload(local_dir,remote_dir):
try:
transport = paramiko.Transport(hostname,port)
transport.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
print('upload file start %s' %datetime.now())
for root,dirs,files in os.walk(local_dir):
for filespath in files:
local_file = os.path.join(root,filespath)
a = local_file.replace(local_dir,"")
remote_file = os.path.join(remote_dir,a)
remote_file_convert = remote_file.replace('\\','/').replace('//','/')
print(remote_file_convert)
try:
sftp.put(local_file,remote_file_convert)
except Exception as e:
repr(e)
for name in dirs:
local_path = os.path.join(root,name)
a = local_path.replace(local_dir,"")
remote_path = os.path.join(remote_dir,a)
remote_path_convert = remote_path.replace('\\','/').replace('//','/')
print(remote_path_convert)
try:
sftp.mkdir(remote_path_convert)
print("mkdir path %s" %remote_path_convert)
except Exception as e:
repr(e)
print('upload file success %s' %datetime.now())
transport.close()
except Exception as e:
repr(e)





if __name__ == '__main__':
local_dir = '\\\\tcent.cn\\dfs\\00.常用软件\\17.IT专用软件\\02.白名单软件库收集'
remote_dir = '\\\\data\\1'
upload(local_dir,remote_dir)
posted @ 2018-08-22 17:34  五等码农  阅读(474)  评论(0编辑  收藏  举报