Press ESC to close

python paramiko实现SSH 多台设备多条命令写入到不同的文件

代码:

'''
Author: 20004@163.com
Date: 2022-08-01 10:19:01
LastEditTime: 2022-08-01 10:30:59
LastEditors: 20004@163.com
Description: 
FilePath: \PythonCode\百度下拉词\ssh10-多台设备多条命令写入文件.py
可以输入预定的版权声明、个性签名、空行等
''' 
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(): 
    outputFileName = device + ' '  + '_output.txt'
    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)

    with open(outputFileName, 'wb') as f:
        for command in commands:
           print(f"Executing command {command}")
           new_connection.send(command)
           time.sleep(2)
           output = new_connection.recv(max_buffer)
           f.write(output)
    
    new_connection.close()

发表回复