问题描述:
如果python文件内,执行一条命令,就可以执行,但执行命令超过一条后,就会报错,提示:Administratively prohibited
组网及组网描述:
import os
import paramiko
def execute_commands_on_device(hostname, username, password, commands, backup_dir):
try:
# 建立SSH连接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=username, password=password)
# 遍历命令列表并执行
for cmd in commands:
# 执行命令
stdin, stdout, stderr = ssh.exec_command(cmd)
output = stdout.read().decode()
error = stderr.read().decode()
# 处理命令输出和错误
if output:
print(f"Command '{cmd}' output:")
print(output)
if error:
print(f"Command '{cmd}' error:")
print(error)
# 生成备份文件的路径和文件名
filename = f"{hostname}_{cmd.replace(' ', '_')}.txt"
backup_path = os.path.join(backup_dir, filename)
# 保存命令输出到文件
with open(backup_path, "w") as file:
file.write(output)
print(f"Command '{cmd}' output saved to {backup_path}")
except paramiko.AuthenticationException:
print(f"Device {hostname} authentication failed, please check the username and password.")
except paramiko.SSHException as e:
print(f"Device {hostname} SSH connection error: {str(e)}")
except Exception as e:
print(f"Device {hostname} error: {str(e)}")
finally:
if ssh:
ssh.close()
def read_device_list(file_path):
with open(file_path, "r") as file:
return [line.strip() for line in file.readlines()]
# 设备清单文件路径
device_list_file = "ips.txt"
# 备份目录
backup_directory = "D:\\Backup"
# 登录信息
username = "admin"
password = "admin"
# 要执行的命令列表
commands_to_execute = [
"display current-configuration",
"display version",
# 添加更多命令...
]
# 读取设备清单
devices = read_device_list(device_list_file)
# 逐个设备执行命令
for hostname in devices:
execute_commands_on_device(hostname, username, password, commands_to_execute, backup_directory)
Secsh channel 1 open FAILED: open failed: Administratively prohibited
暂无评论