initial working
This commit is contained in:
149
vm2/src/load_ftp_users.py
Normal file
149
vm2/src/load_ftp_users.py
Normal file
@@ -0,0 +1,149 @@
|
||||
#!.venv/bin/python
|
||||
"""
|
||||
Script per prelevare dati da MySQL e inviare comandi SITE FTP
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from ftplib import FTP
|
||||
|
||||
import mysql.connector
|
||||
|
||||
from utils.config import users_loader as setting
|
||||
from utils.database.connection import connetti_db
|
||||
|
||||
# Configurazione logging
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Configurazione server FTP
|
||||
FTP_CONFIG = {"host": "localhost", "user": "admin", "password": "batt1l0", "port": 2121}
|
||||
|
||||
|
||||
def connect_ftp() -> FTP:
|
||||
"""
|
||||
Establishes a connection to the FTP server using the predefined configuration.
|
||||
Returns:
|
||||
FTP: An active FTP connection object.
|
||||
"""
|
||||
try:
|
||||
ftp = FTP()
|
||||
ftp.connect(FTP_CONFIG["host"], FTP_CONFIG["port"])
|
||||
ftp.login(FTP_CONFIG["user"], FTP_CONFIG["password"])
|
||||
logger.info("Connessione FTP stabilita")
|
||||
return ftp
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
logger.error("Errore connessione FTP: %s", e)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def fetch_data_from_db(connection: mysql.connector.MySQLConnection) -> list[tuple]:
|
||||
"""
|
||||
Fetches username and password data from the 'ftp_accounts' table in the database.
|
||||
|
||||
Args:
|
||||
connection (mysql.connector.MySQLConnection): The database connection object.
|
||||
Returns:
|
||||
List[Tuple]: A list of tuples, where each tuple contains (username, password).
|
||||
"""
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Modifica questa query secondo le tue esigenze
|
||||
query = """
|
||||
SELECT username, password
|
||||
FROM ase_lar.ftp_accounts
|
||||
"""
|
||||
|
||||
cursor.execute(query)
|
||||
results = cursor.fetchall()
|
||||
|
||||
logger.info("Prelevate %s righe dal database", len(results))
|
||||
return results
|
||||
|
||||
except mysql.connector.Error as e:
|
||||
logger.error("Errore query database: %s", e)
|
||||
return []
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
|
||||
def send_site_command(ftp: FTP, command: str) -> bool:
|
||||
"""
|
||||
Sends a SITE command to the FTP server.
|
||||
|
||||
Args:
|
||||
ftp (FTP): The FTP connection object.
|
||||
command (str): The SITE command string to send (e.g., "ADDU username password").
|
||||
Returns:
|
||||
bool: True if the command was sent successfully, False otherwise.
|
||||
"""
|
||||
try:
|
||||
# Il comando SITE viene inviato usando sendcmd
|
||||
response = ftp.sendcmd(f"SITE {command}")
|
||||
logger.info("Comando SITE %s inviato. Risposta: %s", command, response)
|
||||
return True
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
logger.error("Errore invio comando SITE %s: %s", command, e)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Main function to connect to the database, fetch FTP user data, and send SITE ADDU commands to the FTP server.
|
||||
"""
|
||||
logger.info("Avvio script caricamento utenti FTP")
|
||||
cfg = setting.Config()
|
||||
|
||||
# Connessioni
|
||||
db_connection = connetti_db(cfg)
|
||||
ftp_connection = connect_ftp()
|
||||
|
||||
try:
|
||||
# Preleva dati dal database
|
||||
data = fetch_data_from_db(db_connection)
|
||||
|
||||
if not data:
|
||||
logger.warning("Nessun dato trovato nel database")
|
||||
return
|
||||
|
||||
success_count = 0
|
||||
error_count = 0
|
||||
|
||||
# Processa ogni riga
|
||||
for row in data:
|
||||
username, password = row
|
||||
|
||||
# Costruisci il comando SITE completo
|
||||
ftp_site_command = f"addu {username} {password}"
|
||||
|
||||
logger.info("Sending ftp command: %s", ftp_site_command)
|
||||
|
||||
# Invia comando SITE
|
||||
if send_site_command(ftp_connection, ftp_site_command):
|
||||
success_count += 1
|
||||
else:
|
||||
error_count += 1
|
||||
|
||||
logger.info("Elaborazione completata. Successi: %s, Errori: %s", success_count, error_count)
|
||||
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
logger.error("Errore generale: %s", e)
|
||||
|
||||
finally:
|
||||
# Chiudi connessioni
|
||||
try:
|
||||
ftp_connection.quit()
|
||||
logger.info("Connessione FTP chiusa")
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
logger.error("Errore chiusura connessione FTP: %s", e)
|
||||
|
||||
try:
|
||||
db_connection.close()
|
||||
logger.info("Connessione MySQL chiusa")
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
logger.error("Errore chiusura connessione MySQL: %s", e)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user