4

I have a python script, that is working only if my server is available. So before the script is beginning, i want to ping my server or rather checking the availability of the server.

There are already some related SO questions. E.g

  1. pyping module

    response = pyping.ping('Your IP')
    if response.ret_code == 0:
       print("reachable")
    else:
        print("unreachable")
    
  2. ping process in python

    response = os.system("ping -c 1 " + hostname)
    

These answers works well, but only as ROOT user! When i use this solutions as a common user i get the following error message:

ping: Lacking privilege for raw socket.

I need a solution, that i can do that as a common user, because i run this script in a jenkins job and have not the option to run in as root.

Community
  • 1
  • 1
Oni1
  • 1,445
  • 2
  • 19
  • 39
  • Does it have to be a ping? What about an HTTP GET or a simple UDP packet? – André Borie Nov 22 '16 at 15:45
  • Hmm, i didn't think about it. The first thing what comes to my mind was pinging, therefore i'm trying to solve it with ping. And it's short and simple. But if have any other solution, you can write it as answer below please. – Oni1 Nov 22 '16 at 15:49
  • 4
    Why are you trying to check availability? Are you trying to do a quick check before trying to use some service running on it on a known port? If yes, I would rather try connecting to the service instead of trying to ping it first and then connecting to the "real" service. – Sanjay T. Sharma Nov 22 '16 at 15:56
  • @SanjayT.Sharma no i check the availability, because i want to know if the server is up or down. I didn't use any service of it. – Oni1 Nov 22 '16 at 16:00

1 Answers1

4

Would trying to perform a HTTP HEAD request, assuming the machine has a http server running, suffice?

from http.client import HTTPConnection # python3

try:
    conn = HTTPConnection(host, port, timeout)
    conn.request("HEAD", "/")
    conn.close()

    # server must be up
except:
    # server is not up, do other stuff
georgedeath
  • 419
  • 4
  • 10