This repository was archived by the owner on Jun 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathproxenet-control-cli.py
executable file
·146 lines (113 loc) · 3.87 KB
/
proxenet-control-cli.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# -*- mode: python -*-
import argparse, socket, datetime, os, json, rlcompleter, readline, pprint
import logging, sys
__author__ = "hugsy"
__version__ = 0.1
__licence__ = "WTFPL v.2"
__file__ = "control-client.py"
__desc__ = """control-client.py"""
__usage__ = """%prog version {0}, {1}
by {2}
syntax: {3} [options] args
""".format(__version__, __licence__, __author__, __file__)
FORMAT = '%(asctime)-15s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO,format=FORMAT)
# the socket path can be modified in config.h.in
PROXENET_SOCKET_PATH = "/tmp/proxenet-control-socket"
class ProxenetClientCompleter(object):
def __init__(self, options):
self.options = sorted(options)
return
def complete(self, text, state):
response = None
if state == 0:
if text:
self.matches = [s for s in self.options if s and s.startswith(text)]
logging.debug('{:s} matches: {:s}'.format(repr(text), self.matches))
else:
self.matches = self.options[:]
logging.debug('(empty input) matches: {:s}'.format(self.matches))
try:
response = self.matches[state]
except IndexError:
response = None
return response
def connect(sock_path):
if not os.path.exists(sock_path):
logging.critical("Socket does not exist.")
logging.error("Is proxenet started?")
return None
try:
sock = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
sock.settimeout(5)
sock.connect(sock_path)
except socket.error as se:
logging.error("Failed to connect: %s" % se)
return None
logging.info("Connected")
return sock
def recv_until(sock, pattern=">>> "):
data = ""
while True:
data += sock.recv(1024)
if data.endswith(pattern):
break
return data
def list_commands(sock):
banner = recv_until(sock)
sock.send("help\n")
res = recv_until(sock)
data, prompt = res[:-4], res[-4:]
js = json.loads( data )
cmds = js["Command list"].keys()
sock.send("\n")
return cmds
def input_loop(cli):
if not cli:
return
do_loop = True
try:
while True:
if not do_loop:
recv_until(cli)
break
res = recv_until(cli)
data, prompt = res[:-4], res[-4:]
try:
js = json.loads( data )
print( json.dumps(js, sort_keys=True, indent=4, separators=(',', ': ')) )
except:
print(data)
cmd = raw_input( prompt )
cli.send(cmd.strip()+"\n")
if cmd.strip() == "quit":
do_loop = False
except KeyboardInterrupt:
logging.info("Exiting client")
except EOFError:
logging.info("End of stream")
except Exception as e:
logging.error("Unexpected exception: %s" % e)
finally:
cli.close()
return
if __name__ == "__main__":
parser = argparse.ArgumentParser(usage = __usage__,
description = __desc__)
parser.add_argument("-v", "--verbose", default=False,
action="store_true", dest="verbose",
help="increments verbosity")
parser.add_argument("-s", "--socket-path", default=PROXENET_SOCKET_PATH, dest="sock_path",
help="path to proxenet control Unix socket")
args = parser.parse_args()
sock = connect(args.sock_path)
if sock is None:
sys.exit(1)
command_list = list_commands(sock)
logging.info("Loaded %d commands" % len(command_list))
readline.parse_and_bind("tab: complete")
readline.set_completer(ProxenetClientCompleter(command_list).complete)
input_loop(sock)
sys.exit(0)