примечание перед запуском - Эта проблема отличается от: Объект 'NoneType' не имеет атрибута 'sendall' PYTHON IP-адреса удалены и заменены на xxxx
Похоже, что мой код отправляеттребуемая команда, но затем выдает ошибку с строкой «Nontype», как показано в моем отладочном выводе ниже: «используется строка 83 Попытка найти IP-адрес vlan 10
строка 85 Telnet (xxxx, 23): отправить b'showinterface vlan 10 \ n 'Объект' NoneType 'не имеет атрибута' sendall 'Ложный сценарий завершен'
Wireshark показывает, что соединение telnet сбрасывается при отправке этой команды. Я не вижу ничего в документации Telnetlib или что-либо в Google, которое похоже на проблему, с которой я сталкиваюсь: 56054 6494.389198219 xxxx xxxx TCP 56 51110 → 23 [RST, ACK] Seq = 86 Ack = 3288 Win = 63634Len = 0
У кого-нибудь была подобная проблема здесь? Я думал, может быть, мне придется попытаться сохранить сеанс, произвольно добавив команды записи / чтения, но это, похоже, не работает.
Спасибо!
Код, добавленный ниже:
#!/usr/bin/env python3
from time import sleep
import telnetlib
from getpass import getpass
# f is the .txt document that lists the IP's we'll be using.
f = open("devicess.txt")
#
username = input("please provide your username:")
sleep(.25)
password = getpass()
#
for line in f:
device = (line)
print('Starting to collect information, please wait')
#For those devices in the above list, connect and run the below commands
def loopstart():
for device in f:
tn = telnetlib.Telnet()
tn.open(device, 23, 60)
#Remove # in the line below for debug
tn.set_debuglevel(2000)
tn.read_until(b"Username:", timeout = 20)
sleep(.25)
tn.write(str(username + "\n").encode("ascii"))
sleep(.25)
tn.read_until(b"Password: ", timeout = 10)
sleep(.25)
tn.write((password + "\n").encode("ascii"))
sleep(.25)
#####################################
#Verify Login attempt below #
#####################################
try:
enablemode = tn.read_until(b"#")
if (b"FAIL") in enablemode:
print("Bad credentials to " + device)
tn.close()
sleep(.25)
elif (b"fail") in enablemode:
print("Bad credentials to " + device)
tn.close()
sleep(.25)
elif (b"#") in enablemode:
print("connection established to " + device)
try:
tn.write(str("show mac address-table | include 000c.\n").encode('ascii'))
sleep(1)
MH2 = tn.read_very_eager()
if (b"000c.15") in MH2:
print("possible Cyper power device identified")
try:
mactable = open("mactable.txt", "w+")
mactable.seek(0)
mactable.write(MH2.decode('utf-8'))
mactable.truncate()
mactable.seek(0)
Output1 = mactable.readlines()
for line in Output1:
line = line.strip()
CPMAC = line
print(CPMAC)
try:
sleep(.10)
if ("000c.15") in CPMAC:
vlan = (CPMAC[0:4])
print("line 83 in use")
print(type(vlan))
print("Attempting to find IP of vlan " + vlan)
print("line 85")
tn.write(("show interface vlan " + vlan + "\n").encode("ascii"))
print("line 87")
tn.read_until(b"Internet Address")
tn.close()
elif (str("All")) and (str("CPU")) in (CPMAC):
print ("CPU has matching MAC, checking rest of the output for this device")
tn.close()
else:
print("Moving to next device")
tn.close()
except EOFError as e:
print("could not pull vlan from output")
except EOFError as e:
print("unidentified issue")
#Execute the following commands in case of invalid command input
elif (b"Invalid") in MH2:
sleep(.5)
try:
tn.write(str("show mac-address-table | in 000c.\n").encode('ascii'))
sleep(2)
MH3 = tn.read_very_eager()
if (b"000c.15") in MH3:
print("Line 90 in use")
try:
sleep(.5)
mactable = open("mactable.txt", "rb+")
mactable.seek(0)
mactable.write(MH3)
Output2 = (bytes(mactable.read()))
print (type(Output2))
mactable.truncate()
for line in Output2():
CPMAC = line.decode
try:
if ("000c.15") in CPMAC:
print("line 114")
print(CPMAC + " this is what vlan the cyber power device should be on")
tn.write("show interface vlan" + (CPMAC[:6])+ "\n")
tn.read_until(b"Internet Address")
tn.close()
elif (str("All")) in (CPMAC):
print ("CPU has matching MAC, moving to next device")
tn.close()
else:
print("No Cyber power device found on " + device)
tn.close()
except EOFError as e:
print("could not pull vlan from output")
except EOFError as e:
print("unidentified issue")
elif (b"000c.15") not in MH3:
print ("Cyber power device not found, moving to next device.")
tn.close()
else:
print("Unknown Error")
tn.close()
##############################
# Logout commands #
##############################
except EOFError as e:
print("Connection closed to " + device)
else:
tn.write(str("exit\n").encode('ascii'))
tn.write(str("exit\n").encode('ascii'))
tn.close()
print(tn.read_all().decode('ascii'))
except EOFError as e:
print ("unknown error")
else:
tn.close()
except EOFError as e:
print("Connection closed to " + device)
except Exception as exception:
print('line 165 error')
print(exception, False)
tn.close()
loopstart()
print('script complete')
Редактировать: я добавил оператор печати в «исключение как исключение», которое показывает следующее при запуске. Неверный объект файла: False