Categories
Python Answers

How to ping servers in Python?

Spread the love

Sometimes, we want to ping servers in Python.

In this article, we’ll look at how to ping servers in Python.

How to ping servers in Python?

To ping servers in Python, we can run the ping command with subprocess.

For instance, we write

import platform   
import subprocess 

def ping(host):
    param = '-n' if platform.system().lower()=='windows' else '-c'
    command = ['ping', param, '1', host]
    return subprocess.call(command) == 0

to define the ping function.

In it, we get the ping param given the platform name with

param = '-n' if platform.system().lower()=='windows' else '-c'

Then we create the command list with the command and the arguments for it.

Next, we call subprocess.call with the command and check if it has a 0 exit code with ==.

Conclusion

To ping servers in Python, we can run the ping command with subprocess.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *