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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Protected by WP Anti Spam