1#!/usr/bin/env python3

2"""

3 Check that it's possible to establish a http connection against

4 ubuntu.com

5"""

6 from argparse import ArgumentParser

7 import http.client

8 import urllib.request

9 import urllib.error

10 import urllib.parse

11 import sys

12

13

14 def check_url(url):

15 """

16 Open URL and return True if no exceptions were raised

17 """

18 try:

19 urllib.request.urlopen(url)

20 except (urllib.error.URLError, http.client.InvalidURL):

21 return False

22

23 return True

24

25

26 def main():

27 """

28 Check HTTP and connection

29 """

30 parser = ArgumentParser()

31 parser.add_argument(

32 "-u",

33 "--url",

34 action="store",

35 default="http://cdimage.ubuntu.com",

36 help="The target URL to try. Default is %(default)s",

37 )

38 parser.add_argument(

39 "-a",

40 "--auto",

41 action="store_true",

42 default=False,

43 help="Runs in Automated mode, with no visible output",

44 )

45

46 args = parser.parse_args()

47

48 url = {"http": args.url}

49

50 results = {}

51 for protocol, value in url.items():

52 results[protocol] = check_url(value)

53

54 bool2str = {True: "Success", False: "Failed"}

55 message = "HTTP connection: %(http)s\n" % dict(

56 [(protocol, bool2str[value]) for protocol, value in results.items()]

57 )

58

59 if not args.auto:

60 if all(results.values()):

61 print(message)

62 else:

63 print(message, file=sys.stderr)

64

65 if any(results.values()):

66 return 0

67 else:

68 return 1

69

70

71 if __name__ == "__main__":

72 sys.exit(main())