I have the following simple code, to connect to a local server and retrieve an index.php file.
$username = "Admin";
$password = "Admin";
$url = "192.168.1.33";
$connection = ssh2_connect($url);
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir = 'C:/downloadTest';
$remoteDir = '/htdocs';
$files = scandir('ssh2.sftp://' . $sftp . "/".$remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file == "index.php") {
//echo $remoteDir."/".$file;
//echo $localDir.'/'.$file;
ssh2_scp_recv($connection, "$remoteDir/$file", "$localdir/$file");
}
}
}
However after executing I always get an Error:
Warning: ssh2_scp_recv(): Unable to receive remote file in C:\path\to\index\index.php on line 21
On the server (Windows 10) I enabled OpenSSH Server and added the following lines to the config:
Subsystem sftp sftp-server.exe -d "C:\Server\data\"
ChrootDirectory C:\Server\data
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
AllowUsers Admin
I am able to connect through WinSCP through the SFTP Protocol, but not the SCP protocol.
Printing the file list works, so the connection is there 100%.
Local PC & Server are Windows 10.
Edit:
I am able to download files from the root folder with the following code:
<?php
$username = "Admin";
$password = "Admin";
$url = "192.168.1.33";
$remoteDir = "";
$localDir = "downloadtest\\";
$connection = ssh2_connect($url);
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
if(!$stream = ssh2_sftp($connection)){
die("Unable to create stream");
}
if(!$dir = opendir("ssh2.sftp://{$stream}/{$remoteDir}")){
die("Could not open dir");
}
$files = array();
while (false !== ($file = readdir($dir)))
{
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
foreach ($files as $file){
if(!$remote = #fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}","r")){
echo "unable to open remote file: $file\n";
continue;
}
if(!$local = #fopen($localDir . $file, "w")){
echo "Unable to create local file: $file\n";
continue;
}
$read = 0;
$filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}");
while ($read < $filesize && ($buffer = fread($remote, $filesize - $read))){
$read += strlen($buffer);
if(fwrite($local, $buffer) === false){
echo "Unable to write to local file: $file\n";
}
}
fclose($local);
fclose($remote);
}
?>
However this is not through scp but sftp. With sftp I can download wherever I like (root folder or sub folder), with scp it does not work at all and always gives me the error Warning: ssh2_scp_recv(): Unable to receive remote file in C:\path\to\index\index.php on line 21
I am 100% sure it is not a rights issue, since I can download files through the cmd with the following command
pscp -scp Admin#192.168.1.33:/htdocs/index.php C:\downloadTest\index.php
Related
Previously I connected to SFTP using Password & Username and this work:
if (!function_exists("ssh2_connect"))
die('Function ssh2_connect not found, you cannot use ssh2 here');
if (!$connection = ssh2_connect($host, $port))
die('Unable to connect');
if (!ssh2_auth_password($connection, $username, $password))
die('Unable to authenticate.');
if (!$stream = ssh2_sftp($connection))
die('Unable to create a stream.');
if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
die('Could not open the directory');
$files = array();
while (false !== ($file = readdir($dir)))
{
$filearr = explode(".", $file);
$getFileName = $filearr[0];
if ($getFileName == $fileName){
$files[] = $file;
}
}
How connect to SFTP with RSA key using PHP Native (Not Library) ?
This question already has answers here:
PHP, How to get current date in certain format [duplicate]
(3 answers)
Closed 5 years ago.
#!/usr/bin/php
<?php
$username = "user";
$password = "pass";
$url = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
{echo('Unable to connect.');}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
{echo ('Unable to create SFTP connection.');}
$localDir = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
if (substr($file, 0, 11)=='07-Jun-2017'){
# code...
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
}
?>
I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?
Use date().
date('d-M-Y')
It will become
#!/usr/bin/php
<?php
$username = "user";
$password = "pass";
$url = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
{echo('Unable to connect.');}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
{echo ('Unable to create SFTP connection.');}
$localDir = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
if (substr($file, 0, 11) == date('d-M-Y')) {
# code...
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
}
?>
If you want it to always be, let's say, yesterday, you may use it with strtotime(), so
date('d-M-Y', strtotime('yesterday'))
Replace your date with
date('d-M-Y')
http://php.net/manual/fr/function.date.php
This will take server current time.
My php website is hosted in Debain Machine and I want to move a file from that Machine to another Debain which is connected through VPN.
I tried shell_exec and scp , as mentioned here.
<?php
$output = shell_exec('scp file1.txt dvader#deathstar.com:somedir');
echo "<pre>$output</pre>";
?>
I also tried using SFTP
<?php
class SFTPConnection
{
private $connection;
private $sftp;
public function __construct($host, $port=22)
{
$this->connection = #ssh2_connect($host, $port);
if (! $this->connection)
throw new Exception("Could not connect to $host on port $port.");
}
public function login($username, $password)
{
if (! #ssh2_auth_password($this->connection, $username, $password))
throw new Exception("Could not authenticate with username $username " .
"and password $password.");
$this->sftp = #ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
}
public function uploadFile($local_file, $remote_file)
{
$sftp = $this->sftp;
$stream = #fopen("ssh2.sftp://$sftp$remote_file", 'w');
if (! $stream)
throw new Exception("Could not open file: $remote_file");
$data_to_send = #file_get_contents($local_file);
if ($data_to_send === false)
throw new Exception("Could not open local file: $local_file.");
if (#fwrite($stream, $data_to_send) === false)
throw new Exception("Could not send data from file: $local_file.");
#fclose($stream);
}
}
try
{
$sftp = new SFTPConnection("localhost", 22);
$sftp->login("username", "password");
$sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
echo $e->getMessage() . "\n";
}
?>
Simply My problem is that I am not able to move a file from one machine, where my php applicaton is working , to another machine which is connected through VPN.
I installed proftpd and created a user as mentioned here,
Please note default port is 21. And make sure you restart proftpd:
service proftpd restart
The code I used to upload a file is:
index.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$file = 'a.txt';
$remote_file = 'b.txt';
$conn_id = ftp_connect('www.xxx.com',21);
$login_result = ftp_login($conn_id, "username","password");
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
die();
}
ftp_close($conn_id);
?>
Here a.txt is present in the same directory of index.php.
It will copy the file to the folder you mentioned for that particular user to access and name it b.txt.
I want to download file from SFTP so i created page which looks like it.
<?php
$username = "XYZ";
$password = "ABC";
$url ='FTP.abc.COM';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files))
{
foreach ($files as $file) {
if ($file != '.' && $file != '..')
{
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
?>
When i will call this page from browser. It will show error look like it.
Fatal error: Call to undefined function ssh2_connect() in page.php on line 6
if this method is correct then what should i edit in this page?
and if there is another method then suggest me that method. Thanks in advance.
You'll probably have better success with phpseclib, a pure PHP SFTP implementation. eg.
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
// copies filename.remote to filename.local from the SFTP server
$sftp->get('filename.remote', 'filename.local');
?>
It has a number of advantages over libssh2:
http://phpseclib.sourceforge.net/ssh/compare.html
SSH2 functions are not standard functions in PHP. You have to install them first. See http://php.net/manual/en/ref.ssh2.php for more details.
This may have been asked before, I'm new to PHP and I'm trying to learn as much as I can, but this has really thrown me.
Basically what I want to know is, how would I use PHP code to get it to download everything from a remote server to a local location. It's getting it to download everything not just one file that I'm stuck on. So please can someone show/explain to me how I would do this?
What I've got so far:
<?php
$connection - ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$remote_dir="/remote_dir/";
$local_dir="/local_dir/";
$remote ="$remote_dir";
$stream = ssh2_exec($connection, $remote);
stream_set_blocking($stream,true);
$command=fread($stream,4096);
$array=explode(\n,$command);
$total_files=sizeof($array);
for($i=0;$i<$total_files;$i+++){
$file_name=trim($array[$i]);
if($file_name!=''{
$remote_file=$remote_dir.$file_name;
$local_file=$local_dir.$file_name;
if(ssh2_scp_recv($connection, $remote_file,$local_file)){
echo "File ".$file_name." was copied to $local_dir<br />";
}
}
}
fclose($stream);
?>
I think my $remote ="$remote_dir"; is wrong, and to be honest I've got $filename when I want the whole directory, this is all I have so far.
Here is a small code on how to read the folder and download all its files:
<?php
$host = 'localhost';
$port = 22;
$username = 'username';
$password = 'password';
$remoteDir = '/must/be/the/complete/folder/path';
$localDir = '/can/be/the/relative/or/absolute/local/path';
if (!function_exists("ssh2_connect"))
die('Function ssh2_connect not found, you cannot use ssh2 here');
if (!$connection = ssh2_connect($host, $port))
die('Unable to connect');
if (!ssh2_auth_password($connection, $username, $password))
die('Unable to authenticate.');
if (!$stream = ssh2_sftp($connection))
die('Unable to create a stream.');
if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
die('Could not open the directory');
$files = array();
while (false !== ($file = readdir($dir)))
{
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
foreach ($files as $file)
{
echo "Copying file: $file\n";
if (!$remote = #fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}", 'r'))
{
echo "Unable to open remote file: $file\n";
continue;
}
if (!$local = #fopen($localDir . $file, 'w'))
{
echo "Unable to create local file: $file\n";
continue;
}
$read = 0;
$filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}");
while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
{
$read += strlen($buffer);
if (fwrite($local, $buffer) === FALSE)
{
echo "Unable to write to local file: $file\n";
break;
}
}
fclose($local);
fclose($remote);
}
You can also resume this code to (it will not copy directories):
while (false !== ($file = readdir($dirHandle)))
{
if ($file == "." || $file == "..")
continue;
echo "Copying file: $file\n";
if(!ssh2_scp_recv($connection, $remoteDir . $file, $localDir . $file))
echo "Could not download: ", $remoteDir, $file, "\n";
}
If you do not use the full path on the remote folder it will not work:
opendir("ssh2.sftp://{$stream}{$remoteDir}")
Update: I was kindly corrected that this doesn't use sftp, but instead uses ftps. Here's a Stackoverflow link discussing using PHP to do SFTP.
The PHP docs already cover most of what you should need for this. Here's an example for fetching a list of the contents in the remote directory:
<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);
// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
$buff = ftp_rawlist($conn_id, '.');
var_dump($buff);
ftp_close($conn_id);
?>
Here you will find all the examples for what you can do with SFTP using PHP.
http://phpseclib.sourceforge.net/sftp/examples.html
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
// copies filename.remote to filename.local from the SFTP server
$sftp->get('filename.remote', 'filename.local');
?>