I have one problem. I write a script in PHP which connect to a remote server. The script copy a file and looks like this
<?php
$pubKey = "/path/to/public/key";
$privKey = "/path/to/private/key";
$srcFile = "/path/to/local/app.apk";
$dstFile = "/path/to/remote/app.apk";
$con = ssh2_connect("xxx.xxx.xx.xxx", "22", array("hostkey" => "ssh-rsa"));
if(ssh2_auth_pubkey_file($con, "user", $pubKey, $privKey, "pw"))
{
sftp = ssh2_sftp($con);
$sftpStream = fopen("ssh2.sftp://" . $sftp . $dstFile, "w");
try
{
if(!$sftpStream) throw new Exception("Could not open remote file: " . $dstFile);
$dataToSend = file_get_contents($srcFile);
if($dataToSend === false) throw new Exception("Could not open local file: " . $srcFile);
if(fwrite( $sftpStream, $dataToSend) === false) throw new Exception("Could not send data from file: " . $srcFile);
fclose($sftpStream);
$shell = ssh2_shell($con, "xterm");
fwrite($shell, "su system");
fwrite($con, "pm install -r " . $dstFile);
echo "passed through";
}
catch (Exception $e)
{
error_log("Exception: " . $e->getMessage());
fclose($sftpStream);
}
}
?>
The method ssh2_scp_send always failed so I tried it like this way and it works fine. The method ssh2_scp_send return an error like
PHP Warning: ssh2_scp_send(): Failed copying file in /srv/www/htdocs/index.php on line 10
and line 10 was the method. I have had the correct permission on the remote server and on my local pc.
I also tried something like this
ssh2_exec($con, "su system");
ssh2_exec($con, "pm install -r " . $dstFile);
I have tried to write the path to the app.apk manual too, but nothing works. It doesn't install the app on the remote server but it walks through my code because my website is displaying the message "passed through".
What can be the reason why the command does not executed on the shell on my remote server?
Related
I need to write a script to connect to a Cisco router and execute commands. The linux server and the Cisco router use ssh keys so no username/password are required. I have worked out how to make the connection, but I don't know how to issue the commands and read the responses.
Note: It has to be in php to integrate with some other stuff we have going on.
Here is what I have so far :-
<?php
$connection = ssh2_connect("n.n.n.n", 22, array("hostkey"=>"ssh-rsa"));
if(!$connection)
{
die("Could not connect to the Router \n\r");
exit();
}
if (ssh2_auth_none ($connection, "username"))
{
echo("Public Key Authentication Successful\n\r");
}
else
{
die("Public Key Authentication Failed");
exit();
}
// New commands based on help received
try
{
$command = "dir";
$stream = ssh2_exec($connection, $command);
// added to test if the ssh2_exec command returns false - which it does, issue is with the command ???
if(!$stream)
{
echo("Command returned False\n\r");
exit();
}
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
$errorStreamContent = stream_get_contents($errorStream);
$streamContent = stream_get_contents($stream);
echo("ErrorStream : " . $errorStreamContent . "\n" . "Stream : " .
$streamContent . "\n\r");
}
catch(exception $e)
{
echo("Error : " . $e);
exit();
}
?>
Output is now as follows :-
Public Key Authentication Successful
Command returned False
Can anyone give me the correct way to issue commands and read any result ? Thanks.
I managed to fix this by using ssh2_auth_pubkey_file to pass the ssh keys to the router and authenticate. After that it works fine.
I need to establish a connection to an remote ssh server (debug2) via php. Inside the console everything works fine for me, but I doesnt get my php code running. I get following errormessage:
ssh2_auth_pubkey_file(): Authentication failed for [Username] using public key: Callback returned error
How can I establish a proper connection to debug2 without an registration on this.example.com?
My current code look like this:
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist" . PHP_EOL);
if(!($con = ssh2_connect("this.example.com", 22))){
echo "fail: unable to establish connection" . PHP_EOL;
} else {
if(!ssh2_auth_pubkey_file($con, "[Username]", $pubkeyfile, $privkeyfile)) {
echo "fail: unable to authenticate" . PHP_EOL;
//The point where the script fails
} else {
echo "okay: logged in..." . PHP_EOL;
$tunnel = ssh2_tunnel($con, 'xx.xx.xxx.17', 22);
if (!($stream = ssh2_exec($tunnel, "ls -al" ))) {
echo "fail: unable to execute command" . PHP_EOL;
} else {
stream_set_blocking($stream, true);
$data = "";
while ($buf = fread($stream,4096)) {
$data .= $buf;
}
fclose($stream);
}
}
}
My current ssh_config:
Host example
HostName this.example.com
User [Username]
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa
Host debug2
ProxyCommand ssh exmaple -W xx.xx.xxx.17:22
User [otherusername2]
IdentityFile ~/.ssh/id_rsa
I have to connect to a server via ssh, but to access it I need to first connect to another ssh server. I use standard password access to them.
So my steps are:
ssh root#serverdomain1.com
then when connected in serverdomain1 I do in terminal:
ssh myuseraccount#serverdomain2.com
in php, I tried to use ssh2_exec('ssh serverdomain2.com'); but no results. Then I tried also ss2_tunnel($connection, ...). but nothing worked.
This doesn't work:
$ssh = ssh2_connect('serverdomain1.com', 22);
if (ssh2_auth_password($ssh, $user,$pass)) {
$stream = ssh_exec($ssh, "ssh serverdomain2.com");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out); // <== doesn't work!!!
}
This also doesn't work:
$ssh = ssh2_connect('serverdomain1.com', 22);
if (ssh2_auth_password($ssh, $user,$pass)) {
$tunnel = ssh2_tunnel($ssh, 'serverdomain2.com', 22);
if (!$tunnel) {
echo('no tunnel<br/>');
}
else {
fwrite($tunnel, "echo 1\n");
while (!feof($tunnel)) {
echo fgets($tunnel, 128);
}
}
}
The echo result for tunnel:
"SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.4 Protocol mismatch."
How can I do that with SSH2 from PHP?
I recently published a project that allows PHP to obtain and interact with a real Bash shell, through SSH if needed. Get it here: https://github.com/merlinthemagic/MTS
The project lets you keep bouncing from server to server using ssh.
After downloading you would simply use the following code:
//first you get a shell on the first server:
$shellObj = \MTS\Factories::getDevices()->getRemoteHost('ip_address1')->setConnectionDetail('username1', 'password1')->getShell();
//then build on that first shell, the following way.
\MTS\Factories::getDevices()->getRemoteHost('ip_address2')->setConnectionDetail('username2', 'password2')->getShell($shellObj);
//any command executed on the shell will run only on the second host you connected to.
$return1 = $shellObj->exeCmd("hostname");
echo $return1;//hostname of the second host you connected to
//
Make sure that RSSH, PECL, SSH2 libraries installed on your server
You can check this using phpinfo
Here is my working code to access the server using ssh2. Hope it will help!
<?php
$host = 'SERVER_HOST_ADDR';
$port = SERVER_PORT;
$username = 'SERVER_USERNAME';
$password = 'SERVER_PASSWORD';
$remoteDir = './home/'; //DIR_PATH
$localDir = '/var/www/html/'; //LOCAL_DIR_PATH
// Make our connection
$connection = ssh2_connect($host);
// 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.');
}
/**
* Now that we have our SFTP resource, we can open a directory resource
* to get us a list of files. Here we will use the $sftp resource in
* our address string as I previously mentioned since our ssh2://
* protocol allows it.
*/
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp/$remoteDir");
// Properly scan through the directory for files, ignoring directory indexes (. & ..)
while (false !== ($file = readdir($dirHandle))) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
echo "<pre>";print_r($files);
?>
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'm having lots of fun with ssh2 for php.(!)
I am testing by ssh-ing into localhost (running ubuntu). I have managed to connect and authenticate with my username( not root ), and some commands (like 'ls' return some info, which is promising. Definitely getting somewhere.
What I want to be able to do next is issue an 'su' command and then give the root password.
I don't get an error, and a resource is returned, but there seems to be no data in the stream. (I'm kind of expecting a 'Password:' prompt). I can't authenticate directly with the root password, because that is disabled for ssh.
Is there any reason why 'su' would return with some text, do you think?
Should I be expecting the 'Password:' prompt back?
Here's my code:
function changeServerPassword( $ip, $port, $sshUser, $sshPassword, $rootPassword, $newRootPassword, $newSSHPassword = false) {
// login to server using $sshUser and $sshPassword
// su as root and enter $rootPassword
// if any of the above steps fail, return with appropriate error message
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in
// Do I have to make sure that port is a number?
if(!($con = ssh2_connect($ip, $port))){
echo "fail: unable to establish connection\n";
} else {
// try to authenticate with username root, password secretpassword
if(!ssh2_auth_password($con, $sshUser, $sshPassword)) {
echo "fail: unable to authenticate\n";
} else {
// alright, we're in!
echo "okay: logged in...<br />";
//
if (!($stream = ssh2_exec($con, "su"))) {
echo "fail: unable to execute command\n";
} else {
echo $stream."<br />";
// collect returning data from command
stream_set_blocking($stream, true);
echo "after stream_set_blocking<br />";
$data = "";
while ($buf = fread($stream,4096)) {
$data .= $buf;
}
echo "data len: " . strlen($data) . "<br />";
echo $data."<br />";
fclose($stream);
}
}
}
}
borrowed from http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/
respect.
The output I get is:
okay: logged in...
Resource id #3
after stream_set_blocking
data len: 0
Thanks in advance for any help :)
Joe
You should try the latest SVN version of phpseclib - a pure PHP SSH implementation - instead. Here's how you'd do su with that:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('localhost', 22);
$ssh->login('username', 'password');
$ssh->read('[prompt]');
$ssh->write("su - user\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>
Maybe try something like bash -c su or su root and bash -c "su root"?
All you have to do is append your superuser password at the moment you execute the "su" command. You can make the following modification to your code.
$cmd = "su";
$cmd = "echo '" . $sshPassword . "' | sudo -S " . $cmd;
if (!($stream = ssh2_exec($con, $cmd))) {
...
}