How can PHP scripts on one server interact with SSH commands on another server without compromising security?
PHP scripts on one server can interact with SSH commands on another server using SSH keys for authentication. This involves generating a public and private SSH key pair on the server where the PHP script resides and adding the public key to the authorized_keys file on the remote server. This way, the PHP script can securely execute SSH commands on the remote server without compromising security.
<?php
$remote_server = 'remote_server_ip';
$ssh_user = 'ssh_username';
$command = 'ls -l';
$connection = ssh2_connect($remote_server, 22);
ssh2_auth_pubkey_file($connection, $ssh_user, '/path/to/private_key', '/path/to/public_key_passphrase');
$stream = ssh2_exec($connection, $command);
stream_set_blocking($stream, true);
$data = stream_get_contents($stream);
echo $data;
?>
Keywords
Related Questions
- How can nested arrays in PHP be iterated through using foreach loops without encountering "Array to string conversion" errors?
- What security risks are involved in directly inserting external data into MySQL queries in PHP, and how can they be mitigated using prepared statements?
- In what ways can the encoding of string values impact the behavior of PHP functions, especially when dealing with special characters like "ä"?