From df4ebfd97acc7ff65b96170f5774974277f15cda Mon Sep 17 00:00:00 2001 From: Boernsman <5207214+Boernsman@users.noreply.github.com> Date: Tue, 24 Sep 2024 12:01:48 +0200 Subject: [PATCH] Fix flag parsing --- examples/python/client.py | 117 ++++++++++++++++++++++++++++++ examples/python/find.py | 40 +++++++++++ examples/sh/client.sh | 13 ++++ examples/sh/find.sh | 33 +++++++++ go.mod | 2 + go.sum | 2 + install.sh | 13 ++-- main.go | 145 +++++++++++++++++++++++++++++--------- public/index.html | 22 ++---- public/main.js | 6 +- 10 files changed, 331 insertions(+), 62 deletions(-) create mode 100644 examples/python/client.py create mode 100644 examples/python/find.py create mode 100755 examples/sh/client.sh create mode 100755 examples/sh/find.sh create mode 100644 go.sum diff --git a/examples/python/client.py b/examples/python/client.py new file mode 100644 index 0000000..e6ce08d --- /dev/null +++ b/examples/python/client.py @@ -0,0 +1,117 @@ +import argparse +import requests +import json +import time +import socket +import os + +STATE_FILE = "/tmp/ip_state.json" # Store the last IP and timestamp + +def get_local_ip(): + """ + Retrieve the current local IP address. + """ + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + # This doesn't actually send data; it's just to get the IP + s.connect(('8.8.8.8', 80)) + return s.getsockname()[0] + except Exception as e: + print(f"Error retrieving local IP: {e}") + return None + finally: + s.close() + +def get_hostname(): + """ + Retrieve the local machine's hostname. + """ + return socket.gethostname() + +def get_serial_number(): + """ + Retrieve the device's serial number. + This is an example command that works on many Linux systems. + Adjust as needed based on your hardware. + """ + try: + # This command works on many Linux systems + serial = os.popen("cat /etc/machine-id").read().strip() + if not serial: + serial = "UNKNOWN_SERIAL" + return serial + except Exception as e: + print(f"Error retrieving serial number: {e}") + return "UNKNOWN_SERIAL" + +def load_state(): + """ + Load the last known state (IP and timestamp) from file. + """ + if os.path.exists(STATE_FILE): + with open(STATE_FILE, 'r') as f: + return json.load(f) + return None + +def save_state(ip, timestamp): + """ + Save the current IP and timestamp to file. + """ + with open(STATE_FILE, 'w') as f: + json.dump({"ip": ip, "timestamp": timestamp}, f) + + +def send_ip_update(ip, name, id, server_ip, server_port): + """ + Send the local IP to the REST server as a JSON payload. + """ + url = f"http://{server_ip}:{server_port}/api/register" + payload = { + "name": name, + "address": ip, + "id": id + } + try: + response = requests.post(url, json=payload) + if response.status_code == 200: + print(f"Successfully sent IP update to {server_ip}:{server_port}: {ip}") + else: + print(f"Failed to send IP update. Status code: {response.status_code}") + except Exception as e: + print(f"Error sending IP update: {e}") + +def main(): + # Parse command line arguments + parser = argparse.ArgumentParser(description="Send local IP to a \"whereisit\" server when it changes, or every 24 hours.") + parser.add_argument("--server-ip", required=True, help="The IP address of the REST server.") + parser.add_argument("--server-port", required=True, help="The port number of the REST server.") + args = parser.parse_args() + server_ip = args.server_ip + server_port = args.server_port + + while True: + current_ip = get_local_ip() + + if not current_ip: + print("Could not determine local IP. Retrying in 10 minutes.") + time.sleep(600) # Retry in 10 minutes + continue + + hostname = get_hostname() + identifier = get_serial_number() + + state = load_state() + current_time = time.time() + + # Check if state exists and if 24 hours have passed or IP has changed + if not state or state['ip'] != current_ip or (current_time - state['timestamp'] > 86400): + send_ip_update(current_ip, hostname, identifier, server_ip, server_port) + save_state(current_ip, current_time) + else: + print(f"No changes in IP. Last sent IP: {state['ip']}. Will check again in 10 minutes.") + + # Wait 10 minutes before checking again + time.sleep(600) + +if __name__ == "__main__": + main() diff --git a/examples/python/find.py b/examples/python/find.py new file mode 100644 index 0000000..b2a98c1 --- /dev/null +++ b/examples/python/find.py @@ -0,0 +1,40 @@ +import argparse +import requests + +from typing import List + +def get_devices(server_ip, server_port) -> List[str]: + """ + Send the local IP to the REST server as a JSON payload. + """ + url = f"http://{server_ip}:{server_port}/api/devices" + try: + response = requests.get(url) + if response.status_code == 200: + print(f"Successfully sent IP update to {server_ip}:{server_port}: {ip}") + print(response.content) + else: + print(f"Failed to send IP update. Status code: {response.status_code}") + except Exception as e: + print(f"Error sending IP update: {e}") + +def main(): + # Parse command line arguments + parser = argparse.ArgumentParser(description="Get devices inside the network from a \"whereisit\" server.") + parser.add_argument("--server-ip", required=True, help="The IP address of the REST server.") + parser.add_argument("--server-port", required=True, help="The port number of the REST server.") + parser.add_argument("--identifier", required=False, help="The identifier of the device searched for.") + args = parser.parse_args() + server_ip = args.server_ip + server_port = args.server_port + + deviceList = get_devices(server_ip, server_port) + + if deviceList.count > 0: + for device in deviceList: + print("Device:", device) + else: + print("No device found") + +if __name__ == "__main__": + main() diff --git a/examples/sh/client.sh b/examples/sh/client.sh new file mode 100755 index 0000000..2bbf9bf --- /dev/null +++ b/examples/sh/client.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env sh + +if [ "$#" -ne 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +SERVER_IP=$1 +SERVER_PORT=$2 + +curl -X GET "${SERVER_IP}:${SERVER_PORT}/api/register" + +echo "----- DONE -----" diff --git a/examples/sh/find.sh b/examples/sh/find.sh new file mode 100755 index 0000000..4109df3 --- /dev/null +++ b/examples/sh/find.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env sh + +DEVICE_NAME=$(hostname) +DEVICE_ID=$(cat /etc/machine-id) +DEVICE_IP=$(hostname -I | awk '{print $1}') + +if [ "$#" -ne 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +SERVER_IP=$1 +SERVER_PORT=$2 + +# Construct JSON payload +JSON_PAYLOAD=$(cat < - - NUPNP - + WHEREISIT @@ -16,18 +14,6 @@
@@ -57,13 +43,13 @@

Register

To register a device for 24h:

-

curl -H "Content-Type: application/json" -X POST -d '{"name":"Devicename","address":"192.168.1.XX"}' https://nupnp.com/api/register
+
curl -H "Content-Type: application/json" -X POST -d '{"name":"devicename", "id": "ab4546cd", address":"192.168.1.123"}' ${IP_ADDRESS}/api/register


To register a device, add this to crontab:

-
@reboot sleep 10 && /usr/bin/curl -H "Content-Type: application/json" -X POST -d "{\"name\":\"$(hostname)\",\"address\":\"$(hostname -I | cut -d' ' -f1)\"}" https://nupnp.com/api/register
-          @daily /usr/bin/curl -H "Content-Type: application/json" -X POST -d "{\"name\":\"$(hostname)\",\"address\":\"$(hostname -I | cut -d' ' -f1)\"}" https://nupnp.com/api/register
+
@reboot sleep 10 && /usr/bin/curl -H "Content-Type: application/json" -X POST -d "{\"name\":\"$(hostname)\",\"address\":\"$(hostname -I | cut -d' ' -f1)\"}" /api/register
+          @daily /usr/bin/curl -H "Content-Type: application/json" -X POST -d "{\"name\":\"$(hostname)\",\"address\":\"$(hostname -I | cut -d' ' -f1)\"}" ${IP_ADDRESS}/api/register

diff --git a/public/main.js b/public/main.js index 16a53f5..c38d05e 100644 --- a/public/main.js +++ b/public/main.js @@ -28,6 +28,7 @@ function listDevices() { var devices = JSON.parse(this.response); if (devices.length === 0) { + console.log("No devices present") return; } @@ -39,6 +40,7 @@ function listDevices() { }); devices.forEach(function(l) { + console.log(l) var t = document.querySelector('.device-template'); t.content.querySelector('.device-name').textContent = l.name; t.content.querySelector('.device-link').textContent = l.internaladdress; @@ -52,12 +54,12 @@ function listDevices() { }); } else { - // We reached our target server, but it returned an error + console.log("We reached our target server, but it returned an error") } }; request.onerror = function() { - // There was a connection error of some sort + console.log("There was a connection error of some sort") }; request.send();