博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python用paramiko模块上传本地目录到远程目录
阅读量:7145 次
发布时间:2019-06-29

本文共 1608 字,大约阅读时间需要 5 分钟。

   python用paramiko模块默认中只可以上传文件,在网上也没有找到合适的直接上传目录的方法,所以用os.walk方法和paramiko结合写了一个上传目录的方法,代码如下:

#!/usr/bin/env pythonimport paramiko,datetime,oshostname='192.168.1.100'username='root'password='123456'port=22def upload(local_dir,remote_dir):    try:        t=paramiko.Transport((hostname,port))        t.connect(username=username,password=password)        sftp=paramiko.SFTPClient.from_transport(t)        print 'upload file start %s ' % datetime.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)                try:                    sftp.put(local_file,remote_file)                except Exception,e:                    sftp.mkdir(os.path.split(remote_file)[0])                    sftp.put(local_file,remote_file)                print "upload %s to remote %s" % (local_file,remote_file)            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)                try:                    sftp.mkdir(remote_path)                    print "mkdir path %s" % remote_path                except Exception,e:                    print e        print 'upload file success %s ' % datetime.datetime.now()        t.close()    except Exception,e:        print eif __name__=='__main__':    local_dir='/home/soft/'    remote_dir='/tmp/aaa/'    upload(local_dir,remote_dir)

   经过多次测试,完美实现。

转载地址:http://kdgrl.baihongyu.com/

你可能感兴趣的文章
规划一个智能工厂应避免的十个坑
查看>>
Linux 虚拟网络设备详解之 Bridge 网桥
查看>>
LaTeX的简单使用方法
查看>>
第二十四章:页面导航(四)
查看>>
数字对讲系统开发札记(前端linux c 后端 c#)
查看>>
阿里在使用一种更灵活的软件集成发布模式
查看>>
SpringBoot使用Nacos配置中心
查看>>
SOP 1.2.0 发布,开放平台解决方案项目
查看>>
Element 2.6.3 发布,基于 Vue 2.0 的桌面端组件库
查看>>
丰田研发智能汽车FV2,可利用肢体进行操控
查看>>
基于kubeadm的kubernetes高可用集群部署
查看>>
定位「数字化助手」,腾讯想用服务创新助力产业智慧升级
查看>>
golang之sync.Mutex互斥锁源码分析
查看>>
SAP增强的PA教材内容
查看>>
jQuery系列 第八章 jQuery框架Ajax模块
查看>>
C#使用Xamarin开发可移植移动应用(3.Xamarin.Views控件)附源码
查看>>
Java 模拟基于UDP的Socket通信
查看>>
有关 Windows Lite 的一切,只为对抗 Chrome OS?
查看>>
Android 自定义控件之SlidingMenuVertical顶部悬浮(垂直折叠抽屉,有滑动渐变回调,可自行添加渐变动画)...
查看>>
NG-ZORRO 7.0.1 发布,Ant Design 的 Angular 实现
查看>>