phpseclib 2.x版本带端口连接服务器失败报错求助
Hey there, let's work through this SSH connection issue you're hitting with phpseclib 2.x. That "Connection closed by server" notice usually points to a misconfiguration or network block, so let's break down the fixes step by step.
First: Fix the Port Misuse in Your Code
Looking at your snippet, you're using $_SERVER['SERVER_PORT'] to build the SSH server address — that's the port your web server is running on (like 80 or 443), not the port your SSH server is listening on! That's almost certainly the root cause here.
SSH servers default to port 22, but if yours uses a custom port, you need to specify that explicitly (not pull it from the web server's environment). Here's a corrected version of your code structure:
include '../vendor/autoload.php'; define('NET_SSH2_LOGGING', phpseclib\Net\SSH2::LOG_COMPLEX); // Replace these with your actual SSH server details $sshServer = $_SERVER['SERVER_NAME']; // Only use this if your web server and SSH server are the same machine! $sshPort = 22; // Swap this for your SSH server's actual port (e.g., 2222 if custom) // Initialize SSH2 with the correct port $ssh = new phpseclib\Net\SSH2($sshServer, $sshPort); // Attempt login (replace with your credentials) if (!$ssh->login('your-ssh-username', 'your-ssh-password')) { exit('Login failed: ' . $ssh->getLastError()); } // Debug: Print the full connection log to see exactly where it's failing echo '<pre>' . $ssh->getLog() . '</pre>'; // Test with a simple command echo $ssh->exec('whoami');
Next: Rule Out Other Common Issues
If fixing the port doesn't resolve it, check these common causes:
- Firewall/Security Group Blocks: Make sure the SSH server's firewall allows incoming connections on your target port, and your client's network isn't blocking outbound SSH traffic. Test connectivity with a command-line SSH client first:
If this fails, the issue is network/server-side, not phpseclib.ssh your-username@your-server-ip -p your-ssh-port - SSH Server Configuration: Check your server's
sshd_configfile for restrictions:- Is password login enabled? (If using key auth, make sure phpseclib has access to the private key)
- Are IP restrictions in place that block your web server's IP?
- Does the server use encryption algorithms that phpseclib 2.x doesn't support? (For example, some newer algorithms may require additional PHP extensions)
- phpseclib Log Debugging: You already enabled
LOG_COMPLEX, so use$ssh->getLog()to see the full handshake process. Look for lines like "Server closed connection" — this will tell you if the server rejected the connection immediately (port/network issue) or during authentication (credential/configuration issue).
Final Notes
- Never hardcode credentials in your code — use environment variables or a secure config file instead.
- If your web server and SSH server are not the same machine, replace
$_SERVER['SERVER_NAME']with the actual SSH server's IP or domain.
内容的提问来源于stack exchange,提问作者Rejoanul Alam

