Explain Codes LogoExplain Codes Logo

Pinging servers in Python

python
network-diagnostics
error-handling
concurrency
Nikita BarsukovbyNikita Barsukov·Dec 7, 2024
TLDR

Ping servers in Python by utilising the subprocess module. It enables the use of the ping command via subprocess.run() to inspect server availability.

Quick snippet to ping 'example.com':

import subprocess def ping(host): response = subprocess.run(['ping', '-c', '1', host], stdout=subprocess.PIPE) return 'Success!' if response.returncode == 0 else 'Failed!' print(ping('example.com')) # Bash the keyboard if 'Failed'!

This triggers a single ICMP packet ('-c', '1') ping to 'example.com' and prints the result. Swap 'example.com' with your desired server address.

Adapting to operating systems

Knowing the operating system is crucial for generating the appropriate ping command. Use platform.system() to adjust the ping request accordingly:

import platform import subprocess # For those unfortunate Windows users def ping(host): param = '-n' if platform.system().lower() == 'windows' else '-c' command = ['ping', param, '1', host] return subprocess.run(command, stdout=subprocess.PIPE).returncode == 0 print("Knock, knock.") if ping('example.com'): print('Who is there? Server!') else: print('Nobody...') # Time to call in an exorcist.

Advanced pinging and error handling

For more advanced uses, consider packages like ping3 or pythonping. They cover more intricate situations and provide detailed feedback:

from ping3 import ping, verbose_ping verbose_ping('example.com') # Verbose, like my mother-in-law.

Using ping3, there are no system calls, and it caters to both IPv4 and IPv6 networks.

Handle possible errors such as network delays and packet loss, by using timeouts:

try: delay = ping('example.com', timeout=2) # Wait, but not too long. Just like my dog. except OSError as e: print(f'Ping hiccup: {e}') # It wasn't me, it was the network!

Tool selection and root access

Selecting between os.system, subprocess, or third-party libraries is a matter of simplicity, control, or extended features:

  • os.system("ping ..."): Simple but limited.
  • subprocess.Popen: Grants control and offers output formatting options.
  • ping3, pythonping: Provide advanced tools for deeper network diagnostics.

Remember, root privileges may be necessary, especially when creating raw ICMP packets.

Best practices and practical use-cases

Apart from basic server checks, consider:

  • Pinging multiple servers together using Python's concurrency tools.
  • Validating responses. A successful ping does not guarantee a fully functional server.
  • The security implications of sending ICMP requests – remember some networks may block them.
  • Monitor network policies that might affect ICMP.

Ensure proper exception handling in your script:

import concurrent.futures import ping3 # You'll need some server addresses here hosts = ["octopus.com", "shark.com", "whale.com"] with concurrent.futures.ThreadPoolExecutor() as executor: futures = {executor.submit(ping3.ping, host): host for host in hosts} for future in concurrent.futures.as_completed(futures): host = futures[future] try: response = future.result() # Future so bright, it's got a response! except Exception as exc: print(f"{host}: Oops! We have a problem: {exc}")