[英]How to read list of ip address from a text file and print it out
*I want to print out ip addresses from textfile (solved) *我想从文本文件中打印出ip地址(已解决)
****no ip address in the textfile and error message will be shown.** (solved) ****文本文件中没有ip地址,将显示错误信息。** (已解决)
I have attached my current codes at the bottom, can any one please help?**我在底部附上了我当前的代码,有人可以帮忙吗?**
** ****IP addresses in the textfile will look like this.**** ** ** ****文本文件中的 IP 地址将如下所示。**** **
192.168.12.1
192.168.12.28
*****And the following is my current codes...***** *****以下是我目前的代码... *****
f=open('output.txt','r')
print "IP address is ", f.read()
f.close()
Use file.readlines()
inside a loop.在循环内使用file.readlines()
。
So, the Code will be:因此,代码将是:
f=open('output2.txt','r')
c=f.readlines()
for i in c :
print ("IP address of attacker is ", i)
f.close()
Get IP address from text file and check.从文本文件中获取 IP 地址并检查。 See my code on git. 在 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
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
You have to just split the contents of the file at every newline.您必须在每个换行符处拆分文件的内容。
It is best to open the file in its own context with 'with'.最好使用“with”在其自己的上下文中打开文件。 This way it will be closed automatically after the last line has been reached.这样它会在到达最后一行后自动关闭。 Then loop trough the lines and add your text before each line.然后循环遍历这些行并在每行之前添加您的文本。 Another upside of this solution is that you do not have to keep all IPs in memory.此解决方案的另一个优点是您不必将所有 IP 都保存在内存中。 The IPs will be streamed one at a time. IP 将一次流式传输一个。
This code will also print a message if no ip was found.如果未找到 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'
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.