Python Test Code for URL on IP-Address only

Viewed 130

I'm a bit lost in Google-results. I have a webserver running through a Python built-in module. This works and provides an area to download automation configuration for devices. However, I like to build an availability test to provide better code. If http service is not available, then proceed with tftp server.

I tested with urllib2, but then the website gets timed out. If I try the same code with a named uri 'www.google.com' then the response code 200 is provided.

Any thoughts to provide a good solution?

  • in the code I provide a ping test.
  • now like to add 'service-available' test. on TRUE - proceed with GET.
  • should work on IP-ADDRESS eg.: 10.1.1.1:80

Thank you for the help.

code ex:

import httplib2
h = httplib2.Http(".cache")
(resp_headers, content) = h.request("http://10.10.1.1:80/", "GET")
print(resp_headers)
print(content)
1 Answers

Try this. On a successful ping, the script will attempt to connect to an HTTP service. If the request times out or is not successful (e.g., status 404), it will call your TFTP function:

import shlex
import socket
import subprocess

import httplib2

ip_address = "10.1.1.1"

print("Attempting to ping...")
p = subprocess.Popen(shlex.split("ping -c 3 {0}".format(ip_address)), stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, _ = p.communicate()
rc = p.returncode
if rc != 0 or "100% packet loss" in output.decode():
    raise RuntimeError("Unable to connect to {0}.".format(ip_address))
print("Ping successful.")

print("Attempting to connect to an HTTP service....")
h = httplib2.Http(cache=".cache", timeout=10)
response = {}
content = ""
try:
    response, content = h.request("http://{0}:80".format(ip_address), method="GET")
    if 200 <= int(response["status"]) <= 299:
        print("Connected to HTTP service.")
        for key, value in response.items():
            print(key, ":", value)
        print(content.decode())
    else:
        print("Request not OK. Attempting to connect to a TFTP service...")
        # Call to TFTP function goes here
except socket.timeout:
    print("Request timed out. Attempting to connect to a TFTP service...")
    # Call to TFTP function goes here
Related