import config
import paramiko
import time
class SSH_Tese_Tool():
"""
实例化类时自动调用该方法,链接服务器
"""
def __init__(self):
self.hostname = config.fuwuqi["userhost"]
self.username = config.fuwuqi["username"]
self.password = config.fuwuqi["password"]
self.port = config.fuwuqi["port"]
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
self.ssh_client.connect(hostname=self.hostname, username=self.username, password=self.password, port=self.port)
# 获取transport实例
self.transport = paramiko.Transport(self.hostname, self.port)
self.transport.connect(username=self.username, password=self.password)
# 关闭客户端方法
def close_ssh(self):
self.ssh_client.close()
# 关闭transport实例
def close_transport(self):
self.transport.close()
#客户端远程执行命令,并将结果返回
def remote_command(self,command):
stdin, stdout, stder = self.ssh_client.exec_command(command)
text = stdout.read().decode('utf-8')
return text
#本地上传文件到服务器
#注意,路径要填写根路径
def upload_fileToRemote(self,local_path,remote_path):
# #获取transport实例
# transport=paramiko.Transport(self.hostname,self.port)
# transport.connect(username=self.username,password=self.password)
#获取SFTP实例
sftp=paramiko.SFTPClient.from_transport(self.transport)
sftp.put(local_path,remote_path)
# 下载服务器文件到本地
# 注意,路径要填写根路径
def download_fileToLocal(self,remote_path,local_path):
transport=self.ssh_client.get_transport()
sftp=paramiko.SFTPClient.from_transport(transport)
sftp.get(remote_path,local_path)