我无法确定代码中的确切问题。我有两个功能——inrange()
,检查端口是否在范围内,以及filt()
,它接受一个 txt 文件,查找关键字“UDP”或“TCP”,查看端口(紧接在 : 标记之后),并检查该数字是否在范围内。
def inrange(file,character, num):
with open(file, 'r') as r:
for lines in r:
for key, value in sshd.items():
if character == key and character in lines:
if num in sshd.get(character):
return True
else:
return False
elif character == key and character in lines:
if num in sshd.get(character):
return True
else:
return False
目前这是专门针对 sshd 的。
def filt(file):
with open(file, 'r') as r:
for i, line in enumerate(r):
if "sshd" in line:
plusOne = i + 1
newline = line.strip()
splitIt = newline[7:22]
my_string = splitIt.split(":", 1)[1]
if inrange(file, "TCP", int(my_string)):
print("Line " + str(plusOne) + " is in range" + " " + my_string)
elif inrange(file, "UDP", int(my_string)):
print("Line " + str(plusOne) + " is in range" + " " + my_string)
else:
print("Not in range")
现在,如果我将此作为我的文本文件,这就可以了-
活跃连接数
Proto Local Address Foreign Address State PID
UDP 0.0.0.0:123 0.0.0.0:0 LISTENING 5987 sshd
如您所见,如果您查看字典,则 UDP 123 在范围内sshd
多于。作为回报,我得到了真实的陈述。如果我将 UDP 更改为 TCP,它会返回一个否定语句。这样可行。当我向其中添加不止一行时,就会出现问题。
Active Connections
Proto Local Address Foreign Address State PID
UDP 0.0.0.0:123 0.0.0.0:0 LISTENING 5987 sshd
TCP 0.0.0.0:123 0.0.0.0:0 LISTENING 5987 sshd
UDP 0.0.0.0:123 0.0.0.0:0 LISTENING 5987 sshd
TCP 0.0.0.0:123 0.0.0.0:0 LISTENING 5987 sshd
我得到了所有积极的结果:
Line 5 is in range 123
Line 6 is in range 123
Line 7 is in range 123
Line 8 is in range 123
事实并非如此,因为第 6 行和第 8 行是端口 123 中的 TCP,该端口不在范围内。我觉得我在这里缺少一些明确的东西。想不通。