windows上python上传文件到linux服务器指定路径下

# -*- coding: utf-8 -*-
"""
Created on Thu Sep  6 14:53:04 2018

@author: Administrator
"""

#!/usr/bin/env python
# coding: utf-8
import paramiko   
import datetime    
import os  
  
  
hostname='123.**.**.***'  
username='****'  
password='****'  
port=****  
  
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):  
            print('[%s][%s][%s]' % (root,dirs,files))  
            for filespath in files:  
                local_file = os.path.join(root,filespath)  
                print(11,'[%s][%s][%s][%s]' % (root,filespath,local_file,local_dir))  
                a = local_file.replace(local_dir,'').replace('\\','/').lstrip('/')  
                print('01',a,'[%s]' % remote_dir)  
                remote_file = os.path.join(remote_dir,a)  
                print(22,remote_file)  
                try:  
                    sftp.put(local_file,remote_file)  
                except Exception as e:  
                    sftp.mkdir(os.path.split(remote_file)[0])  
                    sftp.put(local_file,remote_file)  
                    print("66 upload %s to remote %s" % (local_file,remote_file))  
            for name in dirs:  
                local_path = os.path.join(root,name)  
                print(0,local_path,local_dir)  
                a = local_path.replace(local_dir,'').replace('\\','')  
                print(1,a)  
                print(1,remote_dir)  
                remote_path = os.path.join(remote_dir,a)  
                print(33,remote_path)  
                try:  
                    sftp.mkdir(remote_path)  
                    print(44,"mkdir path %s" % remote_path)  
                except Exception as e:  
                    print(55,e)  
        print('77,upload file success %s ' % datetime.datetime.now())  
        t.close()  
    except Exception as e:  
        print(88,e)  
          
if __name__=='__main__':  
     local_dir='C:/Users/Administrator/Desktop/tc' # 本地需要上传的文件所处的目录
     remote_dir='/data/oss/'  #linux下目录
     upload(local_dir,remote_dir)

以上代码可以实现本地文件往服务器某目录下上传文件,需要注意的是在main中声明的本地文件路径要写正确,记得是路径,不要精确到文件了。

发布了96 篇原创文章 · 获赞 161 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/qq_26803795/article/details/82461605