python paramiko模块上传本地目录到远程目录的例子

发布时间:2020-07-20编辑:脚本学堂
分享一例python代码,使用模块paramiko将本地目录上传到远程目录,学习下paramiko模块的详细用法,有需要的朋友一起研究下。

python paramiko模块默认中只可以上传文件,不能直接上传目录。
这里使用os.walk方法与paramiko结合实现一个上传目录的方法,分享给大家。

python paramiko模块上传目录的实例代码,如下:
 

复制代码 代码示例:
#!/usr/bin/env python
#edit www.jb200.com
#
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)

以上就是python paramiko模块实现上传目录的代码,经测试,正常可用。