What are the potential security risks of using ssh2_exec in PHP to send Linux server commands?

The potential security risks of using ssh2_exec in PHP to send Linux server commands include command injection vulnerabilities if user input is not properly sanitized. To mitigate this risk, it is crucial to validate and sanitize user input before passing it to the ssh2_exec function.

// Sanitize user input before executing the command
$user_input = $_POST['user_input'];
$clean_input = escapeshellarg($user_input);

// Execute the sanitized command using ssh2_exec
$connection = ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, "ls -l $clean_input");
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);

echo $output;