import paramiko import json import time from paramiko.ssh_exception import NoValidConnectionsError from paramiko.ssh_exception import AuthenticationException class SSHConnection(): def __init__(self, hostname, port, username, password): self.hostname = hostname self.port = port self.username = username self.password = password try: self.connect() except (AuthenticationException, NoValidConnectionsError, TimeoutError) as e: print(e) stdin, stdout, stderr = self.ssh.exec_command('system identity pr') output = stdout.read().decode() self.identity = output.split(':')[1].strip() def connect(self): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password) def run(self, input): output = self.cmd(input) # self.close() return output def cmd(self, input): stdin, stdout, stderr = self.ssh.exec_command(input) output = stdout.read().decode() # prompt = '[%s@MikroTik] > %s\n' % (self.username, input) prompt = '[%s@%s] > %s\n' % (self.username, self.identity, input) print(prompt + output) return output def close(self): self.ssh.close() if __name__ == '__main__': ssh = SSHConnection('192.168.64.201', 22, '路由器账号', '路由器密码') output = ssh.run('int pppoe-client pr') if output.find('R name="pppoe-out27"') >= 0: ssh.run('/ip pool set test ranges=1.1.1.27') ssh.close()