【问题标题】:python ping ip adress from txt filepython 从文本文件中ping ip地址
【发布时间】:2019-03-07 10:51:17
【问题描述】:

trhe 代码从 txt 中获取 IP 地址。当服务器在线时写入新的txt文件。但是这段代码只写了txt文件中的最后一个文件。而且永远不会有时间进入else。我需要帮助

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

【问题讨论】:

    标签: python operating-system ping


    【解决方案1】:

    需要以追加模式打开输出文件(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))
    

    【讨论】:

    • 谢谢伙计。那行得通,但它永远不会在其他地方。这在txt中写入所有IP
    • 耶哈。例如,其中一个 ips 不可用,但它永远不会在 else 中打印不可用。你明白我的意思吗?
    • 是的 - 我明白了。试试我发布的代码。这是您代码的“更清洁”版本。您仍然面临问题吗?
    猜你喜欢
    • 1970-01-01
    • 2020-02-13
    • 2023-01-25
    • 2016-12-10
    • 2014-12-09
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多