Monday, April 21, 2025

Redirect Command Prompt Operation to .TXT File

import os

list_targets = ['localhost', 'yahoo.com', 'google.com']

file = open('bulk-report.txt', 'w')

for x in list_targets:
    response = os.popen('ping ' + x)

    for y in response.readlines():
        file.write(y)

file.close()
            

The code starts by importing the os module, which provides a way to interact with the operating system and run system commands. Then, a list called list_targets is created, which contains three target addresses: localhost, yahoo.com, and google.com.

import os list_targets = ['localhost', 'yahoo.com', 'google.com']

Next, the code creates a new file called bulk-report.txt in write mode using the open() function and assigns the file object to a variable called file.

file = open('bulk-report.txt', 'w')

A for loop is used to iterate over each target address in the list_targets. For each target address, the os.popen() function is called with the ping command and the target address as an argument. The os.popen() function runs the command and returns the output of the command as a file-like object.

for x in list_targets:
    response = os.popen('ping ' + x)

Inside the for loop, another for loop is used to iterate over each line of output from the ping command using the readlines() method. For each line, the code writes the line to the file object using the write() method.

for y in response.readlines():
        file.write(y)

Finally, after all the target addresses have been processed, the file object is closed using the close() method.

file.close()

This code can be used to automate pinging multiple hosts and save their output to a file, which can be useful for monitoring or troubleshooting network issues. However, it should be noted that the ping command may not work on all systems, and some firewalls or routers may block ICMP traffic.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...