Uname:Linux antigravity-cli 6.8.0-31-generic #31-Ubuntu SMP PREEMPT_DYNAMIC Sat Apr 20 00:40:06 UTC 2024 x86_64

Base Dir : /var/www/moonbloom

User : wp-moonbloom


403WebShell
403Webshell
Server IP : 85.155.190.233  /  Your IP : 216.73.216.103
Web Server : nginx/1.24.0
System : Linux antigravity-cli 6.8.0-31-generic #31-Ubuntu SMP PREEMPT_DYNAMIC Sat Apr 20 00:40:06 UTC 2024 x86_64
User : wp-moonbloom ( 1001)
PHP Version : 8.3.6
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /opt/Gemini_Swarm_Core/scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/Gemini_Swarm_Core/scripts/setup_vps.py
import paramiko
import time
import os
import sys

# Reconfigure stdout/stderr to utf-8 if possible to print unicode characters correctly on Windows
if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass
if hasattr(sys.stderr, 'reconfigure'):
    try:
        sys.stderr.reconfigure(encoding='utf-8')
    except Exception:
        pass

def safe_print(msg):
    try:
        print(msg)
    except UnicodeEncodeError:
        enc = sys.stdout.encoding or 'utf-8'
        print(msg.encode(enc, errors='replace').decode(enc))

IP = "85.155.190.233"
PORT = 22
USER = "root"
PASSWORD = "saLvaK5F0X0iZnh"
NEW_PORT = 50022
PUBLIC_KEY = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOk3CAryZxg2ycxe/tQRs6VZEEQxe4KkGa5IRSsT1gNn hitdlaciebie'

def setup():
    safe_print(f"Connecting to {IP}:{PORT} as {USER}...")
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        client.connect(IP, port=PORT, username=USER, password=PASSWORD, timeout=10)
        safe_print("Successfully connected via password!")
    except Exception as e:
        safe_print(f"Failed to connect: {e}")
        return
        
    sftp = client.open_sftp()
    
    # 1. Setup authorized_keys
    safe_print("Setting up SSH public key...")
    try:
        sftp.mkdir("/root/.ssh", mode=0o700)
    except IOError:
        # Directory already exists
        pass
        
    # Read existing authorized_keys if exists, then append
    auth_path = "/root/.ssh/authorized_keys"
    existing_keys = ""
    try:
        with sftp.file(auth_path, "r") as f:
            existing_keys = f.read().decode('utf-8')
    except IOError:
        pass
        
    if PUBLIC_KEY not in existing_keys:
        safe_print("Appending public key to authorized_keys...")
        new_keys = existing_keys.strip() + "\n" + PUBLIC_KEY + "\n"
        with sftp.file(auth_path, "w") as f:
            f.write(new_keys.encode('utf-8'))
        sftp.chmod(auth_path, 0o600)
        safe_print("SSH public key written successfully.")
    else:
        safe_print("SSH public key already present.")
        
    # 2. Run system updates and install ufw, fail2ban, curl
    safe_print("Installing packages (ufw, fail2ban, curl)...")
    def run_cmd(cmd):
        safe_print(f"Running: {cmd}")
        stdin, stdout, stderr = client.exec_command(cmd)
        exit_status = stdout.channel.recv_exit_status()
        out = stdout.read().decode('utf-8')
        err = stderr.read().decode('utf-8')
        if exit_status != 0:
            safe_print(f"Command failed with code {exit_status}")
            safe_print(f"STDOUT:\n{out}")
            safe_print(f"STDERR:\n{err}")
        else:
            safe_print("Command succeeded.")
            if out.strip():
                safe_print(f"STDOUT:\n{out}")
        return exit_status, out, err

    # Update and install packages
    run_cmd("apt-get update && apt-get install -y ufw fail2ban curl")
    
    # 3. Configure UFW Firewall
    safe_print("Configuring UFW...")
    run_cmd("ufw allow 50022/tcp")
    run_cmd("ufw allow 80/tcp")
    run_cmd("ufw allow 443/tcp")
    # Enable UFW without prompting
    run_cmd("echo 'y' | ufw enable")
    run_cmd("ufw status verbose")
    
    # 4. Handle Ubuntu 24.04 sshd socket activation
    # We disable ssh.socket and enable ssh.service (traditional daemon).
    safe_print("Configuring systemd SSH services...")
    run_cmd("systemctl stop ssh.socket || true")
    run_cmd("systemctl disable ssh.socket || true")
    run_cmd("systemctl enable ssh.service || true")
    run_cmd("systemctl start ssh.service || true")
    
    # 5. Backup and modify /etc/ssh/sshd_config
    safe_print("Modifying sshd_config...")
    sshd_config_path = "/etc/ssh/sshd_config"
    # Backup sshd_config
    run_cmd(f"cp {sshd_config_path} {sshd_config_path}.bak")
    
    # Read sshd_config
    with sftp.file(sshd_config_path, "r") as f:
        lines = f.readlines()
        
    new_lines = []
    keys_to_comment = ["Port", "PasswordAuthentication", "PermitRootLogin", "KbdInteractiveAuthentication", "PubkeyAuthentication"]
    for line in lines:
        stripped = line.strip()
        comment_out = False
        for key in keys_to_comment:
            if stripped.startswith(key + " ") or stripped.startswith(key + "\t"):
                comment_out = True
                break
        if comment_out:
            new_lines.append(f"# {line}")
        else:
            new_lines.append(line)
            
    # Clean up files in sshd_config.d if any
    try:
        files = sftp.listdir("/etc/ssh/sshd_config.d")
        for file in files:
            file_path = f"/etc/ssh/sshd_config.d/{file}"
            safe_print(f"Cleaning settings in {file_path}...")
            run_cmd(f"cp {file_path} {file_path}.bak")
            with sftp.file(file_path, "r") as f_d:
                d_lines = f_d.readlines()
            new_d_lines = []
            for d_line in d_lines:
                d_stripped = d_line.strip()
                comment_out = False
                for key in keys_to_comment:
                    if d_stripped.startswith(key + " ") or d_stripped.startswith(key + "\t"):
                        comment_out = True
                        break
                if comment_out:
                    new_d_lines.append(f"# {d_line}")
                else:
                    new_d_lines.append(d_line)
            with sftp.file(file_path, "w") as f_d:
                f_d.write("".join(new_d_lines).encode('utf-8'))
    except IOError:
        pass

    # Append our custom settings at the end of sshd_config
    custom_settings = f"\n\n# Antigravity VPS Hardening Settings\nPort 50022\nPasswordAuthentication no\nPermitRootLogin prohibit-password\nKbdInteractiveAuthentication no\nPubkeyAuthentication yes\n"
    final_content = "".join(new_lines) + custom_settings
    
    with sftp.file(sshd_config_path, "w") as f:
        f.write(final_content.encode('utf-8'))
    safe_print("sshd_config updated.")
    
    # 6. Configure Fail2ban
    safe_print("Configuring Fail2ban...")
    jail_local_content = """[sshd]
enabled = true
port = 50022
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 3
bantime = 86400
findtime = 600
"""
    with sftp.file("/etc/fail2ban/jail.local", "w") as f:
        f.write(jail_local_content.encode('utf-8'))
    safe_print("Fail2ban configured.")
    run_cmd("systemctl restart fail2ban")
    
    # 7. (Removed Docker installation)

    
    # 8. Restart SSH Service to apply port change
    safe_print("Restarting SSH service...")
    run_cmd("systemctl restart ssh")
    
    safe_print("\nSetup finished on remote host. Testing new SSH connection...")
    
    # 9. Verify connection using private key on port 50022
    safe_print("\nStarting self-verification of the new key-based SSH access on port 50022...")
    time.sleep(3)  # Give SSH service a moment to restart
    test_client = paramiko.SSHClient()
    test_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    private_key_path = os.path.expanduser("~/.ssh/id_ed25519")
    try:
        key = paramiko.Ed25519Key.from_private_key_file(private_key_path)
        test_client.connect(IP, port=NEW_PORT, username=USER, pkey=key, timeout=10)
        safe_print("\n" + "="*80)
        safe_print("Self-verification SUCCESSFUL! Connection established using private key on port 50022.")
        safe_print("="*80 + "\n")
        test_client.close()
    except Exception as e:
        safe_print("\n" + "!"*80)
        safe_print(f"Self-verification FAILED: {e}")
        safe_print("WARNING: DO NOT close this terminal, as password login might have been disabled but key authentication is not working.")
        safe_print("!"*80 + "\n")
        
    sftp.close()
    client.close()

if __name__ == "__main__":
    setup()

Youez - 2016 - github.com/yon3zu
LinuXploit