How to Connect to a Metasploitable Machine Using SSH and FTP with Python

Python Script Image

In the world of cybersecurity and network security, practical, hands-on learning is essential. One of the most effective ways to gain real-world experience in a safe environment is to work with Metasploitable, a virtual machine designed for security training and testing purposes. This article will guide you through using a Python script to connect to a Metasploitable machine using SSH and FTP, allowing for remote command execution and file management.

Purpose of the Script

The purpose of this Python script is to create secure connections to a Metasploitable machine via two common network protocols:

  • SSH (Secure Shell): A protocol for securely accessing the machine and running remote commands.
  • FTP (File Transfer Protocol): A protocol used for exploring and managing files on the remote machine.

With SSH, the script enables you to interact with the Metasploitable machine directly, executing commands and performing various administrative tasks. Using FTP, you can list files, transfer files, and inspect the filesystem on the remote machine in a controlled environment. Together, these functions allow for a hands-on learning experience, from simple command-line navigation to more advanced file management tasks.

Why This Matters

This setup is an invaluable tool for cybersecurity students, professionals, or anyone looking to understand remote connection techniques in a safe environment. By simulating real-world access and data transfer between machines, the script provides practical insights into secure connections and reinforces fundamental knowledge of SSH and FTP protocols.

Code Walkthrough: A Step-by-Step Explanation

Now, let’s explore the code to understand how these functionalities are achieved. (Python)

The source code is available on GitHub = naveen-98

import paramiko
from ftplib import FTP
import sys

# Replace these with your actual credentials
SSH_USERNAME = 'msfadmin'
SSH_PASSWORD = 'msfadmin'
FTP_USERNAME = 'msfadmin'
FTP_PASSWORD = 'msfadmin'

Explanation:

The code begins by importing the required libraries. We use paramiko for SSH and ftplib for FTP connections. Then, the script defines the username and password for each connection type, which can be customized as needed.

Function 1: Establishing an SSH Connection

The ssh_connect function is designed to securely connect to the Metasploitable machine over SSH.

def ssh_connect(metasploitable_ip, port):
    try:
        # Create an SSH client
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        # Connect to the Metasploitable machine
        client.connect(metasploitable_ip, username=SSH_USERNAME, password=SSH_PASSWORD, port=port)
        print(f"Successfully connected to {metasploitable_ip} via SSH on port {port}.")
        
        # Open an interactive shell
        shell = client.invoke_shell()
        while True:
            command = input("Enter command to execute on Metasploitable (or 'exit' to quit): ")
            if command.lower() == 'exit':
                break
            shell.send(command + '\n')
            while shell.recv_ready():
                output = shell.recv(1024).decode('utf-8')
                print(output)
        
        client.close()
    except Exception as e:
        print(f"SSH Connection failed: {e}")
Breakdown:
  • SSH Client Creation: The script initializes an SSH client with paramiko.SSHClient(). It then sets a policy to automatically trust the SSH key of the Metasploitable machine.
  • Connecting to the Metasploitable Machine: Using client.connect(), it connects to the specified IP with the credentials and port number.
  • Interactive Shell: Upon successful connection, the script opens an interactive shell where users can input commands to execute on the remote machine. Each command is sent to the shell, and the output is displayed in real time.
  • Error Handling: If the connection fails, an exception is raised, and the user is notified.

Function 2: Establishing an FTP Connection

The ftp_connect function enables FTP connectivity, which supports file management on the remote server.

def ftp_connect(metasploitable_ip, port):
    try:
        # Create an FTP client
        ftp = FTP()
        ftp.connect(metasploitable_ip, port)
        ftp.login(user=FTP_USERNAME, passwd=FTP_PASSWORD)
        print(f"Successfully connected to {metasploitable_ip} via FTP on port {port}.")
        
        # List files in the current directory
        print("Files in the current directory:")
        ftp.retrlines('LIST')
        
        # Example: Downloading a file
        # ftp.retrbinary('RETR example.txt', open('example.txt', 'wb').write)
        
        ftp.quit()
    except Exception as e:
        print(f"FTP Connection failed: {e}")
Breakdown:
  • FTP Client Creation: Here, ftp = FTP() initializes the FTP client, which then connects to the specified IP and port (typically 21) and logs in with the credentials.
  • Directory Listing: The command ftp.retrlines('LIST') displays a list of files in the current directory on the Metasploitable machine.
  • File Download (optional): An example line for downloading files from the server is provided but commented out. This line can be modified and used to download specific files.
  • Error Handling: If the connection fails, an error message is displayed.

Main Function: User Input and Connection Selection

The main() function collects essential user information and determines the type of connection.

def main():
    metasploitable_ip = input("Enter the IP address of the Metasploitable machine: ")
    port = int(input("Enter the port number (default for SSH is 22, for FTP is 21): "))
    
    print("Select connection type:")
    print("1. SSH")
    print("2. FTP")
    choice = input("Enter your choice (1/2): ")
    
    if choice == '1':
        ssh_connect(metasploitable_ip, port)
    elif choice == '2':
        ftp_connect(metasploitable_ip, port)
    else:
        print("Invalid choice.")
Breakdown:
  • Input Prompts: The function prompts for the IP address and port of the Metasploitable machine.
  • Connection Type Selection: Based on user input, it directs the program to either ssh_connect or ftp_connect. An invalid choice results in an error message.

Running the Code

After executing this script, you’ll follow these steps:

  1. Provide the IP address and port of your Metasploitable machine.
  2. Choose SSH or FTP as your connection type.
  3. For SSH, you’ll be able to run commands interactively; for FTP, you’ll see a list of files in the current directory.

Conclusion

This script provides a foundational way to interact with a Metasploitable machine, making it a powerful tool for learning remote connections and basic file management. By mastering SSH and FTP in a controlled environment, users gain valuable insights into network security concepts and gain hands-on experience essential for further exploration in cybersecurity.

The full video is below.

https://youtu.be/Aivo5OCZnU4?si=D2TFfWd2iJGW2kBB
A Python script to gain remote access to Metasploitable.

Leave a Reply

Your email address will not be published. Required fields are marked *