Python paramiko模块使用解析实现sftp

时间:2023-02-17 11:15:12

一、核心组件SFTPClient

put(self, localpath, remotepath, callback=None, confirm=True)
长传本地文件到远程SFTP服务端
参数说明:
localpath(str类型):需要上传的本地文件(源文件)
remotepath(str类型):远程路径(目标文件)
callback(function(init,init)):获取已接收的字节数及总传输字节数,以便回调函数调用,默认为None
confirm(bool类型):文件长传完毕后是否调用start()方法,以便确认文件的大小

get(self, remotepath, localpath, callback=None)
从远程SFTP服务端下载本地
参数说明:
remotepath(str类型):需要下载的远程文件
localpath(str类型):本地路径
callback(function(init,init)): 获取已接收的字节数及总传输字节数,以便回调函数调用,默认为None
(1)创建一个已连通的SFTP客户端通道,格式为:from_transport(cls,t)
(2)将本地文件上传到服务器,格式为:put(localpath, remotepath, callback=None, confirm=True)
(3)从服务器下载文件到本地,格式为:get(remotepath, localpath, callback=None)
(4)在服务器上创建目录,格式为:mkdir()
(5)在服务器上删除文件,格式为:remove(),删除具体目录,格式为rmdir()
(6)在服务器上重命名目录,格式为:rename()
(7) 查看服务器文件状态,格式为:stat()
(8)列出服务器目录下的文件,格式为:listdir()

二、基于SFTPClient连接

1、上传下载文件

import paramiko,time
scp = paramiko.Transport(('192.168.10.131',22))
scp.connect(username='root',password='123456')
sftp=paramiko.SFTPClient.from_transport(scp)
#上传文件
put_local_path = "D:\temp\cc.txt"
put_remote_path = "/tmp/put_cc.txt"
sftp.put(put_local_path, put_remote_path)
time.sleep(2)
#下载文件
get_local_path = "D:\temp\get_cc.txt"
get_remote_path = "/tmp/put_cc.txt"
sftp.get(get_remote_path, get_local_path)
scp.close()
#要指定下载的文件名,不能只是一个目录

2、上传文件

def upload_file(host, user, psw, local_file, remote_file, port=22):
with paramiko.Transport((host, port)) as transport:
# 连接服务
transport.connect(username=user, password=psw)
# 获取SFTP示例
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_file, remote_file)
transport.close()

if __name__ == '__main__':
upload_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test123.txt", "/home/test/test123.txt")

3、创建删除检查文件状态

import paramiko,time
scp = paramiko.Transport(('192.168.10.131',22))
scp.connect(username='root',password='123456')
sftp_conn=paramiko.SFTPClient.from_transport(scp)
sftp_conn.mkdir("/tmp/haha")
print(sftp_conn.listdir("/tmp")) #listdir返回结果是一个列表,可以遍历列表来检查是否有指定目录
sftp_conn.rmdir("/tmp/haha")
try:
result=sftp_conn.stat("/tmp/haha")
print(result)
except:
print("目录不存在")
scp.close()