ktbyers / netmiko

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

error: Router prompt not found: Error: Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]: #1776

Closed magnate3 closed 2 years ago

magnate3 commented 4 years ago

from netmiko import ConnectHandler import logging logging.basicConfig(filename="test.log", level=logging.DEBUG) huawei = {'device_type': 'huawei', 'ip': '10.10.30.253', 'username': 'root@default', 'password': 'XXXX','port': 22}

net_connect = ConnectHandler(**huawei) sshConfirm = net_connect.find_prompt() print('login ' + sshConfirm) commands = ['dis arp'] output = net_connect.send_config_set(commands) print(output) net_connect.disconnect()

the prog run with this bug error: Router prompt not found: Error: Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]:

I solved the problem by this :

        if "[Y/N]" in prompt:
            self.write_channel("N"+self.RETURN)
            prompt = "<JG05-SA-01-CE8850>"
        #Check that ends with a valid terminator character
        if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
            raise ValueError("Router prompt not found: {0}".format(prompt))

        # Strip off any leading HRP_. characters for USGv5 HA
        prompt = re.sub(r"^HRP_.", "", prompt, flags=re.M)

        # Strip off leading and trailing terminator
        prompt = prompt[1:-1]
        prompt = prompt.strip()
        self.base_prompt = prompt
        log.debug("prompt: {0}".format(self.base_prompt))

        return self.base_prompt
ktbyers commented 4 years ago

Can you provide some details on the context?

I assume it is the router that is sending this message:

Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]:

Why is it doing that i.e. what on the device's CLI is necessitating that?

Kirk

magnate3 commented 4 years ago

DEBUG:paramiko.transport:starting thread (client mode): 0x8f9c0290L DEBUG:paramiko.transport:Local version/idstring: SSH-2.0-paramiko_2.7.1 DEBUG:paramiko.transport:Remote version/idstring: SSH-2.0-- INFO:paramiko.transport:Connected (version 2.0, client -) DEBUG:paramiko.transport:kex algos:[u'diffie-hellman-group-exchange-sha256', u'ecdh-sha2-nistp521', u'ecdh-sha2-nistp384', u'ecdh-sha2-nistp256', u'diffie-hellman-group-exchange-sha1', u'sm2kep-sha2-nistp256'] server key:[u'ssh-dss', u'ssh-rsa', u'ecdsa-sha2-nistp521'] client encrypt:[u'aes256-ctr', u'aes128-ctr'] server encrypt:[u'aes256-ctr', u'aes128-ctr'] client mac:[u'hmac-sha2-256', u'hmac-sha2-256-96', u'hmac-sha1-96'] server mac:[u'hmac-sha2-256', u'hmac-sha2-256-96', u'hmac-sha1-96'] client compress:[u'none', u'zlib'] server compress:[u'none', u'zlib'] client lang:[u''] server lang:[u''] kex follows?False DEBUG:paramiko.transport:Kex agreed: ecdh-sha2-nistp256 DEBUG:paramiko.transport:HostKey agreed: ecdsa-sha2-nistp521 DEBUG:paramiko.transport:Cipher agreed: aes128-ctr DEBUG:paramiko.transport:MAC agreed: hmac-sha2-256 DEBUG:paramiko.transport:Compression agreed: none DEBUG:paramiko.transport:kex engine KexNistp256 specified hash_algo DEBUG:paramiko.transport:Switch to new keys ... DEBUG:paramiko.transport:Adding ecdsa-sha2-nistp521 host key for 10.10.30.253: b6d87e3a5fee634c324c9699dcb14012 DEBUG:paramiko.transport:userauth is OK INFO:paramiko.transport:Authentication (password) successful! DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes DEBUG:paramiko.transport:Secsh channel 0 opened. DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok DEBUG:netmiko:read_channel: Warning: The initial password poses security risks. The password needs to be changed. Change now? [Y/N]: DEBUG:netmiko:read_channel: DEBUG:netmiko:read_channel: DEBUG:netmiko:In set_base_prompt DEBUG:netmiko:read_channel: DEBUG:netmiko:write_channel:

DEBUG:netmiko:read_channel: Error: Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]: DEBUG:netmiko:write_channel:

DEBUG:netmiko:read_channel: Error: Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]: DEBUG:netmiko:read_channel: DEBUG:netmiko:read_channel: DEBUG:netmiko:write_channel: return

DEBUG:netmiko:Pattern is: > DEBUG:netmiko:write_channel: exit

DEBUG:paramiko.transport:EOF in transport thread

ktbyers commented 4 years ago

@magnate3 So this is the very first time configuring this box?

Can you show me what the full SSH-CLI session looks like in this case?

magnate3 commented 4 years ago

support huawei different models switch

class HuaweiBase(CiscoBaseConnection): def session_preparation(self): """Prepare the session after the connection has been established.""" self._test_channel_read() self.set_base_prompt() self.disable_paging(command="screen-length 0 temporary")

Clear the read buffer

    time.sleep(0.3 * self.global_delay_factor)
    self.clear_buffer()

def config_mode(self, config_command="system-view"):
    """Enter configuration mode."""
    return super(HuaweiBase, self).config_mode(config_command=config_command)

def exit_config_mode(self, exit_config="return", pattern=r">"):
    """Exit configuration mode."""
    return super(HuaweiBase, self).exit_config_mode(
        exit_config=exit_config, pattern=pattern
    )

def check_config_mode(self, check_string="]"):
    """Checks whether in configuration mode. Returns a boolean."""
    return super(HuaweiBase, self).check_config_mode(check_string=check_string)

def check_enable_mode(self, *args, **kwargs):
    """Huawei has no enable mode."""
    pass

def enable(self, *args, **kwargs):
    """Huawei has no enable mode."""
    return ""

def exit_enable_mode(self, *args, **kwargs):
    """Huawei has no enable mode."""
    return ""

def set_base_prompt(
    self, pri_prompt_terminator=">", alt_prompt_terminator="]", delay_factor=1
):
    """
    Sets self.base_prompt

    Used as delimiter for stripping of trailing prompt in output.

    Should be set to something that is general and applies in multiple contexts. For Comware
    this will be the router prompt with < > or [ ] stripped off.

    This will be set on logging in, but not when entering system-view
    """
    log.debug("In set_base_prompt")
    delay_factor = self.select_delay_factor(delay_factor)
    self.clear_buffer()
    self.write_channel(self.RETURN)
    time.sleep(0.5 * delay_factor)
    prompt = self.read_channel()
    prompt = self.normalize_linefeeds(prompt)
    '''
    log.debug("prompt is : %s", prompt)
    if "[Y/N]" in prompt:
        log.debug("First time logging in")
        self.write_channel("N"+self.RETURN)
        #self.write_channel("N")
        #self.base_prompt = prompt
        self.base_prompt = ""
        return self.base_prompt
    '''
    # If multiple lines in the output take the last line
    #prompt = self.read_channel()
    #prompt = self.normalize_linefeeds(prompt)
    prompt = prompt.split(self.RESPONSE_RETURN)[-1]
    prompt = prompt.strip()
    log.debug("prompt is : %s", prompt)
    if "[Y/N]" in prompt:
        self.write_channel("N"+self.RETURN)
        prompt = "<>"
        #prompt = "<JG05-SA-01-CE8850>"
        #self.base_prompt = "<JG05-SA-01-CE8850>"
        #self.read_channel()
        #return self.base_prompt
    #Check that ends with a valid terminator character
    if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
        raise ValueError("Router prompt not found: {0}".format(prompt))

    # Strip off any leading HRP_. characters for USGv5 HA
    prompt = re.sub(r"^HRP_.", "", prompt, flags=re.M)

    # Strip off leading and trailing terminator
    prompt = prompt[1:-1]
    prompt = prompt.strip()
    self.base_prompt = prompt
    log.debug("prompt: {0}".format(self.base_prompt))

    return self.base_prompt
ktbyers commented 4 years ago

@magnate3 I didn't understand your response? So if this a different model-type of Huawei switch then you should create a new driver for it.

The process is here:

https://github.com/ktbyers/netmiko/blob/develop/VENDOR.md

magnate3 commented 4 years ago

hi,kbtbyers the phenomenon is like this : first,my program is

from netmiko import ConnectHandler
import logging
logging.basicConfig(filename="test_248.log", level=logging.DEBUG)

huawei = {'device_type': 'huawei_vrpv8', 'ip': '10.xx.xx.248', 'username': 'root@default', 'password': 'Adm.','port': 22, }
net_connect = ConnectHandler(**huawei)
sshConfirm = net_connect.find_prompt()
print('login ' + sshConfirm)
commands = ['dis version']
output = net_connect.send_config_set(commands)
print(output)
net_connect.disconnect()

secondly, my swich is

ssh 10.10.xx.xx -l admin@default User Authentication Enter password:

Warning: The initial password poses security risks. The password needs to be changed. Change now? [Y/N]:n Info: The max number of VTY users is 5, the number of current VTY users online is 1, and total number of terminal users online is 1. The current login time is 2020-07-20 10:15:14. The last login time is 2020-07-16 10:26:00 from 10.10.16.81 through SSH.

dis ver Huawei Versatile Routing Platform Software VRP (R) software, Version 8.180 (CE8850EI V200R005C10SPC800) Copyright (C) 2012-2018 Huawei Technologies Co., Ltd. HUAWEI CE8850-64CQ-EI uptime is 122 days, 18 hours, 19 minutes Patch Version: V200R005SPH013 CE8850-64CQ-EI(Master) 1 : uptime is 122 days, 18 hours, 18 minutes StartupTime 2020/03/19 15:57:10 Memory Size : 4096 M bytes Flash Size : 2048 M bytes CE8850-64CQ-EI version information 1. PCB Version : CEM64CQP01 VER A 2. MAB Version : 1 3. Board Type : CE8850-64CQ-EI 4. CPLD1 Version : 101 5. CPLD2 Version : 101 6. BIOS Version : 192 **thirdly**,I run the program and find the bug is Error: Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]: **fourthly,I** change the netmiko/huawei/huawei.py code, you can see the difference of the code in this site: **https://github.com/magnate3/netmiko/commit/1410c17d5696a3473a11a74d97120660e0024e04**
ktbyers commented 4 years ago

Which version of Netmiko are you using?

magnate3 commented 4 years ago

netmiko 2.4.2

Zuquim commented 4 years ago

If I'm not mistaken, this happens after a new local SSH user is created (not sure if the behavior is limited to this type of user) in a Huawei switch. When the new user logs in, the device displays the following prompt:

Warning: The initial password poses security risks.
The password needs to be changed. Change now? [Y/N]:

If answered with anything (including <cr>) other than Y or N, it will enter a loop displaying the prompt below until the user inputs Y or N, or the prompt timeout* is reached (which is N by default).

Error: Please choose 'YES' or 'NO' first before pressing 'Enter'. [Y/N]:

* I've just tested this said timeout, and it is 30 seconds counting from the last time the device received an input (any kind of keystroke such as letters, numbers, or <cr>). Tested on a S6720 running VRP 5.170 (V200R010C00SPC600).

This post login behavior will persist for this user until the password is updated by answering Y in this prompt.

How else may I help with this issue, @ktbyers ?

ktbyers commented 2 years ago

This password prompting should now be properly handled in the Huawei driver so I am going to close this issue.

Netmiko will respond with N if it sees that prompt.