如何将PING结果写入/附加到输出文件

时间:2018-01-24 18:41:21

标签: python python-3.x output ping

相当新的Python,请原谅基本问题和重复编码。我正在尝试编写一个PING网段的脚本,然后将结果写入几个TXT文件。

我的PING扫描部分工作得很好,我在网上找到了一些代码,但是无法将结果保存到文件中。文件已创建,但它们是空白的。

有人可以检查一下并给我一些建议吗?

import os
import os.path
import sys
import subprocess
import ipaddress

# Prompt the user to input a network address
network = input("Enter a network address in CIDR format(ex.192.168.1.0/24): ")

# Create the network
ip_net = ipaddress.ip_network(network)

# Get all hosts on that network
all_hosts = list(ip_net.hosts())

# Create output file in preset directory
os.chdir("C:\\Python364\\Output")
onlineHosts = "Online_Hosts.txt"
offlineHosts = "Offline_Hosts.txt"
on  = open(onlineHosts, 'a') # File object 'on' is created with append mode
off = open(offlineHosts, 'a') # File object 'off' is created with append mode

# Configure subprocess to hide the console window
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE

# For each IP address in the subnet, 
# run the ping command with subprocess.popen interface
for i in range(len(all_hosts)):
    output = subprocess.Popen(['ping', '-n', '1', '-w', '500', str(all_hosts[i])], stdout=subprocess.PIPE, startupinfo=info).communicate()[0]

    if "Destination host unreachable" in output.decode('utf-8'):
        print(str(all_hosts[i]), "is Offline")
        result = str(all_hosts[i])
        off.write(result)

    elif "Request timed out" in output.decode('utf-8'):
        print(str(all_hosts[i]), "is Offline")
        result = str(all_hosts[i])
        off.write(result)
    else:
        print(str(all_hosts[i]), "is Online")
        result = str(all_hosts[i])
        on.write(result

2 个答案:

答案 0 :(得分:0)

确保在完成文件后关闭文件。写作可能会留在缓冲区中,直到你这样做。

on.close()

off.close()

要立即写入而不关闭,您可以刷新缓冲区:

on.flush()

off.flush()

答案 1 :(得分:0)

如果只想使用外壳,我发现以下对解决此问题很有帮助:https://ss64.com/nt/type.html

要将ping结果写入输出文件,请输入:

ping -t "SomeIPAddress" > newfile.txt

要将ping结果附加到现有输出文件中,请输入:

ping -t "some IP address" >> existingfile.txt

如果您还想在ping结果上添加时间戳,则可以在Powershell中键入以下内容:

ping -t "SomeIPAddress"|Foreach{"{0} - {1}" -f (Get-Date),$_} > > newfile.txt

来源:https://support.solarwinds.com/SuccessCenter/s/article/Ping-Test-and-save-to-text-file?language=en_US