使用pexpect自动执行IP验证

时间:2018-09-12 23:13:41

标签: python ssh network-programming pexpect switching

我的最终目标是登录到交换机,将CDP邻居详细信息写入文件。解析IP地址并在IP地址上执行ping操作,然后将其输出到文件中。我搜索了论坛,但没有发现与切换真正相关的内容。主要是服务器,我已经从那里适应了。但是现在我被困住了。

我已登录到交换机,登录提示似乎已写入文件,但仅此而已。

请原谅代码中的错误。另外,第二个try块正在进行中。我是python的新手,正在学习。我愿意接受所有批评和建议。我想知道我做错了什么,修复它,然后从那里构建。

谢谢!

import pexpect
import getpass
import sys
import re
import os
import time


try:
    switch = raw_input("Host: ")
    un = raw_input("Username: ")
    pw = getpass.getpass("Password: ")

    options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
    prompt = "#"


    connection_string = ("ssh %s@%s %s" % (un,switch,options))


    child = pexpect.spawn(connection_string, timeout=5)
    file_output = open('switch_output.txt','wb+')
    child.logfile = file_output
    rva12 = "";

    child.expect(re.escape("password:"))
    time.sleep(1)
    child.sendline(pw)
    time.sleep(1)
    child.expect(prompt)
    time.sleep(1)
    child.sendline("no page")
    time.sleep(1)
    child.expect(prompt)
    child.sendline("show cdp nei det")
    time.sleep(1)
    child.expect(prompt)
    child.before

    file_output.close()

except Exception as e:
    print("Failed on login")
    print(sys.exc_info()[0].__name__,
          os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
          sys.exc_info()[2].tb_lineno)
    print(e)


try:
    f = open('switch_output.txt', 'r')
    pattern_one = re.compile('.*A\d\n|\:\s\d{2,}\.\d{2,}\.\d{1,}.\d{1,}?')

    for line in f:
        matches = []

        if pattern_one.search(line):
        matches.append(line.split(':', 1)[-1].strip())

        mp = re.compile('\d{2,}\.\d{2,}\.\d{1,}.\d{1,}')

        with open('MDF1.txt', 'wb+') as file:
            for match in matches:
                if mp.search(match):
                    file.write(match+'\n')
                    file.close()

        for line in open('MDF1.txt','r'):
            child.expect(prompt)
            child.sendline('ping '+ line)
            time.sleep(10)


except Exception as e:
    print(sys.exc_info()[0].__name__,
        os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
        sys.exc_info()[2].tb_lineno)
    print(e)

0 个答案:

没有答案