python用paramiko模块上传本地目录到远程目录

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
import paramiko,datetime,os
hostname= '192.168.1.100'
username= 'root'
password= '123456'
port=22
def 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  e
if  __name__== '__main__' :
     local_dir= '/home/soft/'
     remote_dir= '/tmp/aaa/'
     upload(local_dir,remote_dir)

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



本文转自 lover00751CTO博客,原文链接:http://blog.51cto.com/wangwei007/1285412,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值