I have a small script that will check to see if a list of devices are either ssh or telnet enable. Here is my code:
import socket
import sys
file = open('list', 'r')
file = file.readlines()
list = []
for i in file:
i=i.replace('\n','')
list.append(i)
for i in list:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((i, 22))
s.shutdown(2)
s.close()
print (i+' SSH ')
except:
try:
s.connect((i, 23))
s.shutdown(2)
s.close()
print (i+' Telnet')
except:
print (i + 'disable')
pass
When I get an exception, I have to hit ctrl + c to go to the next device. What are am I doing wrong? Thanks
3 Answers 3
did you try adding a timeout?
import socket
import sys
with open('list', 'r') as f:# file is a global class
# per default it reads the file line by line,
# readlines() loads the whole file in memory at once, using more memory
# and you don't need the list.
for i in f:
i=i.replace('\n','')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
try:
s.connect((i, 22))
s.shutdown(2)
s.close()
print (i+' SSH ')
except:
try:
s.connect((i, 23))
s.shutdown(2)
s.close()
print (i+' Telnet')
except:
print (i + 'disable')
pass
setting up a time out closes the stream after a timeout, otherwise it blocks forever.
Comments
I cannot really run the code because I don't have the list file you open on my machine. Still made few edits, any difference?
import socket
import sys
file = open('list', 'r')
file = file.readlines()
list = []
for i in file:
i=i.replace('\n','')
list.append(i)
for i in list:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((i, 22))
s.shutdown(2)
s.close()
print (i+' SSH ')
except:
s.connect((i, 23))
s.shutdown(2)
s.close()
print (i+' Telnet')
else:
print (i + 'disable')
pass
Comments
Again I can't really run the code because of lack of the file 'list' (rather misleading..) but I've done some further refactoring and offered up a suggestion.
import socket
import sys
with open('list', 'r') as f:
# Don't call anything 'list' as it is the name for pythons inbuilt type
# Using `with` will automatically close the file after you've used it.
content = f.readlines()
# We can use a list comprehension to quickly strip any newline characters.
content = [x.replace('\n','') for x in content]
for x in content:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((x, 22))
s.shutdown(2)
s.close()
print (x+' SSH')
except:
# This should catch a specific exception, e.g. TimeoutError etc
# e.g. `except ConnectionError`
try:
s.connect((i, 23))
s.shutdown(2)
s.close()
print (i+' Telnet')
except:
print (i + 'disable')
pass
My guess is that the connection is hanging rather than hitting the exception. Maybe due to timeouts as it cannot connect.
Add a timeout option with:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(60)
except Exception as eand then figure out the type ofeby printingtype(e). Also try printing before each statement in yourtryblock so you know where you're getting stuck.nmap