上一篇讲的是用来执行命令用的SSHclient方式,今天来给大家个Transport的方式,可以用来Upload和Download,希望能帮到大家
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import paramiko.util
CONN_Info = {"host": "172.26.32.139",
"port": 22,
"username": "ice",
"password": "xxx"}
def method_client():
paramiko.util.log_to_file("D:\\SSH_Connect.log")
SSH_Socket = paramiko.SSHClient()
SSH_Socket.set_missing_host_key_policy(paramiko.AutoAddPolicy())
SSH_Socket.connect(CONN_Info["host"], CONN_Info["port"], CONN_Info["username"], CONN_Info["password"])
stdin, stdout, stderr = SSH_Socket.exec_command("ls")
for Line in stdout.readlines():
print(Line, end="")
SSH_Socket.close()
class method_transport(object):
def __init__(self, host, port, username, password):
self._host = host
self._port = port
self._username = username
self._password = password
self._transport = None
self._sftp = None
self._client = None
self._connect()
def _connect(self):
paramiko.util.log_to_file("D:\\SSH_Connect.log")
transport = paramiko.Transport((self._host, self._port))
transport.connect(username=self._username, password=self._password)
self._transport = transport
def download(self, remotepath, localpath):
if self._sftp is None:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.get(remotepath, localpath)
def upload(self, localpath, remotepath):
if self._sftp is None:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.put(localpath, remotepath)
def exec_command(self, command):
if self._client is None:
self._client = paramiko.SSHClient()
self._client._transport = self._transport
stdin, stdout, stderr = self._client.exec_command(command)
for Line in stdout.readlines():
print(Line, end="")
def close(self):
if self._transport:
self._transport.close()
if self._client:
self._client.close()
if __name__ == "__main__":
conn = method_transport(CONN_Info["host"], CONN_Info["port"], CONN_Info["username"], CONN_Info["password"])
localpath = "test.py"
remotepath = "/home/ice/test.py"
conn.upload(localpath, remotepath)
conn.exec_command("ls -l")
conn.download(remotepath, "testtest.py")
如果觉得我的文章对您有用,请点赞。您的支持将鼓励我继续创作!
赞0
添加新评论0 条评论