Jump to content

Recommended Posts

Posted

Boas,

Estava a fazer uma função para pingar um host então o que acontece:
 

def pingx(myip):

    checkState = os.system("ping -n 1 %s" % myip)

    if checkState == 0:
        return 1
    else:
        return 0

O que me está a contecer é que se a máquina estiver up, ele devolve 0 e se estiver down devolve o 1 quando precisamente era o contrario. A pergunta é, como e que sei o que ele guarda na variável após efectuar o comando do ping -n 1..... na consola windows se tiver on ele devolve um reply se tiver off e um timeout. Como e que ele traduz o ping. 

Posted

Astuto,

Isso deve-se ao facto de estares a utilizar ferramentas do sistema para fazer o ping. Em linux o habitual é devolver 0 quando tudo está bem e outro número quando algo correu mal, servindo o número para identificar o tipo de erro. Possivelmente a implementação em Windows poderá ser diferente, daí o teu problema.

Podes sempre detectar a plataforma no teu código e interpretar os resultados consoante a mesma.

  • Vote 1
  • 2 weeks later...
Posted

Testei no Windows e funcionou normalmente.

Você pode testar na linha de comando e pedir para exibir o valor de retorno com:

echo %ERRORLEVEL%

Quando a máquina está ativa, retorna 0

Quando a máquina não responde, retorna 1.

Testado no Windows 10 com Python 3.5.1:

C:\Users\Utilisateur>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> def pingx(myip):
...     checkState = os.system("ping -n 1 %s" % myip)
...     if checkState == 0:
...         return 1
...     else:
...         return 0
...
>>> print(pingx("www.google.com"))

Pinging www.google.com [2a00:1450:400e:805::2004] with 32 bytes of data:
Reply from 2a00:1450:400e:805::2004: time=28ms

Ping statistics for 2a00:1450:400e:805::2004:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 28ms, Maximum = 28ms, Average = 28ms
1
>>> print(pingx("wxxxww.google.com"))
Ping request could not find host wxxxww.google.com. Please check the name and tr
y again.
0

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.