Python Paramiko SSH 命令执行优化
import paramiko
def run_ssh_command(command): with paramiko.SSHClient() as ssh_client: ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname='192.168.1.1', port=22, username='admin', password='admin') stdin, stdout, stderr = ssh_client.exec_command(command) output = stdout.read().decode() print(output)
执行命令
commands = ['system-view', 'netconf', 'quit'] for command in commands: run_ssh_command(command)
优化:
1. 使用with语句,自动关闭SSH连接
2. 将多次执行命令的操作放入循环中,避免代码重复
3. 删除不必要的注释
原文地址: https://www.cveoy.top/t/topic/n33X 著作权归作者所有。请勿转载和采集!