#!/usr/bin/env python3
"""
Simple MikroTik credential tester
Tests common default passwords for MikroTik devices
"""
import paramiko
import requests
from requests.auth import HTTPBasicAuth
import time

def test_ssh_credentials(host, username, password, timeout=5):
    """Test SSH credentials"""
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(
            host,
            port=22,
            username=username,
            password=password,
            timeout=timeout,
            allow_agent=False,
            look_for_keys=False,
        )
        client.close()
        return True
    except paramiko.AuthenticationException:
        return False
    except Exception as e:
        print(f"SSH connection error: {e}")
        return False

def test_http_credentials(host, username, password, timeout=5):
    """Test HTTP credentials by checking for successful auth"""
    try:
        # Try to access a protected resource
        response = requests.get(
            f"http://{host}/status",
            auth=HTTPBasicAuth(username, password),
            timeout=timeout,
            allow_redirects=False
        )
        # If we get anything other than 401/403, auth might be working
        return response.status_code not in [401, 403]
    except Exception as e:
        print(f"HTTP connection error: {e}")
        return False

def main():
    host = "10.250.2.2"
    username = "admin"
    
    # Common MikroTik default passwords
    passwords = [
        "",           # Empty password
        "admin",      # admin/admin
        "password",   # admin/password
        "123456",     # admin/123456
        "mikrotik",   # admin/mikrotik
        "router",     # admin/router
        "default",    # admin/default
        "1234",       # admin/1234
        "pass",       # admin/pass
    ]
    
    print(f"Testing credentials for MikroTik device at {host}")
    print("=" * 50)
    
    for password in passwords:
        pwd_display = f'"{password}"' if password else "(empty)"
        print(f"Testing {username}:{pwd_display}...", end=" ")
        
        # Test SSH first
        if test_ssh_credentials(host, username, password):
            print(f"✓ SSH SUCCESS with {username}:{pwd_display}")
            return password
        
        # Test HTTP
        if test_http_credentials(host, username, password):
            print(f"✓ HTTP SUCCESS with {username}:{pwd_display}")
            return password
            
        print("✗ Failed")
        time.sleep(0.5)  # Be polite
    
    print("\nNo common default passwords worked.")
    print("Suggestions:")
    print("1. Device may have custom password")
    print("2. Device may use different default algorithm") 
    print("3. Consider hardware reset if you own the device")
    return None

if __name__ == "__main__":
    main()