pexpect输出超出ord

2024-06-16 15:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果这是一个愚蠢的问题,这是我第一次尝试python。我写了一个脚本,从一个文件中读取接口列表,登录到cisco 7600,然后调用一个函数来获取接口的状态和运行配置。我在每个界面上运行2个命令。问题是管理pexpect输出。有些接口和我期望的完全一样(没有双关语的意思),而另一些接口,它似乎根本不等待任何输出,还有一些接口在检查了2个或3个其他接口之后,一个命令的输出就会出现。现在我只是把它全部输出到系统标准输出. 一旦我开始工作,我会把它写进一个文件。我试过用sendline代替send,我玩过子级.超时, 子级.maxsize, 时间。睡觉... 我可以根据要求发布输出。我只是想不让这事太久。我遇到的问题是:

def get_int_conf(child, if_file, dev_type, prompt):
  open_file = "/home/" + if_file

  if dev_type == 'cisco':
      child.logfile = sys.stdout
      with open(open_file, 'r') as int_list:
#
#Pull name from list
#
          for int_name in int_list:
              print "Interface name is %s" % (int_name)
#
#Build correct syntax
#
              match1 = re.search("(Gi|Te)", int_name)
              match2 = re.search("[0-9]+/[0-9]+", int_name)
              if match1 and match2:
                  first_match = match1.group(1)
                  second_match = match2.group()
                  short_nm = first_match + second_match + " \n"
#
# Run show interface status commmand
#
              child.send('sh interface status | in ' + short_nm)
              child.expect(prompt)
              child.send('\n')
#
# Run show run interface command
#
              child.send('sh run interface ' + int_name)
              child.expect(prompt)
              child.send('\n')
  return()

Tags: 文件namesendchildifmatchopenprompt
1条回答
网友
1楼 · 发布于 2024-06-16 15:05:04

由于child是在函数之外创建和使用的,所以我首先要确保它首先进入“已知状态”,然后只是交替sendline和expect语句。我曾经在7600飞机上使用过这样的东西:

child.sendline('term len 0')  # if not already done, else just child.sendline('')
child.expect(prompt)
...
for int_name in int_list:
    ...
    child.sendline('sh interface status | in ' + short_nm)
    child.expect(prompt)
    child.sendline('sh run interface ' + int_name)
    child.expect(prompt)

也许很愚蠢,但我也会检查open_file中接口的顺序。在

旁注:您可以访问字符串缓冲区,这些缓冲区包含pexpect在每个child.expect()语句中匹配模式前后接收的内容,这些结构可以随意打印/处理:

^{pr2}$

您可能希望熟悉它们-它们是开发/调试期间的朋友,甚至可以在实际的脚本实现中使用它们。在

相关问题 更多 >