71 lines
2.8 KiB
Python
71 lines
2.8 KiB
Python
import argparse
|
||
from datetime import datetime
|
||
import json
|
||
import base64
|
||
from pymongo import MongoClient
|
||
|
||
def connect_to_mongo(uri, db_name):
|
||
"""Подключение к MongoDB."""
|
||
client = MongoClient(uri)
|
||
db = client[db_name]
|
||
return db
|
||
|
||
def load_json(json_path):
|
||
"""Загружает JSON-данные из файла."""
|
||
with open(json_path, "r", encoding="utf-8") as f:
|
||
return json.load(f)
|
||
|
||
def encode_file(file_path):
|
||
"""Читает файл и кодирует его в Base64."""
|
||
with open(file_path, "rb") as f:
|
||
return base64.b64encode(f.read()).decode("utf-8")
|
||
|
||
def insert_certificate(data, cert_path, cert_location):
|
||
"""Добавляет сертификат в указанное место внутри структуры JSON."""
|
||
# Читаем и кодируем сертификат
|
||
certificate_data = encode_file(cert_path)
|
||
|
||
# Разбиваем путь на вложенные ключи
|
||
keys = cert_location.split(".")
|
||
target = data
|
||
for key in keys[:-1]:
|
||
if key not in target:
|
||
target[key] = {} # Создаем вложенные ключи, если их нет
|
||
target = target[key]
|
||
target[keys[-1]] = {
|
||
"data": certificate_data,
|
||
"uploaded_at": datetime.utcnow()
|
||
}
|
||
|
||
def insert_data(db, collection_name, data):
|
||
"""Вставляет данные в указанную коллекцию MongoDB."""
|
||
collection = db[collection_name]
|
||
collection.insert_one(data)
|
||
print(f"Данные успешно вставлены в коллекцию '{collection_name}'.")
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="Insert JSON data into MongoDB with certificate")
|
||
parser.add_argument("--mongo-uri",default="mongodb://root:itOj4CE2miKR@mongodb:27017" ,required=True, help="MongoDB URI")
|
||
parser.add_argument("--db-name",default="MongoDBSub&Ser" ,required=True, help="MongoDB database name")
|
||
parser.add_argument("--collection",default="servers", required=True, help="Collection name")
|
||
parser.add_argument("--json-path", required=True, help="Path to the JSON file with data")
|
||
parser.add_argument("--cert-path", required=True, help="Path to the certificate file (.crt)")
|
||
parser.add_argument("--cert-location", required=True, help="Path inside JSON structure to store certificate (e.g., 'server.certificate')")
|
||
|
||
args = parser.parse_args()
|
||
|
||
# Подключение к MongoDB
|
||
db = connect_to_mongo(args.mongo_uri, args.db_name)
|
||
|
||
# Загрузка данных из JSON-файла
|
||
data = load_json(args.json_path)
|
||
|
||
# Вставка сертификата в структуру данных
|
||
insert_certificate(data, args.cert_path, args.cert_location)
|
||
|
||
# Вставка данных в MongoDB
|
||
insert_data(db, args.collection, data)
|
||
|
||
if __name__ == "__main__":
|
||
main()
|