繁体   English   中英

Python - 从文本中 Ping 多个 IP

[英]Python - Pinging multiple IPs from text

我是 Python 的新手,正在尝试制作脚本,但我有点迷路了。

我想检查 text1.txt 中的 IP 是否在 text2.txt 中。 如果不是,我想 ping 它们,如果 ping 正常,那么我想将它们添加到 text3.txt。 如果 ping 不正常,我想将它们添加到 text4.txt

我只做了这个.. 这告诉我他们是否可以被 ping 通。


#!/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)
       

它对我有用,至少 T_T。

你能建议我如何推进主要思想吗?

只是为我要求一些痕迹:)。

我想单独尝试,但我迷路了:-/。

谢谢你。

这是您的代码的更正版本。

您只需要打开文件一次

您需要以 append 模式打开目标文件,并使用与读取文件不同的名称

您需要实际写入 output 文件

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)

这是一个适合您的基本代码。
我希望它能解决你的问题。

#!/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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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