PHP实现向同局域网PC发送命令行指令的方法咨询
Hey there! Since you're new to PHP and trying to send commands to other computers on your local network, the standard exec() function isn't built for direct network communication—but there are several straightforward ways to achieve what you want. Let's break them down:
1. Using SSH (for Linux/macOS/Windows with SSH Server)
If the target PC has an SSH server running, this is one of the most reliable methods:
- Option 1: PHP SSH2 Extension
First, install and enable thessh2extension in yourphp.ini. Then you can usessh2_exec()to run commands remotely:$connection = ssh2_connect('192.168.1.100', 22); ssh2_auth_password($connection, 'your_username', 'your_password'); $stream = ssh2_exec($connection, 'ls -l /home'); stream_set_blocking($stream, true); $output = stream_get_contents($stream); echo $output; - Option 2: Call System SSH via
exec()
If you don't want to install the extension, use PHP'sexec()to call your system's native SSH command. Set up passwordless SSH login (using SSH keys) first to avoid manual password prompts:$ip = '192.168.1.100'; $command = 'ls -l /home'; exec("ssh your_username@{$ip} '{$command}'", $output, $return_var); print_r($output);
2. Using Windows Remote Tools (for Target Windows PCs)
For Windows machines, tools like psexec (from Sysinternals) work perfectly. Call it directly via PHP's exec():
$ip = '192.168.1.101'; $username = 'admin'; $password = 'your_password'; $command = 'dir C:\\'; exec("psexec \\\\{$ip} -u {$username} -p {$password} {$command}", $output, $return_var); print_r($output);
Note: The target PC needs administrative shares enabled and firewall rules configured to allow this traffic.
3. Custom TCP Client/Server
If you need full control, set up a simple TCP server on the target PC (using Python, C#, etc.) and use PHP as a client to send commands:
$ip = '192.168.1.102'; $port = 8080; $command = 'command arg1 arg2'; $socket = fsockopen($ip, $port, $errno, $errstr, 30); if ($socket) { fwrite($socket, $command . "\n"); $response = fgets($socket); echo $response; fclose($socket); } else { echo "Failed to connect: {$errstr} ({$errno})"; }
The target server will listen on the specified port, execute the received command, and send back the output.
Key Notes to Remember
- Security: Never hardcode passwords in your code—use environment variables or secure credential storage. Always validate and sanitize command inputs to prevent command injection attacks.
- Permissions: Ensure the PHP process has access to execute system tools (like SSH or psexec), and the target PC allows incoming connections (check firewall settings).
- Error Handling: Always check return values of functions like
exec(),ssh2_connect(), orfsockopen()to handle connection failures or command errors gracefully.
内容的提问来源于stack exchange,提问作者Miakatt

