Press ESC to close

python paramiko 实现SSH 多台设备多条命令

代码:

 
import paramiko
import time

commands = ['uname -a\n', 'df -h\n']

max_buffer = 65535
devices = {
   'linux1': {
      'ip': 'xxx',
      'username': 'xxx',
      'password': 'xxx',
      'port': '22'
      },
   'linux2': {
      'ip': 'xxx',
      'username': 'xxx',
      'password': 'xxx',
      'port': '22'
      }
   }


def get_connection(host, username, password, port):
   ssh = paramiko.SSHClient()
   ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   ssh.connect(hostname=host,username=username, password=password, port=port, look_for_keys=False, allow_agent=False)
   return ssh


def clear_buffer(connection):
    if connection.recv_ready():
        return connection.recv(max_buffer)


for device in devices.keys(): 
   connection = get_connection(host=devices[device]['ip'], username=devices[device]['username'], password=devices[device]['password'], port=devices[device]['port'])
   new_connection = connection.invoke_shell()
   output = clear_buffer(new_connection)
   time.sleep(2)
   new_connection.send("terminal length 0\n")
   output = clear_buffer(new_connection)
    
   for command in commands:
      print(f"Executing command {command}")
      new_connection.send(command)
      time.sleep(2)
      output = new_connection.recv(max_buffer)
      print(output)
           
new_connection.close()

发表回复