如何使用python脚本telnet huawei开关?

时间:2018-04-19 07:09:08

标签: python python-3.x python-2.7

我想用python脚本telnet huawei switch来读取一些基本的工作人员,比如“display int brief”结果。我知道基本的huawei命令和一些编程。 我可以使用python脚本telnet cisco路由器。

这是我到目前为止的尝试

import telnetlib 
import datetime 

now = datetime.datetime.now() 
host = "myhost" # your router ip 
username = "user" # the username 
password = "pass" 

tn = telnetlib.Telnet(host,23,6) 
tn.read_until("Username:") 
tn.write(username+"\n") 
tn.read_until("Password:") 
tn.write(password+"\n") 
tn.write("display int description"+"\n") 
#tn.write("sh run"+"\n") 
tn.write("quit"+"\n") 
output = tn.read_all() 

fp = open("sw_hu.txt","w") 
fp.write(output) 
fp.close()

2 个答案:

答案 0 :(得分:0)

我会使用pexpect库然后打开与pexpect.spawn('telnet ip_address')模块文档的连接是一个很好的开始。如果你现在有命令,那么它主要是sendlineexpectbefore的组合。

    child = pexpect.spawn ('telnet %s' % dev_name)
    try:
        i = child.expect_exact(['Password:', 'Username:'])
    except (pexpect.EOF, pexpect.TIMEOUT):
        return False
    if i == 1:
        child.sendline(user_name)
        child.expect_exact('Password:')
        child.sendline(passw)
    else:
        child.sendline(passw)
        if child.expect_exact(['>', 'Wrong', pexpect.TIMEOUT], timeout=5):
            child.close()
            return False
        child.sendline('sup')
        i = child.expect_exact(['Password:', '>', 'Unknown', 'not set'])
        if i == 1:
            child.sendline('')
        elif i == 2 or i == 3:
            child.close()
            return False
        else:
            child.sendline(ena)
    if child.expect_exact(['>', 'Password', 'failed']):
        child.close()
    child.sendline('tftp %s put %s %s.backup.txt' % (TFTP, conf_name, name))
    child.expect_exact(['>', 'successfully'])
    if 'Unable' in child.before:
        .... 
        ....

编辑:为备份配置添加了部分示例(它是python 2.x和旧华为路由器)

答案 1 :(得分:0)

    if  w['router_type'] == "cisco":
        tn.read_until("Username:")
        tn.write(user.encode('ascii')+"\n"
            #tn.write(user +"\n")
        if password:
            tn.read_until("Password:")
            tn.write(password.encode("ascii") + "\n")(indent)
            tn.write("terminal length 0\n")
            tn.write("show version\n")
            tn.write("show running-config view full\n")
            tn.write("exit\n")
            tn_output = tn.read_all()
            print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
            flag = 1


    if  w['router_type'] == "huawei":
        tn.read_until("Username:")
        tn.write(user + "\n")
        if password:
            tn.read_until("Password:")
            tn.write(password + "\n")
            tn.write("screen-length 0 temporary\n")
            tn.write("dis version\n")
            tn.write("dis current-configuration\n")
            tn_output = tn.read_until("return")
            tn.write("quit\n")
            print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
            flag = 1


    if  w['router_type'] == "MAIPU":
        tn.read_until("login:")
        tn.write(user + "\n")
        if password:
            tn.read_until("password:")
            tn.write(password + "\n")           
            tn.write("more off\n")
            tn.write("show version\n")
            tn.write("show running\n")
            tn.write("logout\n")
            tn_output = tn.read_all()
            flag = 1
            print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
    print ("\n Count: " )+ str(v_count) + ("---\n")
    if flag:
        if v_count==0:
            saveoutput = open ("BACKUP/" + HOST + ".txt" , "w")
            saveoutput.write(tn_output)
            print ("Saving new file ") + HOST + ("......")
        elif v_count == 1:
            previous_file = open("BACKUP/" + HOST + ".txt")
            temp_file = previous_file.read()

            if str(temp_file) != str(tn_output):
            saveoutput = open ("BACKUP/" + HOST + "_v2.txt" , "w")
                saveoutput.write(tn_output)`enter code here`
                print ("Saving new file " )+ HOST + ("......")
        elif v_count > 1:
            previous_file = open("BACKUP/" + HOST + "_v" + str(v_count) + ".txt")
            temp_file = previous_file.read()

                if str(temp_file) != str(tn_output):
    saveoutput = open ("BACKUP/" + HOST + "_v" + str(v_count + 1)  + ".txt" , "w")
        print ("Saving new version of file ") + HOST + ("......")`enter code here`