sus/susmng.py

93 lines
2.6 KiB
Python
Raw Permalink Normal View History

2022-05-26 01:08:50 +00:00
#!/usr/bin/env python3
import sys
import requests
import hmac
import hashlib
import pathlib
import os
2022-05-26 14:51:14 +00:00
import json
import sys
2024-04-11 18:06:53 +00:00
import time
2022-05-26 01:08:50 +00:00
def get_args():
""" Get command line arguments """
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('command')
2022-05-26 14:51:14 +00:00
parser.add_argument('-s', '--server', default="")
parser.add_argument('-l', '--shortlink', default="")
parser.add_argument('-v', '--value', default="")
parser.add_argument('-c', '--config', type=pathlib.Path, default=pathlib.Path(os.path.expanduser('~/.config/susmng/config.json')))
parser.add_argument('-H', '--http', action='store_true')
2022-05-26 01:08:50 +00:00
return parser.parse_args()
def main(args):
""" Entry point for script """
2022-05-26 14:51:14 +00:00
if args.command == "init":
print(f"creating config file and quitting")
if args.config.exists():
print("config file exists... doing nothing")
return
with open(args.config, 'w+') as fp:
json.dump({ 'secrets': { 'sus.example.com': 'secret' } }, fp, indent=2)
return
2022-05-26 14:51:14 +00:00
with open(args.config) as fp:
config = json.load(fp)
server = args.server
if server == "":
server = list(config['secrets'].keys())[0]
secret = config['secrets'][server]
if args.command == "delete" and args.value != "confirm":
print("--value not set to 'confirm'... delete operation may fail")
2024-04-11 18:06:53 +00:00
# accoring to python documentation (https://docs.python.org/3/library/time.html#time.time)
# this function does not explicitly have to use unix time, and implementation is dependent
# platform.
# most platforms (windows, unix) will probably give unix time though.
#
# the server side (main.go file) does explicitly use unix time (time.Now().UnixNano()) to get
# this number, but hopefully there should be no issues on most platforms.
timestamp = str(time.time_ns())
data = {
'Command': args.command,
'Shortlink': args.shortlink,
'Value': args.value,
'Timestamp': timestamp,
}
headers = {
'Signature': 'SUS-SIGNATURE-' + hmac.new(
secret.encode("UTF-8"),
(timestamp + ":" + args.command + ":" + args.shortlink + ":" + args.value).encode("UTF-8"),
hashlib.sha256
).hexdigest()
}
print(f"{data=}")
print(f"{headers=}")
r = requests.post(f"{'http' if args.http else 'https'}://{server}", data=data, headers=headers)
print(r, file=sys.stderr)
print(r.content.decode().strip())
2022-05-26 01:08:50 +00:00
return 0
if __name__ == '__main__':
try:
sys.exit(main(get_args()))
except KeyboardInterrupt:
sys.exit(0)