txt文件中的python ping ip地址

kosta11

这些代码采用txt中的IP地址。当服务器在线时,写入新的txt文件。但是这段代码只写了txt文件中的最后一个文件,其他时间再也没有了。我需要帮助

吊车


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 ")

在此处输入图片说明

鲍德曼

您需要在附加模式下打开输出文件(IPsCheck.txt):“ a +”

有关更多信息,请参见此处https://www.guru99.com/reading-and-writing-files-in-python.html#2

下面的代码似乎有效。如果要从ips文件读取ips,请将DEBUG更改为False。

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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章