我有一个小脚本,它将检查设备列表是否启用了ssh或telnet。下面是我的代码:
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当我得到一个异常,我必须按下ctrl +c转到下一个设备。我做错了什么?谢谢
发布于 2013-06-14 01:39:38
您是否尝试添加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设置超时将在超时后关闭流,否则它将永远阻塞。
发布于 2013-06-14 01:17:05
我不能真正运行代码,因为我的机器上没有您打开的list文件。还是做了很少的编辑,有什么区别吗?
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发布于 2013-06-14 01:45:54
再说一次,我不能真正运行代码,因为缺少文件'list‘(相当误导..)但我已经做了一些进一步的重构,并提供了一个建议。
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我的猜测是连接挂起了,而不是遇到了异常。可能是因为超时,因为它无法连接。
使用以下命令添加超时选项:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(60)https://stackoverflow.com/questions/17093032
复制相似问题