lundi 4 juillet 2016

Python 3 - filtering/piping and redirecting the output of a function Windows

ipl = socket.gethostbyname(socket.gethostname())
seg1,seg2,seg3,seg4=ipl.split(".")
ip2 = seg1+"."+seg2+"."+seg3+"."
ip3 = seg1+"."+seg2+"."+seg3+"."

def ipar(ip2):
    seg4=0
    n=5
    while n > seg4:
        seg4=seg4+1
        ip2 += str(seg4)
        os.system("ping -n 1 "+ip2)
        ip2 = ip3

I want to filter the results of the code just printing successful ping attempts similary to AWK , sed in linux

I changed the code a bit , the last for loop stops on the first variable how i changed it ? there another way to do this task better ?

import subprocess
import socket
import sys

ipl = socket.gethostbyname(socket.gethostname())
seg1, seg2, seg3, seg4 = ipl.split(".")
stip = seg1 + "." + seg2 + "." + seg3 + "."

i = 0


def ppout(cmd: str) -> str:
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    while True:
        out = p.stdout.read(1)
        if out == '' and p.poll() != None:
            break
        if out != '':
            sys.stdout.write(out.decode('utf-8'))
            sys.stdout.flush()

for i in range(1, 3):
    cmd = "ping -n 1 " + stip + str(i)
    print(i)
    ppout(cmd)

Aucun commentaire:

Enregistrer un commentaire