Архив метки: timeout

Python ping

Модуль называется ping3

Установка модуля ping3:

$ python3 -m pip install ping3
Collecting ping3
  Downloading ping3-3.0.2-py3-none-any.whl (12 kB)
Installing collected packages: ping3
Successfully installed ping3-3.0.2

Как пользоваться:

>>> ping("192.168.1.1")
0.00391697883605957

Как пропинговать подсеть:

>>> for i in range(1, 5):
...   ip = f"192.168.1.{i}"
...   for j in range(3):
...     print(f"{ip}: {ping(ip)}")
... 
192.168.1.1: None
192.168.1.1: 0.11145853996276855
192.168.1.1: 0.008517742156982422
192.168.1.2: None
192.168.1.2: None
192.168.1.2: None
192.168.1.3: None
192.168.1.3: 0.6436576843261719
192.168.1.3: 0.004034757614135742
192.168.1.4: 0.00033211708068847656
192.168.1.4: 0.00026726722717285156
192.168.1.4: 0.00026297569274902344
192.168.1.5: None
192.168.1.5: None
192.168.1.5: None

Как указать таймаут:

>>> ping("habr.com", timeout=5)
>>> ping("habr.com", timeout=1)
>>> ping("ya.ru", timeout=1)
0.035222530364990234
>>>

Ещё несколько примеров из документации:

pip install ping3  # install ping

>>> from ping3 import ping, verbose_ping
>>> ping('example.com')  # Returns delay in seconds.
0.215697261510079666

>>> verbose_ping('example.com')  # Ping 4 times in a row.
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
ping 'example.com' ... 219ms
ping 'example.com' ... 217ms

$ ping3 example.com  # Verbose ping.
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
ping 'example.com' ... 219ms
ping 'example.com' ... 217ms

Installation

pip install ping3  # install ping3
pip install --upgrade ping3 # upgrade ping3
pip uninstall ping3  # uninstall ping3

Functions

>>> from ping3 import ping, verbose_ping

>>> ping('example.com')  # Returns delay in seconds.
0.215697261510079666

>>> ping('not.exist.com')  # If host unknown (cannot resolve), returns False.
False

>>> ping("224.0.0.0")  # If timed out (no reply), returns None.
None

>>> ping('example.com', timeout=10)  # Set timeout to 10 seconds. Default timeout is 4 for 4 seconds.
0.215697261510079666

>>> ping('example.com', unit='ms')  # Returns delay in milliseconds. Default unit is 's' for seconds.
215.9627876281738

>>> ping('example.com', src_addr='192.168.1.15')  # Set source ip address for multiple interfaces. Default src_addr is None for no binding.
0.215697261510079666

>>> ping('example.com', interface='eth0')  # LINUX ONLY. Set source interface for multiple network interfaces. Default interface is None for no binding.
0.215697261510079666

>>> ping('example.com', ttl=5)  # Set packet Time-To-Live to 5. The packet is discarded if it does not reach the target host after 5 jumps. Default ttl is 64.
None

>>> ping('example.com', size=56)  # Set ICMP packet payload to 56 bytes. The total ICMP packet size is 8 (header) + 56 (payload) = 64 bytes. Default size is 56.
0.215697261510079666

python перехват вывода внешней программы

>>> from subprocess import check_output
>>> out = check_output(["ping", "-c3", "8.8.8.8"])
>>> out
b'PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n64 bytes from 8.8.8.8: icmp_seq=1 ttl=108 time=152 ms\n64 bytes from 8.8.8.8: icmp_seq=2 ttl=108 time=151 ms\n64 bytes from 8.8.8.8: icmp_seq=3 ttl=108 time=46.9 ms\n\n--- 8.8.8.8 ping statistics ---\n3 packets transmitted, 3 received, 0% packet loss, time 2004ms\nrtt min/avg/max/mdev = 46.872/116.565/152.004/49.283 ms\n'
>>>

Способ работает только если вызванная программа завершилась без ошибок. Если хотим предусмотреть ошибки:

import subprocess as sp

# ok
pipe = sp.Popen( 'ls /bin', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])
for line in res[0].decode(encoding='utf-8').split('\n'):
  print(line)

# with error
pipe = sp.Popen( 'ls /bing', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])


proc = subprocess.Popen(["notepad.exe",],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()