doorstatus/setstatus.py

90 lines
2.9 KiB
Python
Executable file

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# file: setstatus.py
# date: 26.07.2019
# email: berhsi@web.de
# client, that connects to the statusserver at port 10001 to update the
# krautspace door status. allowed arguments are 0 or 1.
import argparse
import socket
import ssl
import sys
import os
def main():
description = "Set door status of Krautspace"
parser = argparse.ArgumentParser(description=description)
parser.add_argument("status_code", help="status to set", type=int,
choices=(0, 1))
args = parser.parse_args()
print("Status set to {}".format(bytes([args.status_code])))
HOST = 'localhost'
PORT = 10001
SERVER_NAME = 'server.status.kraut.space'
CLIENT_CERT = './certs/client.crt'
CLIENT_KEY = './certs/client.key'
SERVER_CERT = './certs/server.crt'
STATUS = None
RESPONSE = None
print('Check certs')
for certfile in (CLIENT_CERT, CLIENT_KEY, SERVER_CERT):
if os.access(certfile, os.R_OK) is False:
print('Failed to read cert: {}'.format(certfile))
sys.exit(1)
try:
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
cafile=SERVER_CERT)
context.load_cert_chain(certfile=CLIENT_CERT, keyfile=CLIENT_KEY)
context.set_ciphers('EECDH+AESGCM') # only ciphers for tls 1.2 and 1.3
context.options |= getattr(ssl._ssl, 'OP_NO_COMPRESSION', 0)
print('SSL context created')
except Exception as e:
print('Failed to create ssl context: {}'.format(e))
sys.exit(2)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as mySocket:
print('Socket created')
try:
conn = context.wrap_socket(mySocket, server_side=False,
server_hostname=SERVER_NAME)
print('Connection wrapped with ssl.context')
conn.settimeout(5.0)
except Exception as e:
print('Context wrapper failed: {}'.format(e))
try:
conn.connect((HOST, PORT))
print('Connection established: {}'.format(conn.getpeercert()))
except socket.timeout:
print('Connection timeout')
except Exception as e:
print('Connection failed: {}'.format(e))
sys.exit(3)
try:
print('Send new status: {}'.format(STATUS))
conn.send(STATUS)
except Exception as e:
print('Error: {}'.format(e))
sys.exit(4)
try:
RESPONSE = conn.recv(1)
print('Server returns: {}'.format(RESPONSE))
if RESPONSE == STATUS:
print('Status sucessfull updated')
else:
print('Failed to update status')
print('Disconnect from server')
except Exception as e:
print('Error: {}'.format(e))
sys.exit(5)
if __name__ == '__main__':
main()