I have a MariaDB hosted onto my Pi. In order to access the data I need to SSH into it.
The same piece of code sometimes work exactly as intended, sometimes it will hang forever. Sometimes if I run it I'll get the following error. Note that raspberry.local is the host name of my Pi.
2024-01-30 02:59:17,323| ERROR | Could not resolve IP address for raspberry.local, aborting!
Traceback (most recent call last):
File "C:\Users\..\PycharmProjects\..\src\readme\test.py", line 28, in <module>
tunnel.start()
File "C:\Users\..\PycharmProjects\..\venv\lib\site-packages\sshtunnel.py", line 1331, in start
self._raise(BaseSSHTunnelForwarderError,
File "C:\Users\..\PycharmProjects\..\venv\lib\site-packages\sshtunnel.py", line 1174, in _raise
raise exception(reason)
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
Here's the code I have.
import mariadb
import os
import sys
import json
from sshtunnel import SSHTunnelForwarder
dir_path = os.path.dirname(os.path.realpath(__file__))
config_path = f"{dir_path}/mariadb_ga_config.json"
ssh_path = f"{dir_path}/ssh_config.json"
# SSH configs
with open(ssh_path, "r") as ssh_config_file:
ssh_config = json.load(ssh_config_file)
# MariaDB configs
with open(config_path, "r") as file:
creds = json.load(file)
host = ssh_config["host"] #hangs with 192.168.x.x, Cannot resolve IP address for raspberry.local if I put in raspberry.local. But sometimes using either the direct IP or raspberry.local will still output the correct result
port = ssh_config["port"] #22
username = ssh_config["username"]
password = ssh_config["password"]
remote_bind_address = ssh_config["remote_bind_address"] #127.0.0.1
remote_port = ssh_config["remote_port"] #3306
tunnel = SSHTunnelForwarder((host, port), ssh_password=password, ssh_username=username,
remote_bind_address=(remote_bind_address, remote_port))
tunnel.start()
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user=creds["user"],
password=creds["password"],
host=remote_bind_address,
port=tunnel.local_bind_port,
database=creds["database"]
)
except mariadb.Error as e:
print(e)
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
cur = conn.cursor()
cur.execute("SELECT * FROM sensordb.time_on_pc;")
x = cur.fetchall()
print(x)
conn.close()
tunnel.stop()