*我想从文本文件(已解决)
打印出ip地址****文本文件中没有IP地址,将显示错误消息。** (已解决)
我已将当前的代码附在底部,任何人都可以帮忙吗?**
** ****文本文件中的IP地址将如下所示。**** **
Organization
*****以下是我目前的代码...... *****
192.168.12.1
192.168.12.28
答案 0 :(得分:1)
在循环中使用file.readlines()
。
因此,守则将是:
f=open('output2.txt','r')
c=f.readlines()
for i in c :
print ("IP address of attacker is ", i)
f.close()
答案 1 :(得分:1)
从文本文件中获取IP地址并进行检查。 See my code on git.
import socket
import re
f = open('ip_list.txt', 'r') #Text file with many ip address
o = f.read()
ip1 = re.findall( r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", o )
hosts = ip1
ports = [80]
for host in hosts:
for port in ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
result = s.connect_ex((host, port))
if result == 0:
print(" [*] Port " + str(port) + " open!" + host)
else: print("[+] CLOSE HOST " + host + ":" + str(port))
except:
pass
答案 2 :(得分:0)
import sys
import os
import time
b='sudo tshark -i ens33 -Y "tcp contains "attack"" -T fields -e ip.src -a duration:20>output2.txt'
a=os.popen(b)
time.sleep(22)
with open(output2.txt,"r") as f:
ip=f.read.split('\n')
for Ip in ip:
print "IP address of attacker is ", Ip
您必须在每个换行符处拆分文件内容。
答案 3 :(得分:0)
最好使用'with'在自己的上下文中打开文件。这样,它将在到达最后一行后自动关闭。然后循环通过线条并在每行之前添加文本。此解决方案的另一个好处是您不必将所有IP保留在内存中。 IP将一次一个地流式传输。
如果没有找到ip,此代码也会打印一条消息。
with open('output2.txt','r') as f:
ip_not_found = True
for line in f:
ip_not_found = False
print "IP address of attacker is {IP}".format(IP=line)
if ip_not_found:
print 'no ip address was found'
答案 4 :(得分:0)
import ipaddress
ip_address_file = open('ip.txt', 'r') # open text file with ip addresses
for i in ip_address_file: # loop through the ip text file
i = i.strip() # read each line
try:
i = ipaddress.ip_address(str(i)) #validates either ip is ipv4 or 6
except ValueError: #catch error for invalid ip format
print('invalid ip '.format(i))
continue # if line empty continue with loop