You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从WordPress网站向远程Ubuntu服务器发送命令?

Hey there! Let's break down how you can send commands from your WordPress site to a remote Ubuntu server—whether you're sticking with your existing site or spinning up a new one. I’ll walk you through the most reliable, secure methods below, with code examples you can adapt:

This method leverages SSH for secure server-to-server communication, which is far safer than password-based auth. Here's how to set it up:

  • First, configure passwordless SSH access from your WordPress server to the remote Ubuntu box:
    1. Generate an SSH key on your WordPress server: ssh-keygen -t ed25519 (press enter through all prompts to avoid passphrases, or add one for extra security)
    2. Copy the public key to your remote server: ssh-copy-id ubuntu@your-remote-server-ip
  • Next, add a custom admin interface to WordPress to trigger remote commands. Paste this code into your theme's functions.php file or a custom plugin:
add_action('admin_menu', 'add_remote_command_menu');
function add_remote_command_menu() {
    add_menu_page(
        'Remote Server Commands', 
        'Remote Commands', 
        'manage_options', 
        'remote-commands', 
        'remote_command_page'
    );
}

function remote_command_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('You don’t have permission to access this page.'));
    }

    if (isset($_POST['execute_command'])) {
        $command = sanitize_text_field($_POST['server_command']);
        // Update these values to match your remote server
        $remote_user = 'ubuntu';
        $remote_host = 'your-remote-server-ip';
        $remote_port = 22;

        // Execute the remote command via SSH
        $output = shell_exec("ssh -p $remote_port $remote_user@$remote_host '$command'");
        echo '<pre>' . esc_html($output) . '</pre>';
    }
    ?>
    <div class="wrap">
        <h1>Remote Server Command Executor</h1>
        <form method="post">
            <label for="server_command">Enter Command:</label>
            <input type="text" name="server_command" id="server_command" style="width: 600px;">
            <p class="submit"><input type="submit" name="execute_command" class="button-primary" value="Run Command"></p>
        </form>
    </div>
    <?php
}
  • Critical Security Notes: Restrict access to admins only, sanitize all input to prevent command injection, and never expose this tool on your site's frontend.

2. Using PHP's SSH2 Extension

If you prefer a more integrated PHP approach, use the SSH2 extension to directly connect to the remote server:

  • Install the SSH2 extension on your WordPress server: sudo apt install php-ssh2 (for Ubuntu/Debian), then restart your web server (sudo systemctl restart apache2 or nginx)
  • Add this custom admin interface to WordPress:
add_action('admin_menu', 'ssh2_remote_command_menu');
function ssh2_remote_command_menu() {
    add_menu_page(
        'SSH2 Remote Commands', 
        'SSH2 Remote', 
        'manage_options', 
        'ssh2-remote', 
        'ssh2_remote_page'
    );
}

function ssh2_remote_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('No access here.'));
    }

    if (isset($_POST['run_command'])) {
        $command = sanitize_text_field($_POST['cmd']);
        $host = 'your-remote-server-ip';
        $user = 'ubuntu';
        $port = 22;
        $private_key = '/path/to/your/ssh/private/key'; // e.g., /var/www/.ssh/id_ed25519

        // Check if SSH2 extension is installed
        if (!function_exists('ssh2_connect')) {
            echo '<div class="error"><p>SSH2 extension is missing! Install it first.</p></div>';
            return;
        }

        // Connect to remote server
        $connection = ssh2_connect($host, $port);
        if (!$connection) {
            echo '<div class="error"><p>Failed to connect to the remote server.</p></div>';
            return;
        }

        // Authenticate with private key
        if (!ssh2_auth_pubkey_file($connection, $user, $private_key . '.pub', $private_key)) {
            echo '<div class="error"><p>Authentication failed. Check your SSH keys.</p></div>';
            return;
        }

        // Run the command and fetch output
        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        fclose($stream);

        echo '<pre>' . esc_html($output) . '</pre>';
    }
    ?>
    <div class="wrap">
        <h1>SSH2 Remote Command Runner</h1>
        <form method="post">
            <input type="text" name="cmd" style="width: 600px;" placeholder="e.g., df -h">
            <input type="submit" name="run_command" class="button-primary" value="Execute">
        </form>
    </div>
    <?php
}
  • Security Tip: Set strict permissions on your private key file (chmod 600 /path/to/private/key) to prevent unauthorized access.

3. Predefined API Middleware (Most Secure Option)

If you want to avoid arbitrary command execution entirely, build a lightweight API on your remote Ubuntu server that only runs pre-approved commands. This eliminates injection risks:

  • On your Ubuntu server, create a simple Flask API (install Flask first: pip install flask):
from flask import Flask, request, abort
import subprocess

app = Flask(__name__)

# Restrict requests to your WordPress server's IP
ALLOWED_IP = 'your-wordpress-server-ip'
# List of safe, predefined commands
ALLOWED_COMMANDS = {
    'update_packages': 'sudo apt update -y',
    'check_disk': 'df -h',
    'restart_nginx': 'sudo systemctl restart nginx'
}

@app.route('/run-command', methods=['POST'])
def run_command():
    # Block unauthorized IPs
    if request.remote_addr != ALLOWED_IP:
        abort(403, description="Unauthorized access")
    
    command_key = request.json.get('command')
    if command_key not in ALLOWED_COMMANDS:
        abort(400, description="Invalid command")
    
    # Run the command and return output
    result = subprocess.run(ALLOWED_COMMANDS[command_key], shell=True, capture_output=True, text=True)
    return {
        'stdout': result.stdout,
        'stderr': result.stderr,
        'code': result.returncode
    }

if __name__ == '__main__':
    # Use Gunicorn in production, not Flask's dev server!
    app.run(host='0.0.0.0', port=5000)
  • Then, add a WordPress admin interface to call this API:
add_action('admin_menu', 'api_remote_command_menu');
function api_remote_command_menu() {
    add_menu_page(
        'API Remote Commands', 
        'API Remote', 
        'manage_options', 
        'api-remote', 
        'api_remote_page'
    );
}

function api_remote_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('No permission to access this.'));
    }

    if (isset($_POST['execute_api_command'])) {
        $command_key = sanitize_text_field($_POST['cmd_key']);
        $api_url = 'http://your-remote-server-ip:5000/run-command';
        
        $response = wp_remote_post($api_url, array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode(array('command' => $command_key))
        ));

        if (is_wp_error($response)) {
            echo '<div class="error"><p>Failed to connect to the remote API.</p></div>';
            return;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        echo '<h3>Command Output:</h3>';
        echo '<pre>Stdout: ' . esc_html($body['stdout']) . '</pre>';
        echo '<pre>Stderr: ' . esc_html($body['stderr']) . '</pre>';
    }
    ?>
    <div class="wrap">
        <h1>API Remote Command Executor</h1>
        <form method="post">
            <select name="cmd_key">
                <option value="update_packages">Update Package Lists</option>
                <option value="check_disk">Check Disk Usage</option>
                <option value="restart_nginx">Restart Nginx</option>
            </select>
            <input type="submit" name="execute_api_command" class="button-primary" value="Run Command">
        </form>
    </div>
    <?php
}
  • Pro Tip: Use Nginx as a reverse proxy for the API and add SSL (via Let's Encrypt) to encrypt all traffic.

Final Security Best Practices

  • Never allow arbitrary command execution: Stick to predefined commands whenever possible to avoid injection attacks.
  • Restrict access: Only let site admins use these tools—never expose them to regular users or the frontend.
  • Monitor logs: Check your WordPress and remote server logs regularly for unusual activity.
  • Use SSH keys: Always prefer key-based auth over passwords for server connections.

内容的提问来源于stack exchange,提问作者Sidonia Crown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:03:58