-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexpose
executable file
·71 lines (48 loc) · 1.92 KB
/
expose
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
#!/usr/bin/env python
"""
Matt Post
May 2017
Exposes a regular UNIX command as a web service running on an arbitrary port (-p).
This lets you then query the command using tools like "nc".
Requires that the underlying command being called NOT be buffered.
Example usage:
1. Start the server
$ ./expose -p 7648 "sed -l s/[aeiouy]//g"
2. Connect to it
$ echo "This is a test" | nc localhost 7648
ths s tst
(Why isn't this a builtin UNIX tool?)
"""
import sys
from SimpleHTTPServer import *
import SocketServer
import BaseHTTPServer
import argparse
import subprocess
parser = argparse.ArgumentParser(description='Server around nematus')
parser.add_argument('-p', dest='port', type=int, default=5675, help='Port to use')
parser.add_argument('-v', dest='verbose', action='store_true', default=False,
help="Be verbose")
parser.add_argument('command', type=str, help='command to run')
class MyTCPHandler(SocketServer.StreamRequestHandler):
def setup(self):
SocketServer.StreamRequestHandler.setup(self)
self.process = subprocess.Popen(args.command.split(),
stdout = subprocess.PIPE,
stdin = subprocess.PIPE)
def handle(self):
self.data = self.rfile.readlines()
for lineno, line in enumerate(self.data, 1):
self.process.stdin.write(line)
response = self.process.stdout.readline()
if args.verbose:
sys.stderr.write("{}/{} {} -> {}".format(self.client_address[0], lineno, line.rstrip(), response))
self.wfile.write(response)
def finish(self):
SocketServer.StreamRequestHandler.finish(self)
if __name__ == '__main__':
args = parser.parse_args()
if args.verbose:
sys.stderr.write('Listening on port {}\n'.format(args.port))
server = SocketServer.TCPServer(("", args.port), MyTCPHandler)
server.serve_forever()