Last active
January 3, 2016 08:09
-
-
Save hedgeven/8433851 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
import sys, os, shutil | |
import getopt | |
import urllib2 | |
import base64 | |
import socket | |
from urlparse import urlparse | |
work_dir='/tmp/http_response' | |
log_file='/var/log/http_request' | |
def input_parse(argv): | |
params={'url':'','user':'','pw': ''} | |
try: | |
opts, args = getopt.getopt(argv,"hl:u:p:",["url=","user=","password="]) | |
except getopt.GetoptError: | |
print "Usage: http_request -l <'url'> [ -u <user> -p <password> ]" | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
print "Usage: http_request -l <'url'> [ -u <user> -p <password> ]" | |
sys.exit() | |
elif opt in ("-l", "--url"): | |
params['url'] = arg | |
elif opt in ("-u", "--user"): | |
params['user'] = arg | |
elif opt in ("-p", "--password"): | |
params['pw'] = arg | |
return params | |
def main(argv): | |
params = input_parse(argv) | |
url = urlparse(params['url']) | |
if os.path.exists(work_dir): | |
shutil.rmtree(work_dir) | |
os.mkdir(work_dir) | |
request = urllib2.Request(params['url']) | |
if params['user']!='' and params['pw']!='': | |
base64string = base64.encodestring('%s:%s' % (params['user'], | |
params['pw'])).replace('\n', '') | |
request.add_header("Authorization", "Basic %s" % base64string) | |
try: | |
resp = urllib2.urlopen(request, timeout=10) | |
print "Success:",resp.getcode() | |
sys.exit(0) | |
except urllib2.HTTPError, e: | |
print e | |
with open(work_dir+"/"+str(e.code), 'a') as f: | |
f.write(str(e)+"\n") | |
sys.exit(1) | |
except urllib2.URLError, e: | |
if isinstance(e.reason, socket.timeout): | |
print "Error: Timeout exceeded" | |
open(work_dir+"/Timeout", 'a').close() | |
else: | |
print "Error:",e.args[0][1] | |
with open(work_dir+"/Error", 'a') as f: | |
f.write(str(e.args[0][1])+"\n") | |
sys.exit(1) | |
except: | |
raise | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment