dnsping.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #! /usr/bin/env python2
  2. # -*- coding: utf8 -*-
  3. import os
  4. def application(environ, start_response):
  5. parameters_list = environ['QUERY_STRING'].split("&")
  6. param_value = {}
  7. for item in parameters_list:
  8. param, value = item.split("=")
  9. param_value[param] = value
  10. ipv4_file_path = os.path.join(environ['DOCUMENT_ROOT'], "tmp/ipv4_address")
  11. ipv6_file_path = os.path.join(environ['DOCUMENT_ROOT'], "tmp/ipv6_address")
  12. try:
  13. file_v4 = open(ipv4_file_path, "r")
  14. file_v6 = open(ipv6_file_path, "r")
  15. except IOError:
  16. old_ipv4 = ""
  17. old_ipv6 = ""
  18. else:
  19. old_ipv4 = file_v4.readline()
  20. old_ipv6 = file_v6.readline()
  21. file_v4.close()
  22. file_v6.close()
  23. try:
  24. new_ipv4 = param_value["ipv4"]
  25. except KeyError:
  26. new_ipv4 = ""
  27. try:
  28. new_ipv6 = param_value["ipv6"]
  29. except KeyError:
  30. new_ipv6 = ""
  31. response_status = "200 IP didn't change"
  32. response_body = ""
  33. error = False
  34. if new_ipv4 == "" and new_ipv6 == "":
  35. # TODO: maybe implement some checking if it is a correct IPv4
  36. # address here
  37. response_status = "400 Bad Request"
  38. response_body = "The IP address you defined was empty or " \
  39. "invalid."
  40. else:
  41. if new_ipv4 != old_ipv4 and new_ipv4 != "":
  42. try:
  43. file = open(ipv4_file_path, "w")
  44. except IOError:
  45. error = True
  46. else:
  47. file.write(param_value['ipv4'])
  48. file.close()
  49. response_status = "200 OK"
  50. response_body = "The new IP address has been saved, thanks " \
  51. "and have a nice day!"
  52. if new_ipv6 != old_ipv6 and new_ipv6 != "":
  53. try:
  54. file = open(ipv6_file_path, "w")
  55. except IOError:
  56. error = True
  57. else:
  58. file.write(param_value["ipv6"])
  59. file.close()
  60. response_status = "200 OK"
  61. response_body = "The new IP address has been saved, thanks " \
  62. "and have a nice day!"
  63. if error is True:
  64. response_status = "503 Internal server error"
  65. response_body = "There has been an error serving your request."
  66. response_headers = [('Content-Type', 'text/plain'),
  67. ('Content-Length',
  68. str(len(response_body.encode('utf8'))))]
  69. start_response(response_status, response_headers)
  70. return [response_body.encode('utf8')]