get_ipaddr_state.py 647 B

12345678910111213141516171819202122232425
  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. import sys,socket,json
  4. if sys.version_info[0] == 2:
  5. import urllib2 as request
  6. else:
  7. import urllib.request as request
  8. try:
  9. socket.setdefaulttimeout(5)
  10. if len(sys.argv) == 1:
  11. apiurl = "http://ip-api.com/json"
  12. elif len(sys.argv) == 2:
  13. apiurl = "http://ip-api.com/json/%s" % sys.argv[1]
  14. content = request.urlopen(apiurl).read().decode('utf-8')
  15. content = json.JSONDecoder().decode(content)
  16. #print(content)
  17. if content['status'] == 'success':
  18. if content['country'] == 'China':
  19. print("CN")
  20. else:
  21. print(content['country'])
  22. except:
  23. print("Usage:%s IP" % sys.argv[0])