i am new to Python and trying to make a script but i am kind of lost.
I would like to check if IPs from text1.txt are in text2.txt. If not i want to ping them and if ping is ok then i would like to add them to text3.txt. If ping is not ok i want to add them to text4.txt
I only did this .. that tells me if they can be pinged.
#!/usr/bin/env python
import os
file = open("input.txt","r ")
with open("input.txt","r") as file:
for line in file:
response = os.system("ping -c 1 " line)
if response == 0:
with open("output.txt","w") as file:
print(line)
It works for me with pinging, atleast T_T .
Can you suggest me how to proceed with the main idea?
Just asking for some traces for me :).
I want to try it alone but iam lost :-/.
Thank you.
CodePudding user response:
Here's the corrected version of your code.
You only need to open the file once
You need to open the destination file in append mode an with another name than the reading one
You neeed to actually write into the output file
import os
with open("input.txt", "r") as file:
for line in file:
response = os.system("ping -c 1 " line)
if response == 0:
with open("output.txt", "a") as out:
out.write(line)
CodePudding user response:
Here is a basic code which will work for you.
I hope it solves your problem.
#!/usr/bin/env python
import os
# Creat a empty list to get contents of text2.txt
lines = []
# Load contents of text2 file in the list for comparison. (Not memory-efficient)
with open("/path/to/text2.txt") as file:
lines = [line.strip() for line in file]
# Ping each IP from input file (text1)
with open("/path/to/text1.txt","r") as input_file:
for line in input_file:
if line not in lines:
response = os.system("ping -c 1 " line)
if response == 0:
with open("/path/to/text3.txt", mode='a') as out_file:
out_file.write(line)
else:
with open("/path/to/text4.txt", mode='a') as out_file:
out_file.write(line)