-3

I am working with this python script. I want it to dump all hosts which are alive into a text file and discard all hosts which don't respond to the ping. Currently I have this part.

#!/usr/bin/python2
import subprocess
import sys

ip = "10.11.1."

for sub in range (0,255):
    sweep = subprocess.Popen("ping -c 1 "+ ip+str(sub), shell=True, 
    stderr=subprocess.PIPE)
    out = sweep.stderr.read(1)
    sys.stdout.write(out)

How would I add the part dumping relevant information into a .txt file?

Tadas Melnikas
  • 87
  • 2
  • 3
  • 12

2 Answers2

0

Saving content to a file 101:

with open(<path>, 'w') as f:
    f.write(<content>)

Note: the second argument in open denotes that we open the file to write. If you want to append the file you would have to use the mode 'a'.

meissner_
  • 556
  • 6
  • 10
0

Are you asking how to send output to a file?

with open('myfile.txt', 'w') as outfile:
    for sub in range (0,255):
        sweep = subprocess.Popen("ping -c 1 "+ ip+str(sub), shell=True, 
                                 stderr=subprocess.PIPE)
        outfile.write(sweep.stderr.read(1))
E.Serra
  • 1,495
  • 11
  • 14
  • This is producing the error: Traceback (most recent call last): File "pingsweep.py", line 12, in outfile.write(sweep.stderr.read(1)) IOError: File not open for writing – Tadas Melnikas Aug 21 '18 at 14:49
  • you didn't open it for writting, did you put the 'w' thing ? – E.Serra Aug 21 '18 at 14:50
  • I put 'w'. I did run it again and now it works, but writes nothing into a file. – Tadas Melnikas Aug 21 '18 at 15:09
  • Hahaha change 'myfile.txt' for an absolute path to the file you want to run, I think python chooses current working directory as your base directory. In essence myfile.txt --> /home/you// – E.Serra Aug 21 '18 at 15:15