Проблемы с использованием telnet в функции, вызывающие проблемы масштабирования кода python - PullRequest
0 голосов
/ 21 сентября 2019

Итак, у меня возникли некоторые проблемы с масштабированием кода в моем скрипте VLAN.

В основном у меня есть функция addvlanfunc (), которая будет:

1.telnet в коммутатор 2.создать vlan3. выйти из сеанса telnet. 4. закрыть сеанс telnet. 5. Этот процесс повторяется на всех коммутаторах. 6. Цикл for заставляет его повторяться до тех пор, пока все VLANS не будут настроены

Все работает правильно, но я вижу некоторое масштабированиевопросы.Поэтому я хотел бы добавить в свой код другую функцию, которая бы принимала команды, которые запускаются на переключателях, которые никогда не меняются, и помещала их в однострочную функцию vlancmd () для вызова addvlanfunc ().

Однако, когда я делаю это, я могу добавить только первую VLAN в моем списке к первому коммутатору, и мой код выдает ошибку с сообщением о закрытии telnet.вся ошибка приведена ниже, далее - рабочий код, а после - неработающий код.Я думаю, я хочу знать, что я ломаю, когда я пытаюсь использовать эту новую функцию.Я ценю любое понимание, которое может быть дано мне!(моя трассировка может быть немного отключена, я изменил некоторые значения переменных, чтобы защитить невинных)

Traceback (most recent call last):
  File "WF-VLAN-AUTO-FOR-FUNC-TEST", line 70, in <module>
    addvlanfunc()
  File "WF-VLAN-AUTO-FOR-FUNC-TEST", line 27, in addvlanfunc
    vlancmd()
  File "WF-VLAN-AUTO-FOR-FUNC-TEST", line 9, in vlancmd
    tn.read_until(b"Username: ")
  File "C:\Users\scott\AppData\Local\Programs\Python\Python37-32\lib\telnetlib.py", line 327, in read_until
    return self.read_very_lazy()
  File "C:\Users\scott\AppData\Local\Programs\Python\Python37-32\lib\telnetlib.py", line 403, in read_very_lazy
    raise EOFError('telnet connection closed')
EOFError: telnet connection closed

#GOOD CODE BELOW

import getpass
import sys
import telnetlib

# Defines a function that will add vlans to catalyst switches

def addvlanfunc():
    tn = telnetlib.Telnet(HOST)
    tn.read_until(b"Username: ")
    tn.write(teluser.encode('ascii') + b"\n")
    if telpassword:
        tn.read_until(b"Password: ")
        tn.write(telpassword.encode('ascii') + b"\n")
        tn.write(b"enable\n")
        tn.write(enpassword.encode('ascii') + b"\n")
        tn.write(b"conf t\n")
        tn.write(b"vlan " + vlans.encode('ascii') + b"\n")
        tn.write(b"end\n")
        tn.write(b"exit\n")
        print(tn.read_all().decode('ascii'))
        tn.close()
        tn = telnetlib.Telnet(HOST1)
        tn.read_until(b"Username: ")
        tn.write(teluser.encode('ascii') + b"\n")
        if telpassword:
            tn.read_until(b"Password: ")
            tn.write(telpassword.encode('ascii') + b"\n")
            tn.write(b"enable\n")
            tn.write(enpassword.encode('ascii') + b"\n")
            tn.write(b"conf t\n")
            tn.write(b"vlan " + vlans.encode('ascii') + b"\n")
            tn.write(b"end\n")
            tn.write(b"exit\n")
            print(tn.read_all().decode('ascii'))
            tn.close()

# Defines a function that will remove a vlan on a catalyst switch
def rmvvlanfunc():
    tn.read_until(b"Username: ")
    tn.write(teluser.encode('ascii') + b"\n")
    if telpassword:
        tn.read_until(b"Password: ")
        tn.write(telpassword.encode('ascii') + b"\n")
        tn.write(b"enable\n")
        tn.write(enpassword.encode('ascii') + b"\n")
        tn.write(b"conf t\n")
        tn.write(b"no vlan " + vlantoremove.encode('ascii') + b"\n")
        tn.write(b"end\n")
        tn.write(b"exit\n")
        print(tn.read_all().decode('ascii'))



HOST = "x.x.x.x"
HOST1 = "y.y.y.y"
teluser = "username"
telpassword = "telpassword"
enpassword = "enpassword"
tn = telnetlib.Telnet(HOST)
# Host variables define a switch that will be configured
# teluser and password are the credentals that will be used to telnet into switch
# enable password will allow user to configure switch
# tn = telnetlib.Telnet(HOST) this variable needs changed everytime we need to run the function on the next switch



print("WELCOME TO WF VLAN AUTOMATION")
print("0.Exit")
print("1.Create a VLAN")
print("2.Remove a VLAN")
userchoice = input("Please make a choice: ")
# Core of script is in the if, elif, and else statements
# user choice will allow functions to be ran on switches and easy input validation

if userchoice == "0":
    exit()

elif userchoice == "1":
    vlantoadd = input("Please enter VLANS: ").split()
    for vlans in vlantoadd:
        addvlanfunc()



else:
    exit()


#BAD CODE BELOW

import getpass
import sys
import telnetlib


# Defines a function that will add vlans to catalyst switches

def vlancmd():
    tn.read_until(b"Username: ")
    tn.write(teluser.encode('ascii') + b"\n")
    if telpassword:
        tn.read_until(b"Password: ")
        tn.write(telpassword.encode('ascii') + b"\n")
        tn.write(b"enable\n")
        tn.write(enpassword.encode('ascii') + b"\n")
        tn.write(b"conf t\n")
        tn.write(b"vlan " + vlans.encode('ascii') + b"\n")
        tn.write(b"end\n")
        tn.write(b"exit\n")
        print(tn.read_all().decode('ascii'))

def addvlanfunc():
    tn = telnetlib.Telnet(HOST)
    vlancmd()
    tn.close()
    tn = telnetlib.Telnet(HOST1)
    vlancmd()
    tn.close()

# Defines a function that will remove a vlan on a catalyst switch
def rmvvlanfunc():
    tn.read_until(b"Username: ")
    tn.write(teluser.encode('ascii') + b"\n")
    if telpassword:
        tn.read_until(b"Password: ")
        tn.write(telpassword.encode('ascii') + b"\n")
        tn.write(b"enable\n")
        tn.write(enpassword.encode('ascii') + b"\n")
        tn.write(b"conf t\n")
        tn.write(b"no vlan " + vlantoremove.encode('ascii') + b"\n")
        tn.write(b"end\n")
        tn.write(b"exit\n")
        print(tn.read_all().decode('ascii'))

HOST = "x.x.x.x"
HOST1 = "y.y.y.y"
teluser = "teluser"
telpassword = "telpassword"
enpassword = "enpassword"
tn = telnetlib.Telnet(HOST)
# Host variables define a switch that will be configured
# teluser and password are the credentals that will be used to telnet into switch
# enable password will allow user to configure switch
# tn = telnetlib.Telnet(HOST) this variable needs changed everytime we need to run the function on the next switch

print("WELCOME TO WF VLAN AUTOMATION")
print("0.Exit")
print("1.Create a VLAN")
print("2.Remove a VLAN")
userchoice = input("Please make a choice: ")
# Core of script is in the if, elif, and else statements
# user choice will allow functions to be ran on switches and easy input validation

if userchoice == "0":
    exit()

elif userchoice == "1":
    vlantoadd = input("Please enter VLANS: ").split()
    for vlans in vlantoadd:
        addvlanfunc()

else:
    exit()
...