【原文链接】Python代码集----paramiko应用之远程在linux系统上执行命令并获取回显
(1)首先需要安装一下paramiko库
pip install paramiko
(2)封装好的代码类如下
import paramiko
class SSHClient(object):
def __init__(self,host,username,password,port=22):
self.__host=host
self.__username=username
self.__password=password
self.__port=port
self.__ssh=None
self.connect()
def __del__(self):
self.close()
def connect(self):
self.__ssh = paramiko.SSHClient()
self.__ssh.set_missing_host_key_policy(\
paramiko.AutoAddPolicy())
self.__ssh.connect(hostname=self.__host,port=self.__port,\
username=self.__username,password=self.__password)
def exec(self,cmd):
stdin, stdout, stderr = self.__ssh.exec_command(cmd,\
timeout=1800)
output=stdout.read().decode('utf-8')
return output
def close(self):
self.__ssh.close()
(3)使用方式如下,比如通过VMWare安装一个linux虚拟机,ip地址为192.168.1.144,如下代码为远程在linux机器上执行ipconfig命令
if __name__=="__main__":
ssh=SSHClient("192.168.1.144","root","xxxxxx")
output = ssh.exec("ifconfig")
print(output)
执行结果如下,即将ifconfig命令的回显拿到了