The below code works perfectly if the input file ip_file.txt have the following format.
8.8.8.8
www.google.com
www.yahoo.com
www.microsoft.com
But how can I ping the IPs if the input is something like this and write the output same in format.
8.8.8.8, www.google.com
www.yahoo.com,www.microsoft.com
My code is given below:
import subprocess
import threading
import time
import re
timestr = time.strftime("%Y-%m-%d %H%M%S")
timesec = time.strftime("%Y-%m-%d%H:%M:%S")
raw_list = []
def ping(host):
results_file = open("results_bng_" str(timestr) ".txt", "a")
p = subprocess.Popen(["ping", host, "-n", "5"], shell=True, universal_newlines=True, stdout=subprocess.PIPE)
response = p.communicate()[0]
for i in response.split("\n"):
para =i.split("=")
# print(para)
try:
if para[0].strip() =="Minimum":
latency =para[3].strip()
print(latency)
latfin = re.findall('\d ', latency)
latfin1 = latfin[0]
except:
print("time run")
if "Received = 1" and "Approximate" in response:
print(f"UP {host} Ping Successful")
results_file.write(f"{host},UP,{latfin1},{timesec}" "\n")
else:
print(f"Down {host} Ping Unsuccessful")
results_file.write(f"{host},Down,0,{timesec}" "\n")
results_file.close()
with open(r'bng.txt', "r") as server_list_file:
hosts = server_list_file.read()
hosts_list =hosts.split('\n')
num_threads = 1
number = 0
while number< len(hosts_list):
# print(number)
for i in range(num_threads):
t = threading.Thread(target=ping, args=(hosts_list[number i],))
t.start()
t.join()
number = number 1
CodePudding user response:
Pings are specific IP packets that can only be sent to one ip at a time. There are special IP which are meant for broadcasting. For example, you could direct your ping at a specific subnet and the devices connected to that subnet could all choose to answer to a ping. Note that most routers or IP stacks do not answer to such broadcast pings nowadays as they could be used to discover the devices that are connected to the subnet.
CodePudding user response:
You could replace each newline
character with a comma
and split at each comma
:
bng.txt:
8.8.8.8, www.google.com
www.yahoo.com,www.microsoft.com
Code:
with open(r'bng.txt', "r") as server_list_file:
hosts = server_list_file.read()
hosts_list = hosts.replace('\n', ',').split(',')
for host in hosts_list:
print(host.strip()) # strip remaining whitespaces
Out:
8.8.8.8
www.google.com
www.yahoo.com
www.microsoft.com
CodePudding user response:
After you open your file you need to do a for loop and read each line at a time and split based on comma. That will ultimately give you a list of all single IPs / hosts to ping. Something like.
listOfAllIPs = []
for line in file:
x = line.split(',') ## this makes x a list
listOfAllIPs = listOfAllIPs x
After that runs you should be able to use listOfAllIPs as your input. It will have 1 IP or host per item. Just iterate through.