python下载文件传到服务器_Python本地和服务器实现文件上传下载

# !/usr/bin/env python

# -*- coding: utf8 -*-

# coding: utf-8

import paramiko

import datetime

import os

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

hostname= '192.0.0.0'

username= 'root'

password= '123'

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, filesin os.walk(local_dir):

print('[%s][%s][%s]' % (root, dirs, files))

for filespathin 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 namein 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)

def remote_scp(remote_path, local_path):

t= paramiko.Transport((hostname, 22))

t.connect(username=username, password=password)

sftp= paramiko.SFTPClient.from_transport(t)

src= remote_path

des= local_path

sftp.get(src, des)

t.close()

if __name__== '__main__':

# local_dir = r'E:\test'

# remote_dir = '/home/File/'

# upload(local_dir, remote_dir)

remote_path= '/home/File/File.txt'

local_path= r'E:\MD5\download\File.txt'

remote_scp(remote_path, local_path)

你可能感兴趣的:(python下载文件传到服务器)