简体   繁体   中英

python ping ip adress from txt file

trhe code take the ip adress from txt. when the server is online write in the new txt file. But this code write only the last file in the txt file.And never time goes in the else. I need help

tahnks


import os


file = open("IPs.txt","r+")

with open("IPs.txt","r") as file:

  for line in file:
     response =  os.system("ping   " + line)

     if response == 0:
        with open("IPsCheck.txt","w") as file:
            print(line)
            file.write(line)




     else:
        print("server not available ")

在此处输入图片说明

You need to open the output file (IPsCheck.txt) in append mode: "a+"

See here for more https://www.guru99.com/reading-and-writing-files-in-python.html#2

The code below seems to work. Change the DEBUG to False if you want to read the ips from the ips file.

import os

DEBUG = True

DEBUG_IPS = ['1.1.1.1', '8.8.8.8']

if DEBUG:
    ips = DEBUG_IPS
else:
    with open("IPs.txt", "r+") as ips_file:
        ips = [ip.strip() for ip in ips_file.readlines()]

with open("IPsCheck.txt", "w") as available_ips_file:
    for ip in ips:
        response = os.system('ping {}'.format(ip))
        if response == 0:
            available_ips_file.write(ip)
        else:
            print('server {} not available'.format(ip))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM