ding/ding

117 lines
3.0 KiB
Python
Executable File

#!/usr/bin/env python3
# Author: Bandie Canis
# License: 2-Clause BSD License
import sys, ssl, socket, os, getopt
import configparser
host = None
port = 0
cafile = None
certfile = None
keyfile = None
exitcode = 1
def init(conf):
if(conf == None):
if(os.name == 'nt'):
CONFIG = "ding.win.cfg"
else:
CONFIG = "ding.cfg"
else:
CONFIG = conf
cfg = configparser.ConfigParser()
try:
cfg.read(CONFIG)
global host, port, cafile, certfile, keyfile
host = cfg.get("Client", "host")
port = int(cfg.get("Client", "port"))
cafile = cfg.get("Client", "cafile")
certfile = cfg.get("Client", "certfile")
keyfile = cfg.get("Client", "keyfile")
except configparser.NoSectionError:
print("No suitable config found. Expecting some config in", CONFIG, file=sys.stderr)
quit(3)
def send(conn, cmd):
conn.connect((host, port))
buf = conn.recv(1024)
if(buf == b"OK 1337\n"):
conn.sendall(cmd)
buf = conn.recv(1024)
if(buf == b"OK CMD"):
exitcode = 0
elif(buf == b"ERR NO_CMD"):
print("Error. Server said: The command isn't set on the server.", file=sys.stderr)
exitcode = 1
elif(buf == b"ERR CMD_ERR"):
print("Error. Server said: The command doesn't work because the file doesn't exist on the server.", file=sys.stderr)
exitcode = 2
elif(buf == b"ERR PW"):
print("Error. Password required. The password was wrong.", file=sys.stderr)
exitcode = 4
elif(b"OK PW" in buf):
bufr=str(buf.decode('utf-8'))
print("Password accepted. Timeout:", bufr.replace("OK PW ",""), "seconds.")
else:
conn.sendall(b"NO.")
print("The server seems to be crazy. Nothing sent.", file=sys.stderr)
conn.close()
quit(exitcode)
def main(arg):
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(cafile)
context.load_cert_chain(certfile=certfile, keyfile=keyfile)
except FileNotFoundError as e:
print(e)
print("Please check your paths in the config file. (Have you forgotten to generate the Certificates?)", sep="", file=sys.stderr)
quit(2)
if(":" in host):
conn = context.wrap_socket(socket.socket(family=socket.AF_INET6))
else:
conn = context.wrap_socket(socket.socket(family=socket.AF_INET))
try:
send(conn, bytes(arg[0], sys.stdin.encoding))
except IndexError:
print(sys.argv[0], ": Missing argument.\nSyntax: ", sys.argv[0], " <COMMAND>", file=sys.stderr)
except ConnectionRefusedError:
print("Connection refused.", file=sys.stderr)
quit(1)
except ssl.SSLError:
print("Wrong certificate.", file=sys.stderr);
quit(3)
if(__name__ == "__main__"):
try:
conf = None
opts, args = getopt.getopt(sys.argv[1:], "c:")
for o, a in opts:
if o == "-c":
conf = a
init(conf)
main(args)
except getopt.GetoptError as e:
print("Error using options. Allowed options:\n-c [FILE] - Config file\n")
quit(2)
quit(exitcode)