#!/usr/bin/env python3
"""
Тихая проверка SSH credentials - только логин, без активных действий
"""
import socket
import paramiko
from pathlib import Path

def test_ssh_login(host, port, username, password):
    """Тихая проверка SSH login без активных действий"""
    try:
        # Создаем SSH клиент
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        # Подключаемся к SSH серверу
        ssh.connect(host, port=port, username=username, password=password, timeout=10)
        
        # Получаем информацию о сервере
        transport = ssh.get_transport()
        server_version = transport.remote_version
        
        # Закрываем соединение
        ssh.close()
        
        return True, f"SSH login successful: {server_version}"
        
    except paramiko.AuthenticationException:
        return False, "Authentication failed"
    except paramiko.SSHException as e:
        return False, f"SSH error: {str(e)}"
    except socket.timeout:
        return False, "Connection timeout"
    except ConnectionRefusedError:
        return False, "Connection refused"
    except Exception as e:
        return False, f"Error: {str(e)}"

def main():
    print("=== Тихая проверка SSH credentials ===\n")
    
    # SSH credentials из нашего набора
    ssh_creds = [
        {
            'db': '2210PIGOTTOILUAP01',
            'username': 'marketmax',
            'password': 'IMP$1220mm',
            'host': '65.122.47.114',
            'type': 'ssh_vendor'
        },
        {
            'db': '2610PIGOTTOILUAP01',
            'username': 'marketmaxinv',
            'password': 'IMP$0606ma',
            'host': '65.122.47.114',
            'type': 'ssh_vendor'
        }
    ]
    
    successful_logins = []
    failed_logins = []
    
    for cred in ssh_creds:
        print(f"Testing: {cred['username']}@{cred['host']}")
        print(f"Database: {cred['db']}, Type: {cred['type']}")
        
        # Определяем порт (по умолчанию 22)
        port = 22
        
        success, message = test_ssh_login(
            cred['host'], 
            port, 
            cred['username'], 
            cred['password']
        )
        
        if success:
            print(f"  ✅ {message}")
            successful_logins.append(cred)
        else:
            print(f"  ❌ {message}")
            failed_logins.append(cred)
        
        print()
    
    # Результаты
    print("=== Результаты ===")
    print(f"Успешных логинов: {len(successful_logins)}")
    print(f"Неудачных логинов: {len(failed_logins)}")
    
    if successful_logins:
        print("\n✅ Рабочие credentials:")
        for cred in successful_logins:
            print(f"  - {cred['username']}@{cred['host']} (db: {cred['db']})")
    
    if failed_logins:
        print("\n❌ Нерабочие credentials:")
        for cred in failed_logins:
            print(f"  - {cred['username']}@{cred['host']} (db: {cred['db']})")

if __name__ == '__main__':
    main()
