ktbyers / netmiko

Multi-vendor library to simplify Paramiko SSH connections to network devices
MIT License
3.59k stars 1.31k forks source link

Netmiko - OSError: Search pattern never detected in send_command_expect: #1898

Closed kaykuok closed 4 years ago

kaykuok commented 4 years ago

Hi everyone, i am new to python and i am writing a script for obtaining the output of "display diagnostic-information" of H3c switches.

The code is listed as below, `import openpyxl import time import netmiko from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException import getpass import logging from netmiko.base_connection import BaseConnection

my_wb = openpyxl.Workbook() my_sheet = my_wb.active localtime = time.localtime(time.time())

UName = input("Username:") PW = getpass.getpass("Login Password: ") EN = getpass.getpass("Enable Password: ")

for IP in iplist: Port = 23 Date = time.strftime('%Y%m%d%H%M%S', time.localtime())

#  Setup SSH Parameters
hp_comware = {
    'device_type': 'hp_comware_telnet',
    'ip': IP,
    'username': UName,
    'password': PW,
    'port': 23,  # optional, defaults to 22
    'secret': EN,  # enable password
    'verbose': False,  # optional, defaults to False
}
################################################################################################
filename = 'Debugging output for the batch command on ' + str(Date) + '.log'
logging.basicConfig(filename=filename, level=logging.DEBUG)
logger = logging.getLogger("netmiko")
################################################################################################
# telnet Login
all_devices = [hp_comware]
for devices in all_devices:
    try:
        print ('The host IP is:', IP)
        net_connect = ConnectHandler(**hp_comware)
        net_connect.enable()

    # When telnet time-out, bypass the device and create a doc 'Unreachable_IP_vyyyymmdd.log' to log this IP.
    except NetMikoTimeoutException:
        print('Device Unreachable: ' + devices['ip'] + '\n')
        with open('Unreachable_IP_v' + str(Date) + '.log', 'a', newline='') as unreach:
            unreach.write(devices['ip'] + '\n')
        continue

    # When telnet Authentication Failed, bypass the device and create a doc 'Auth_Failed.log_vyyyymmdd' to log this IP.
    except NetMikoAuthenticationException:
        print('Authentication Failed: ' + devices['ip'] + '\n')
        with open('Auth_Failed_v' + str(Date) + '.log', 'a', newline='') as auth_f:
            auth_f.write(devices['ip'] + '\n')
        continue

*** The following line is to "display diagnostic-information" and write to the file *

with open(str(IP) + '_v' + str(Date) + '.log', 'a', newline='') as SaveOutput:    
    cmd = "display diagnostic-information"
    cmds_output = net_connect.send_command("display diagnostic-information", "")
    time.sleep(1)
    if 'Save or display diagnostic information' in cmds_output:
        cmds_output = net_connect.send_command('n\n',cmd_verify=False) 
        print(cmds_output)
        Date = time.strftime('%Y%m%d%H%M%S', time.localtime())
        SaveOutput.write(f'#{cmd}\n{cmds_output}\n')

* End *****

`

But i am getting the error as below,

File "d:\ShareCache\user\Python\H3C_Telnet\TelnettoH3CSwitch.py", line 115, in <module> cmds_output = net_connect.send_command('n\n',cmd_verify=False) File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\netmiko\utilities.py", line 347, in wrapper_decorator return func(self, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\netmiko\base_connection.py", line 1429, in send_command raise IOError( OSError: Search pattern never detected in send_command_expect: Before\ pressing\ ENTER\ you\ must\ choose\ 'YES'\ or\ 'NO'\[Y/N\]:

And the command output is not able to write to the .log file, but it existi in the netmiko debug logger file like below,

` DEBUG:netmiko:Exiting disable_paging DEBUG:netmiko:read_channel: DEBUG:netmiko:write_channel: b'super\r\n' DEBUG:netmiko:Pattern is: (sw-itch|ssword) DEBUG:netmiko:read_channel: DEBUG:netmiko:read_channel: super

Please input the password to change the privilege level, press CTRL_C to abort.

Password: DEBUG:netmiko:Pattern found: (sw-itch|ssword) super

Please input the password to change the privilege level, press CTRL_C to abort.

Password: DEBUG:netmiko:write_channel: password!\r\n' DEBUG:netmiko:Pattern is: sw-itch DEBUG:netmiko:read_channel: DEBUG:netmiko:read_channel:

User privilege level is 3, and only those commands can be used

whose level is equal or less than this.

Privilege note: 0-VISIT, 1-MONITOR, 2-SYSTEM, 3-MANAGE

DEBUG:netmiko:Pattern found: sw\-itch User privilege level is 3, and only those commands can be used whose level is equal or less than this. Privilege note: 0-VISIT, 1-MONITOR, 2-SYSTEM, 3-MANAGE DEBUG:netmiko:read_channel: DEBUG:netmiko:write_channel: b'display diagnostic-information\r\n' DEBUG:netmiko:Pattern is: display\ diagnostic\-information DEBUG:netmiko:read_channel: DEBUG:netmiko:read_channel: display diagnostic-information Save or display diagnostic information (Y=save, N=display)? [Y/N]: DEBUG:netmiko:Pattern found: display\ diagnostic\-information display diagnostic-information Save or display diagnostic information (Y=save, N=display)? [Y/N]: DEBUG:netmiko:read_channel: DEBUG:netmiko:write_channel: b'\r\n' DEBUG:netmiko:read_channel: Before pressing ENTER you must choose 'YES' or 'NO'[Y/N]: DEBUG:netmiko:read_channel: DEBUG:netmiko:[find_prompt()]: prompt is Before pressing ENTER you must choose 'YES' or 'NO'[Y/N]: DEBUG:netmiko:read_channel: DEBUG:netmiko:write_channel: b'n\r\n' DEBUG:netmiko:read_channel: n ================================================================= ===============running CPU usage information=============== ================================================================= DEBUG:netmiko:read_channel: ===== Current CPU usage info =====` **The expected output of the script is to write the below output to the .log file but it can't now and pop-up the error** **Please help, thanks!**
kaykuok commented 4 years ago

I have changed the script with method of send_command_timing in the interactive part, it works fine with no error and all output can be written to the log file. Thanks.

with open(str(IP) + '_v' + str(Date) + '.log', 'a', newline='') as SaveOutput: cmds_output = net_connect.send_command("display diagnostic-information", "") cmds_output = net_connect.send_command_timing('n\n') Date = time.strftime('%Y%m%d%H%M%S', time.localtime()) SaveOutput.writelines(f'#{cmd}\n{cmds_output}\n')