-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpc.py
executable file
·72 lines (65 loc) · 2.75 KB
/
httpc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import socket
import argparse
from urllib.parse import urlparse
def httpc_get(url, verbose):
# initialize the socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# urlparse is only used here to grab the hostname and request separately,
# NOT to connect! (So, you know, please don't dock marks for it... thanks!)
url = urlparse(url)
s.connect((url.hostname, 80))
request = "GET " + url.path + "?" + url.query + " HTTP/1.0\r\n\r\n"
s.sendall(request.encode("utf-8"))
response = s.recv(4096).decode("utf-8")
if not verbose:
response = response.split("\n")
for i in range(9,len(response)):
print(response[i])
else:
print(response)
s.close
def httpc_post(url, header, data, verbose):
# initialize the socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = urlparse(url)
s.connect((url.hostname, 80))
request = "POST " + url.path + " HTTP/1.0" + "\r\n" + "Host: "+ url.hostname + "\r\n" + header + "\r\n" + "Content-Length: " + str(len(data)) + "\r\n" + "\r\n" + data
s.sendall(request.encode("utf-8"))
response = s.recv(4096).decode("utf-8")
if not verbose:
response = response.split("\n")
for i in range(9,len(response)):
print(response[i])
else:
print(response)
s.close
# argument parsing for command-line use
parser = argparse.ArgumentParser()
getVsPost = parser.add_mutually_exclusive_group()
getVsPost.add_argument('-g', '--get', help='get with URL argument', type=str)
getVsPost.add_argument('-p', '--post', help='post with URL argument', type=str)
parser.add_argument('--header', help='header for HTTP post', type=str)
dataVsFile = parser.add_mutually_exclusive_group()
dataVsFile.add_argument('-d', '--data', help='data string for HTTP post', type=str)
dataVsFile.add_argument('-f', '--file', help='file for HTTP post', type=str)
verbose = parser.add_argument('-v', '--verbose', help='show verbose output',
action='store_true')
args = parser.parse_args()
if args.get is not None:
httpc_get(args.get, args.verbose)
elif args.post is not None and args.header is not None:
if args.data is not None:
httpc_post(args.post, args.header, args.data, args.verbose)
elif args.file is not None:
f = open(args.file, 'r')
data = file.read()
f.close()
httpc_post(args.post, args.header, data, args.verbose)
else:
print("error: expected either a data string (-d) or file (-f) for post request.")
parser.print_help()
elif args.post is not None and args.header is None:
print("error: expected a header (--header) for post request.")
parser.print_help()
else:
parser.print_help()