onionator/onion_importer.py

56 lines
1.8 KiB
Python
Raw Permalink Normal View History

import argparse
import mysql.connector
from pathlib import Path
import shutil
import configparser
import base64
# Set up the argument parser
parser = argparse.ArgumentParser()
parser.add_argument('base_dir', nargs='+', help='path to the base directory')
args = parser.parse_args()
# Read the MariaDB server details from the configuration file
config = configparser.ConfigParser()
config.read('config.ini')
# Connect to the database
conn = mysql.connector.connect(
host=config['database']['host'],
user=config['database']['user'],
password=config['database']['password'],
database=config['database']['database']
)
cursor = conn.cursor()
# Create the table if it doesn't already exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS onion_keys (hostname text, public_key text, secret_key text)
''')
# Iterate over all base directories passed as arguments
for base_dir in args.base_dir:
base_dir = Path(base_dir)
# Iterate over all directories in the base directory
for dir_path in base_dir.iterdir():
if dir_path.is_dir():
# Read the contents of the hostname, public_key, and secret_key files
with open(dir_path / 'hostname') as f:
hostname = f.read().strip()
with open(dir_path / 'hs_ed25519_public_key', 'rb') as f:
public_key = base64.b64encode(f.read())
with open(dir_path / 'hs_ed25519_secret_key', 'rb') as f:
secret_key = base64.b64encode(f.read())
# Insert the data into the database
cursor.execute('''
INSERT INTO onion_keys (hostname, public_key, secret_key) VALUES (%s, %s, %s)
''', (hostname, public_key, secret_key))
conn.commit()
# Delete the directory and its contents
shutil.rmtree(dir_path)
# Close the connection to the database
conn.close()