moth/ctf/pointscli.py

64 lines
1.4 KiB
Python
Raw Normal View History

2009-08-20 16:20:44 -06:00
#! /usr/bin/env python3
2009-08-20 12:51:47 -06:00
import optparse
import select
import socket
import time
2009-10-05 13:33:20 -06:00
from . import points
2009-08-20 12:51:47 -06:00
def makesock(host):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((host, 6667))
return s
def submit(cat, team, score, sock=None):
if not sock:
2009-09-25 13:27:37 -06:00
sock = makesock('localhost')
2009-08-21 13:27:17 -06:00
begin = time.time()
mark = int(begin)
req = points.encode_request(1, mark, cat, team, score)
2009-08-20 16:20:44 -06:00
while True:
sock.send(req)
2009-08-21 13:27:17 -06:00
r, w, x = select.select([sock], [], [], begin + 2 - time.time())
if not r:
break
b = sock.recv(500)
try:
id, txt = points.decode_response(b)
2009-08-21 13:27:17 -06:00
except ValueError:
# Ignore invalid packets
continue
if id != 1:
# Ignore wrong ID
2009-08-21 13:27:17 -06:00
continue
if txt == 'OK':
return
else:
2009-08-20 16:20:44 -06:00
raise ValueError(txt)
2009-08-21 13:27:17 -06:00
2009-08-20 12:51:47 -06:00
def main():
p = optparse.OptionParser(usage='%prog CATEGORY TEAM SCORE')
p.add_option('-s', '--host', dest='host', default='localhost',
help='Host to connect to')
opts, args = p.parse_args()
try:
cat, team, score = args
score = int(score)
except ValueError:
return p.print_usage()
2009-08-20 16:20:44 -06:00
s = makesock(opts.host)
2009-08-20 12:51:47 -06:00
2009-08-20 16:20:44 -06:00
try:
submit(cat, team, score, sock=s)
2009-08-20 16:20:44 -06:00
except ValueError as err:
print(err)
raise
2009-08-20 12:51:47 -06:00
if __name__ == '__main__':
main()