#!/usr/bin/python
# coding=utf-8
import paramiko
import os
def sftp_upload(host,port,username,password,local,remote):
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local):#判断本地参数是⽬录还是⽂件
for f in os.listdir(local):#遍历本地⽬录
sftp.put(os.path.join(local+f),os.path.join(remote+f))#上传⽬录中的⽂件
else:
sftp.put(local,remote)#上传⽂件
except Exception,e:
print('upload exception:',e)
sf.close()
def sftp_download(host,port,username,password,local,remote):
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local):#判断本地参数是⽬录还是⽂件
for f in sftp.listdir(remote):#遍历远程⽬录
sftp.get(os.path.join(remote+f),os.path.join(local+f))#下载⽬录中⽂件
else:
sftp.get(remote,local)#下载⽂件
except Exception,e:
print('download exception:',e)
sf.close()
if __name__ == '__main__':
host = '192.168.1.2'#主机
port = 22 #端⼝
username = 'root' #⽤户名
password = '123456' #密码
local = 'F:\\sftptest\\'#本地⽂件或⽬录,与远程⼀致,当前为windows⽬录格式,window⽬录中间需要使⽤双斜线
remote = '/opt/tianpy5/python/test/'#远程⽂件或⽬录,与本地⼀致,当前为linux⽬录格式
sftp_upload(host,port,username,password,local,remote)#上传
#sftp_download(host,port,username,password,local,remote)#下载
Python使⽤sftp实现上传和下载功能(实例代码)
于 2022-06-30 10:09:45 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)