aggiunti server sftp

This commit is contained in:
2025-11-02 16:33:16 +01:00
parent d865b7daf2
commit b5d3e764e8
15 changed files with 674 additions and 22 deletions

View File

@@ -1,11 +1,17 @@
#!.venv/bin/python
"""
This module implements an FTP server with custom commands for
This module implements an FTP/SFTP server with custom commands for
managing virtual users and handling CSV file uploads.
Server mode is controlled by FTP_MODE environment variable:
- FTP_MODE=ftp (default): Traditional FTP server
- FTP_MODE=sftp: SFTP (SSH File Transfer Protocol) server
"""
import asyncio
import logging
import os
import sys
from hashlib import sha256
from logging.handlers import RotatingFileHandler
from pathlib import Path
@@ -140,15 +146,9 @@ def setup_logging(log_filename: str):
root_logger.info("Logging FTP configurato con rotation (10MB, 5 backup) e console output")
def main():
"""Main function to start the FTP server."""
# Load the configuration settings
cfg = setting.Config()
def start_ftp_server(cfg):
"""Start traditional FTP server."""
try:
# Configure logging first
setup_logging(cfg.logfilename)
# Initialize the authorizer with database support
# This authorizer checks the database on every login, ensuring
# all FTP server instances stay synchronized without restarts
@@ -185,7 +185,60 @@ def main():
server.serve_forever()
except Exception as e:
logger.error("Exit with error: %s.", e)
logger.error("FTP server error: %s", e, exc_info=True)
sys.exit(1)
async def start_sftp_server_async(cfg):
"""Start SFTP server (async)."""
try:
from utils.servers.sftp_server import start_sftp_server
logger.info(f"Starting SFTP server on port {cfg.service_port}")
logger.info(f"Database connection: {cfg.dbuser}@{cfg.dbhost}:{cfg.dbport}/{cfg.dbname}")
# Start SFTP server
server = await start_sftp_server(cfg, host="0.0.0.0", port=cfg.service_port)
# Keep server running
await asyncio.Event().wait()
except ImportError as e:
logger.error("SFTP mode requires 'asyncssh' library. Install with: pip install asyncssh")
logger.error(f"Error: {e}")
sys.exit(1)
except Exception as e:
logger.error("SFTP server error: %s", e, exc_info=True)
sys.exit(1)
def main():
"""Main function to start FTP or SFTP server based on FTP_MODE environment variable."""
# Load the configuration settings
cfg = setting.Config()
# Configure logging first
setup_logging(cfg.logfilename)
# Get server mode from environment variable (default: ftp)
server_mode = os.getenv("FTP_MODE", "ftp").lower()
if server_mode not in ["ftp", "sftp"]:
logger.error(f"Invalid FTP_MODE: {server_mode}. Valid values: ftp, sftp")
sys.exit(1)
logger.info(f"Server mode: {server_mode.upper()}")
try:
if server_mode == "ftp":
start_ftp_server(cfg)
elif server_mode == "sftp":
asyncio.run(start_sftp_server_async(cfg))
except KeyboardInterrupt:
logger.info("Server stopped by user")
except Exception as e:
logger.error("Unexpected error: %s", e, exc_info=True)
sys.exit(1)
if __name__ == "__main__":