python端口扫描器遇到的线程问题和KeyError
在写python端口扫描器,想把结果以html格式发送到邮箱,提取函数结果这一块参考了知乎的一个回答写的:
附上自己的代码:
import nmap
from optparse import OptionParser
from threading import Thread
def getaddresslist(addr):
""" getaddresslist(addr) -> IP address file
IP address read from the file.
"""
try:
with open(addr, 'r') as tgthosts:
lines = tgthosts.readlines()
address = [line.strip() for line in lines]
return address
except (IOError, IndexError) as e:
return str(e)
class CustomTask:
def __init__(self): self._result = None
def nmScan(self, tgthost, tgtport):
whitelist = []
result = ''
nmscan = nmap.PortScanner()
tmp = nmscan.scan(tgthost, tgtport)
result = result + "<h2>ip地址:%s ...... %s</h2><hr>" % (tgthost, tmp['scan'][tgthost]['status']['state'])
try:
ports = tmp['scan'][tgthost]['tcp'].keys()
for port in ports:
if port not in whitelist:
info = '<span><font color=red>Alert:非预期端口</font></span> '
else:
info = '<span><font color=green>Info:正常开放端口</font></span> '
portinfo = "%s <span>port</span> : %s <span>state</span> : %s <span>product</span> : %s <br>" % (info, port, tmp['scan'][tgthost]['tcp'][port]['state'], tmp['scan'][tgthost]['tcp'][port]['product'])
result = result + portinfo
except KeyError as e:
if whitelist:
whitestr = ','.join(whitelist)
result = result + "未扫到开放端口!请检查%s端口对应的服务状态" % whitestr
else:
result = result + "扫描结果正常,无暴露端口"
print(result)
self._result = result
def get_result(self):
return self._result
def main():
f1 = open('D:\python_work/iplist.txt', 'ab')parser = OptionParser()
parser.add_option('-H', dest='tgthost', type='string', help='specify target host')
parser.add_option('-f', dest='file', default='', help='host list', metavar='LIST')
(options, args) = parser.parse_args()
tgthost = options.tgthost
tgtports = [20, 21, 22, 23, 25, 69, 80, 109, 110, 139, 179, 443, 445, 544, 1080, 1433, 1434, 1521, 1158, 2100,3306, 3389, 7001, 8080, 8081, 9080, 9090]
if options.file == '':
for tgtport in tgtports:
ct = CustomTask()
t = Thread(target=ct.nmScan, args=(str(tgthost), str(tgtport)))
t.start()
# result = ct.get_result()
# tool.sendemail(result)
else:
f = open(options.file, 'r')
current_host = f.readline().strip()
while (current_host):
for tgtport in tgtports:
ct = CustomTask()
t = Thread(target=ct.nmScan, args=(str(tgthost), str(tgtport)))
t.start()
current_host = f.readline().strip()
# result = ct.get_result()
f.close()
# tool.sendemail(result)
f1.close()
if name == '__main__':
main()
在运行时出现了这样的错误提示,基本每个错误类型都是一样的,请各位大佬指教应该如何修改!
回答:
很明显运行到那句的时候tgthost
为None
,
也就是 t = Thread(target=ct.nmScan, args=(str(tgthost), str(tgtport)))
这一句运行的时候,有些tgthost
转换为str
后为None,
可以在这里做些文章。
回答:
多谢楼上大佬的提醒传入值为空,是自己粗心把参数名字写错了,在传文件的时候的Ip参数应该是 current_host 而不是 tgthost。
以上是 python端口扫描器遇到的线程问题和KeyError 的全部内容, 来源链接: utcz.com/a/161714.html