Ping manipulation in Python

Asked

Viewed 4,804 times

1

I’m creating a code that pings a list of ips. I managed to make him drip and give me the answer, but I can’t make the condition that I want, which is:

SE ping ok:
   continuar os comandos
SENÃO:
   faz outra coisa.

I don’t know how to manipulate the ping response to put this logic in the code, can help me?

Sorry, I’m a beginner.

This is my code:

#coding: utf-8
import sys
import os
import platform
import subprocess
from ips_list import radius

plat = platform.system()
scriptDir = sys.path[0]
if plat == "Windows":
    for ip in radius:
        try:
            line = ip.strip()
            ping = subprocess.Popen(
                ["ping", "-n", "2", "-l", "1", "-w", "100", line],
                stdout = subprocess.PIPE,
                stderr = subprocess.PIPE
            )
        expect:


if plat == "Linux":
    for ip in radius:
        line = ip.strip( )
        ping = subprocess.Popen(
            ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1", line],
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE
        )
        out, error = ping.communicate()
        print out
        print error

How can I add this if logic.. I lse in it?

Thank you!

2 answers

2

Use this function, works on linux and windows, for python 2.7 or 3:

def ping(host):
    import os, platform

    if  platform.system().lower()=="windows":
        ping_str = "-n 1"
    else:
        ping_str = "-c 1"

    resposta = os.system("ping " + ping_str + " " + host)
    return resposta == 0

Function returns true if ping gets a response and false if it fails.

0

I did it this way, taking through a list of IPS and making an infinite loop to check each one:

# -*- coding: utf-8 -*-

import subprocess
import os
import time
ips = ['192.168.0.8','192.168.0.11','192.168.0.12','192.168.0.13','192.168.0.18']

while True:
    with open(os.devnull, "wb") as limbo:
        for ip in ips:

            result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
                    stdout=limbo, stderr=limbo).wait()
            if result:
                    print ip, "inativo"
            else:
                    print ip, "ativo"

    time.sleep(2)
    print(' -- recomeçar --')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.