Last active
March 1, 2024 21:51
-
-
Save xkstein/d2b4c5592f958c3319727694b2d6a5d3 to your computer and use it in GitHub Desktop.
Upload ip to firebase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| This is a little script for uploading raspberry pi ip's to a firebase server | |
| The idea is to have this script set up as a service that launches at network start | |
| Requires: | |
| + pyrebase | |
| + netifaces | |
| Set the following ENV variables (with your firebase server's config): | |
| + FIREBASE_API_KEY | |
| + FIREBASE_AUTH_DOMAIN | |
| + FIREBASE_DB_URL | |
| + FIREBASE_BUCKET | |
| + FIREBASE_AUTH_EMAIL | |
| + FIREBASE_AUTH_PASS | |
| **Note** You will have to change the `ni.ifaddresses` argument if not using wifi | |
| ''' | |
| import sys, datetime | |
| from os import getenv | |
| import socket | |
| import pyrebase | |
| import netifaces as ni | |
| import logging | |
| logging.basicConfig(filename='/home/pi/bin/upload_ip.log', encoding='utf-8', level=logging.DEBUG) | |
| try: | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| except ImportError: | |
| pass | |
| hostname = socket.gethostname() | |
| ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr'] | |
| logging.info(f'\n\nhostname:{hostname} ip:{ip}') | |
| firebaseConfig = { | |
| 'apiKey': getenv('FIREBASE_API_KEY'), | |
| 'authDomain': getenv('FIREBASE_AUTH_DOMAIN'), | |
| 'databaseURL': getenv('FIREBASE_DB_URL'), | |
| 'storageBucket': getenv('FIREBASE_BUCKET'), | |
| } | |
| logging.info(f'config: {firebaseConfig}') | |
| firebase = pyrebase.initialize_app(firebaseConfig) | |
| auth = firebase.auth() | |
| user = auth.sign_in_with_email_and_password(getenv('FIREBASE_AUTH_EMAIL'), | |
| getenv('FIREBASE_AUTH_PASS')) | |
| auth_token = user['idToken'] | |
| db = firebase.database() | |
| host = '-'.join(hostname.split('.')) | |
| entries = db.child('iplist').shallow().get() | |
| logging.info('Sending data...') | |
| package = { | |
| "ip": ip, | |
| "time": str(datetime.datetime.now()) | |
| } | |
| if host in entries.val(): | |
| data = { host: package } | |
| db.child('iplist').update(data, auth_token) | |
| else: | |
| db.child('iplist').child(host).set(package, auth_token) | |
| sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment