[英]How to read list of ip address from a text file and print it out
*我想從文本文件中打印出ip地址(已解決)
****文本文件中沒有ip地址,將顯示錯誤信息。** (已解決)
我在底部附上了我當前的代碼,有人可以幫忙嗎?**
** ****文本文件中的 IP 地址將如下所示。**** **
192.168.12.1
192.168.12.28
*****以下是我目前的代碼... *****
f=open('output.txt','r')
print "IP address is ", f.read()
f.close()
在循環內使用file.readlines()
。
因此,代碼將是:
f=open('output2.txt','r')
c=f.readlines()
for i in c :
print ("IP address of attacker is ", i)
f.close()
從文本文件中獲取 IP 地址並檢查。 在 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
您必須在每個換行符處拆分文件的內容。
最好使用“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'
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.