python-3.x 未检测到Netmiko模式

14ifxucb  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(301)

我用cisco 2960X交换机运行此代码。

from netmiko import ConnectHandler

network_device= {
    "host": "192.168.xxx.xxx",
    "username": "xxxx",
    "password": "xxxx",
    "device_type": "cisco_ios",
    "session_log": "netmiko_session.log"
}

connect= ConnectHandler(**network_device)
connect.enable()

interface_name= "GigabitEthernet1/0/10"

def send_command(command):
    return connect.send_command(command)
try:
    send_command('enable')
    send_command('configure terminal')
except Exception as e:
    print(e)
    print("Failed!")

但在我得到下面的错误。

Pattern not detected: 'Switch\\#' in output.

Things you might try to fix this:
1. Explicitly set your pattern using the expect_string argument.
2. Increase the read_timeout to a larger value.
You can also look at the Netmiko session_log or debug log for more information.

Failed!

请检查netmiko_会话. log的以下内容

Switch#
Switch#terminal width 511
Switch#terminal length 0
Switch#
Switch#enable
Switch#
Switch#configure terminal
Enter configuration commands, one per line.  End with CNTL/Z.
Switch(config)#

我重命名了交换机主机名。但同样的错误仍然存在。

bejyjqdl

bejyjqdl1#

如果您想更改配置,您应该考虑使用ssh.send_config_set方法:

from netmiko import ConnectHandler

network_device= {
    "host": "192.168.xxx.xxx",
    "username": "xxxx",
    "password": "xxxx",
    "device_type": "cisco_ios",
    "session_log": "netmiko_session.log"
}

connect = ConnectHandler(**network_device)
config_commands = [
    'hostname NEW_NAME',
    'interface Gi1/0/10',
    'description NEW_IF_NAME'
]
connect.enable()
connect.send_config_set(config_commands)
connect.save_config()
connect.disconnect()

当您发送命令“conf terminal”时,提示符会更改以反映配置模式,并且它开始看起来像Switch(config)#,而netmiko仍然在等待Switch#
因此,如果您想逐个发送命令,也可以设置预期的提示符或使用“send_command_timing”

# this one will just wait 2 seconds before thinking that the command was applied to the device
connect.send_command_timing('hostname NEW_NAME', read_timeout=2)
# this one will expect a custom string from the device after the command is entered
connect.send_command('hostname NEW_NAME', expect_string='(config)#')
# be aware, that if you enter "configure interface" mode prompt will also change
connect.send_command('interface gi1/0/10', expect_string='(config-if)#')

相关问题