Upload
andolasoft
View
912
Download
0
Embed Size (px)
Citation preview
How to send files to remote server via SSH in PHP?
This example describes ‘How to SSH to remote server in PHP and send files from one server to another server using libssh2.’
ssh2_connect() - Connect to a remote serverssh2_scp_send() - Send a file via SSHssh2_exec() - Execute a command on a remote server
Install libssh2 and then install PECL SSH2 extension for PHP.
Example:$ip = "192.168.2.101";$username = "test";$port = 22;$public_ssh_key = "/var/www/html/ssh_keys/id_dsa.pub";$private_ssh_key = "/var/www/html/ssh_keys/id_dsa";
if(function_exists("ssh2_connect")) {$ssh_conn = ssh2_connect($ip, $port);if($ssh_conn) {
//Validate your username with ssh keysif(ssh2_auth_pubkey_file($ssh_conn, $username, $public_ssh_key,
$private_ssh_key, 'secret')) {
// Check file list $stream = ssh2_exec($ssh_conn, 'ls -l /home/test/'); if($stream) {
stream_set_blocking($stream, true);while ($buf = fread($stream,4096)) {
flush(); // comment this line$data.=$buf;print_r($buf); // comment this line
}fclose($stream);
} // send file from one server to another ssh2_scp_send($ssh_conn, '/path/from/file.ext',
'/home/test/file.ext', 0777); }else { die("SSH validation failed using Username: ".$username." (specify
valid SSH keys or check your SSH key path)");}
} else {
die("SSH validation failed for IP: ".$ip);}
}else {
die("'ssh2_connect()' doesn't exists. Install libssh2 with PECL SSH2 extension");}
Other commands:
ssh2_sftp() - Initialize SFTP subsystemssh2_sftp_mkdir() - Create directory on remote server$sftp = ssh2_sftp($ssh_conn);ssh2_sftp_mkdir($sftp, '/var/www/html/test');
ssh2_auth_password() - Authenticate over SSH using a plain passwordssh2_auth_pubkey_file() - Authenticate using a public keyssh2_shell() - Request an interactive shellssh2_tunnel() - Open a tunnel through a remote server