How to pass netmiko expect_string with regex pattern as a variable?

问题描述 投票:0回答:1

尝试管理未在 netmiko 中列出的网络元素,因此使用自动检测。有一个 expect_string 参数。我尝试使用带有起始模式的 .* 来表示更多字符并以 # 或 $ 或 ? 之一结尾。当我直接这样做时,这很好用。但是,当我将其分配给变量时,它不起作用。我不确定是什么错误,并试图在 netmiko 和 netmiko 文档中查看以前的 stackoverflow 评论,但找不到示例。

在执行命令时,此网络元素将有一个提示,该提示将以相同的前缀开头,但将具有基于其间给出的命令的字符,并且提示的结尾可以更改为 $ 或?代替 #。我不想简单地使用 [$?#] 因为相同的字符将出现在某些命令的输出中,并且可能不是提示的必要匹配项。

在不工作的情况下,我得到了错误

netmiko.exceptions.ReadTimeout: 未检测到模式:'INCHN34003.*[#?$]' 在输出中。

我看到变量已正确分配 - SetExpectString 是 r"INCHN34003.*[#?$]"

工作代码:

NW_Session.send_command ( command_string=current_command, expect_string = r"INCHN34003.*[#?$]"

无效代码:

        NW_prompt = NW_Session.find_prompt()
        if ('#' in NW_prompt):
            Hash_location = NW_prompt.find('#')
            SetExpectString = 'r"' + NW_prompt[:(Hash_location-1)] + '.*[#?$]'
            print(f"# is in the location {Hash_location} and SetExpectString is {SetExpectString}")
            with open(InputKargs['OLT_COMMAND_File'], 'r') as i_file:
                while current_command := i_file.readline():
                    NW_Session.send_command ( command_string=current_command, expect_string = SetExpectString )

prompt netmiko
1个回答
0
投票

我可能会这样做:

# Drop the last character from the prompt
nw_prompt = nw_prompt[:-1]

# There might be regex special characters in the prompt (treat them literally)
base_pattern = re.escape(nw_prompt)

# Construct final regex pattern (I dropped the ? as I doubted it was needed)
pattern = rf"{base_pattern}.*[#$]"
© www.soinside.com 2019 - 2024. All rights reserved.