12 Replies - 489 Views - Last Post: 22 January 2012 - 05:02 PM

Topic Sponsor:

#1 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 21-January 10

PHP ssh

Posted 19 January 2012 - 05:20 PM

Hi all,

I need to create a php script that connects to a remote linux box and retrieves data. But I need it to continually run as the data will be updated very often. I plan on storing the data in a database but I need to get around this problem first.

The plan is when I go to the site the script would run and keep the database up to date.

I've included the code im working from.

Thanks for the help

<?php
if($ssh = ssh2_connect('127.0.0.1', 22))//If it connects 
{
    if(ssh2_auth_password($ssh, 'user', 'password'))//User and password to use 
    {
        $stream = ssh2_exec($ssh, 'cat -e /home/jason/Desktop/test');//command to execute
        stream_set_blocking($stream, true);
        $data = '';
        while($buffer = fread($stream, 4096))//read from stream 
	   {
            $data .= $buffer;
	    echo $data; //output results
        }
        fclose($stream);//close stream
    }
}
?>

This post has been edited by compactbrain: 19 January 2012 - 05:34 PM


Is This A Good Question/Topic? 0
  • +

Replies To: PHP ssh

#2 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 21-January 10

Re: PHP ssh

Posted 19 January 2012 - 08:41 PM

Hi again

I've been trying a few things, nothing working yet but I have done some more research.
I need to sort out my php script to properly get the data and update my mySQL databse.
Then when i'm using javascript (thats what i'm using to make use of the data i get) i just need to call the function to refresh the database. what would be the best way of calling it, do i need to set up some sort of timer?
Was This Post Helpful? 0
  • +
  • -

#3 KuroTsuto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: PHP ssh

Posted 19 January 2012 - 09:09 PM

Hey my man!

I must admit you've got me somewhat confused - let me see if I've got this straight:

You wish to create a web-page that, once visited, uses SSH to retrieve data from a remote computer. The webpage would use Javascript to periodically prompt the PHP server to poll data from the remote system and save it in the database, correct?
Was This Post Helpful? 0
  • +
  • -

#4 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 21-January 10

Re: PHP ssh

Posted 19 January 2012 - 09:26 PM

yes thats it.

sorry if my posts where confusing i've been at this awhile and i'm fairly confused myself.

Do you have any pointers or tips?

Thanks
Was This Post Helpful? 0
  • +
  • -

#5 KuroTsuto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: PHP ssh

Posted 19 January 2012 - 10:01 PM

Certainly!!

First off, a recommendation. Where are you planning to run this PHP script? If you'd like the script to be in constant communication with the remote system and the database, I'd recommend writing a PHP script for the command line (if you have access - webhosts typically don't provide you with access to the PHP command line if that's where you're thinking your script will reside). In this manner, when you executed the PHP script it would run as a straight-up process that could maintain a consistent connection to both the remote system AND the database such that it could poll and save data as need be.

That said, if you do not have access to the PHP command-line or are otherwise set on using a web-script, here are my thoughts. Here's a rough overview of the execution from my perspective:

  • You request your PHP script via your web-browser
  • Your PHP script Secure Shells into the remote computer and runs a command
  • The remote computer executes the command and returns the result to the PHP script
  • The PHP script disconnects from the SSH session
  • The PHP script connects to the database if the result is valid
  • The PHP script saves the result to a database
  • The PHP script disconnects from the database
  • The PHP script returns the result in a webpage to your browser
  • Your web-browser executes Javascript to call the script again


FRONT-END
Alright, so my primary consideration here is that the PHP script never needs any input from you or your web-browser, save for the request. In essence, this means that you could simply call a timer in Javascript to refresh the page.

But on a brief tangent, you could actually pull off an incremented page refresh with an HTML meta tag. It's been a while since I've checked the compatibility so it might not work in every browser, but a meta refresh looks something like
<!-- place this in the <head> section of your webpage. change CONTENT to the number of seconds you'd like to wait before refreshing -->
<META HTTP-EQUIV="refresh" CONTENT="15">


In Javascript, you can use the setTimeout("expression", milliseconds) function to execute code x number of milliseconds from when its called. So the Javascript equivalent of the above meta tag would be
<script>
setTimeout( "location.reload()", 15000 );
</script>



That said, you'll be generating a fair bit of overhead by sending request and response headers back and forth constantly. Given a web-page PHP & web-browser approach, your most efficient option would be to make an AJAX request every x seconds such that the browser needn't reload the page every time.

If you'd like, I can give you an example using the jQuery Javascript library, but know that if this is the extent of your project, including the jQuery library would probably be entirely overkill. You can execute AJAX without jQuery, however I am not familiar with the syntax.

What else can I help you with? :)
Was This Post Helpful? 2
  • +
  • -

#6 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 21-January 10

Re: PHP ssh

Posted 19 January 2012 - 10:23 PM

Well that was an impressive reply, thanks :smile2:

I'm doing all this locally so I have full access to the server (my laptop).
But I would rather the web based solution as i could actually use it later on a real web server.
There's not much more to the project but I dont know much about jQuery so i might as well have a look and try it out.
Do you know much about reading from devices in linux? I was going to try get the php script to try read from a device rather than a file.

Thanks for the help
Was This Post Helpful? 0
  • +
  • -

#7 KuroTsuto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: PHP ssh

Posted 19 January 2012 - 11:01 PM

Well at my university we usually SSH into our department's Linux servers to work on or submit homework, so I'm adequately familiar with both SSH and Linux environments, but communicating with PHP over an SSH connection is another matter entirely!

It looks like the most simple method would be to use the PECL SSH2 extension. I don't believe you'll find it installed by default on your PHP installation (it's definitely not in mine), but you never know. You can run a script containing the function phpinfo() to view your current PHP configuration. Searching for SSH on the page will let you know ;)

Addendum:
Researching the extension further, it appears that there have only been beta releases for like the last 7 years, which likely means no PHP distro includes it by default. Installation requires the PEAR Installer as well.

Addendum to the Addendum:
Sorry for my erratic postings now, but I've found myself in unfamiliar territory! It looks like apart from the PECL package, PHP's not too adequate at communicating via SSH. You could write your own implementation with PHP Sockets (which I believe requires another extension), but I did find this PHP implementation of SSH in a convenient library (haven't ever used it though).

This post has been edited by KuroTsuto: 19 January 2012 - 11:15 PM

Was This Post Helpful? 0
  • +
  • -

#8 KuroTsuto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: PHP ssh

Posted 19 January 2012 - 11:34 PM

Ok, re-read this entire thread and realized I've brought you full-circle - you were already using the PECL extension. Did the code you originally posted function at all?
Was This Post Helpful? 0
  • +
  • -

#9 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 21-January 10

Re: PHP ssh

Posted 19 January 2012 - 11:56 PM

yeah the code works, it just displays whatever is in the file on the webpage.I used this site to get the ssh working.
The plan was to save the device data to file and then use ssh to get it but if there was a way to access the device directly it would be great. I've heard of serial over tcp/ip but would it be possible to tunnel it over ssh?
Was This Post Helpful? 0
  • +
  • -

#10 KuroTsuto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: PHP ssh

Posted 20 January 2012 - 12:20 AM

Ah alright - now I'm finally with you, I think.

As far as I know, you'd be pretty hard-pressed to read and interpret a device's registers by shell-scripting alone.

What I would do is write a quick C program (as I see that it's listed in your profile ;)) that reads the device registers for you, parses them to meet your needs, then dumps the result to stdout. That way you could simply execute the binary over the SSH connection and it would return whatever the binary dumped to stdout.

If the device in question already has some sort of drivers that communicate with it on the linux system, there's a chance that you could use the devices driver's to get the information you need instead of writing a custom program.

The only problem that I can foresee with this method would be if you wanted to capture ALL of the data that the device is generating. If this is the case, your program would need to run as a process and collect data either simply in memory or a file on disk or a database of some sort, then dump everything it's collected when prompted over the SSH connection and clear the logging buffer.

Yet Another Addendum:
I'm going to go crash out, but I'll check on this thread in the morning!

This post has been edited by KuroTsuto: 20 January 2012 - 12:25 AM

Was This Post Helpful? 1
  • +
  • -

#11 JackOfAllTrades  Icon User is online

  • No Sugar Coding Here!
  • member icon

Reputation: 4681
  • View blog
  • Posts: 20,360
  • Joined: 23-August 08

Re: PHP ssh

Posted 20 January 2012 - 08:05 AM

Sounds like you're working on something similar to what this fellow is doing, so maybe something there would be helpful?
Was This Post Helpful? 0
  • +
  • -

#12 compactbrain  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 31
  • Joined: 21-January 10

Re: PHP ssh

Posted 21 January 2012 - 11:28 AM

Heres the code so far, all working. I had a look at the other thread didnt see much the would be useful to me. I want to read from a gps and either save to file or send directly. I am making the assumption that the gps sends data like "55,12,33.462;23,4,2.268" just for ease. So if I had a gps at /dev/ttyS2 how would i read from that. KuroTsuto suggested a c program to read the device registers but thats new to me and would appriciate any tips.
I'm using Gmaps for the front end of this project.
<?php
require("dbinfo.php");
if($ssh = ssh2_connect('127.0.0.1', 22))//If it connects 
{
    if(ssh2_auth_password($ssh, 'user', 'pass'))//User and password to use 
    {
        $stream = ssh2_exec($ssh, 'cat /home/jason/Desktop/test');//command to execute
        stream_set_blocking($stream, true);
        $data = '';
        while($buffer = fread($stream, 30))//read from stream 
	{
        $data = $buffer;
        }
	$latlng = explode(";", $data);
	echo $latlng[0]; //output results
	echo "</br>";
	echo $latlng[1];
	$lat = explode(",", $latlng[0]);
	$lng = explode(",", $latlng[1]);
	echo "</br>";
	$Declat = round($lat[0]+((($lat[1]*60)+($lat[2]))/3600),6);
	$Declng = round($lng[0]+((($lng[1]*60)+($lng[2]))/3600),6);
	echo $Declat;
	echo "</br>";
	echo $Declng;
        fclose($stream);//close stream
    }
	// Opens a connection to a MySQL server
	$connection=mysql_connect (localhost, $username, $password);
	if (!$connection) {
	  die('Not connected : ' . mysql_error());
	}

	// Set the active MySQL database
	$db_selected = mysql_select_db($database, $connection);
	if (!$db_selected) {
	  die ('Cant find db : ' . mysql_error());
	}
	// Insert new row into table
	$query = "INSERT INTO markers(lat,lng) VALUES ($Declat,$Declng)";
	$result = mysql_query($query);
	if (!$result) {
	  die('Invalid query: ' . mysql_error());
	}
}
?>

Was This Post Helpful? 0
  • +
  • -

#13 KuroTsuto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: PHP ssh

Posted 22 January 2012 - 05:02 PM

View Postcompactbrain, on 21 January 2012 - 06:28 PM, said:

I want to read from a gps and either save to file or send directly. I am making the assumption that the gps sends data like "55,12,33.462;23,4,2.268" just for ease. So if I had a gps at /dev/ttyS2 how would i read from that.

Do you have the datasheet for your GPS device on-hand, or perhaps a part number from which we could find a datasheet from? That would be the easiest way in which we could deduce the correct manner in which to communicate with the device!

Also I believe that you want this
$data = '';
        while($buffer = fread($stream, 30))//read from stream 
	{
            $data = $buffer;
        }
	$latlng = explode(";", $data);


to be this
$data = '';
        while($buffer = fread($stream, 30))//read from stream 
	{
            $data .= $buffer;
        }
	$latlng = explode(";", $data);


Correct me if I'm wrong, but I believe that the $data variable in the first code box will be overwritten with each new iteration of $buffer rather than being appended to!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1