I have written a small script that issues a series of commands via write() to a linux machine, with a 5 second sleep() between each one. The exact same commands work when entered manually but despite being connected successfully, do not seem to work when used from a PHP script.
As this is the case, I am curious if using read() is absolutely necessary prior to issuing a write() command?
<?php
include('Net/SSH2.php');
$serverhostname = "IP_HERE";
$ssh_username = "root";
$ssh_password = "PASS_HERE";
// Establish new SSH2 Connection
$connection = new Net_SSH2($serverhostname, 22);
if($connection->login($ssh_username, $ssh_password))
{
echo "LOGGED IN! </br>";
sleep(5);
$result = $connection->write('en PASS_HERE\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('configure terminal\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('interface ve 110\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('port-name Test_Brett\r\n');
echo "RESULT: " . $result . " </br>";
}
else
{
echo "SSH Connection Failed. Check that the remote host is online and accepting connections!";
}
?>
UPDATE
$result = $connection->write('en PASS_HERE\n');
$result = $connection->write('configure terminal\n');
$result = $connection->write('interface ve 110\n');
$result = $connection->write('port-name Test_Brett\n');
$connection->setTimeout(5);
echo $connection->read();
I just did this:
$connection->write("ls -la\n");
$connection->write("pwd\n");
$connection->setTimeout(5);
echo $connection->read();
And it seemed to perform the commands just fine without a read() between the two write()'s. But it could be that a read() has to be done, even if just once, at the end.
What I'd do if I were you is, instead of doing sleep(5) do $connection->setTimeout(5); $connection->read();. You can throw away the return value of read(). If you knew what to expect back you could just do $connection->read('pattern'), which would be faster, but if you don't, I'd do the $connection->setTimeout(5); route just to be on the safe side.
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'm using iTunes API Search and Advanced Custom Field WordPress plugin so the wp author can add a mac app id to a custom field and the implanted iTunes Search API above will add all the other information of app automatically in the wp post. and when app information updated my wp post will have the updated info like last verion number app size and ...
but the problem is my own wrote review and guide of any verion of any app inside my website and it need to be updated manually.
for example i have added a post for version 3.7.1 of "Things 3" mac app using method above to my WordPress and i have reviewed this version with my own description and hand-wrote in the post.
now i need to get notified when ever this app gets a new version or update so i can update my review and add some text for new version inside the post as well.
is there any way or method you guys can think of, so i can get notified when ever an app i have reviewed in my site gets an update ?
i really appreciate any way or taught !
Thanks.
There is no native API to do what you're asking.
However, with a little coding I believe you could use the RSS feed of the application to then create something to notify you on a change.
See Example for the App HomeScan
https://itunes.apple.com/lookup?id=1380025232
ID= YOURAPPID
I believe this should give you some general direction to do what you need.
This is a reply to our comment history in the other answer.
#erfanMHD, there are a number of ways to really do this. You don't have to do it in javascript. This isn't really something someone can give you an easy code snippet for since it requires a few additional things and is generally frowned upon in StackOverflow.
You'll need somewhere to store the localVersion of the application of the review you last wrote. In the example I wrote below I used a simple MySQL database to hold the local version. You'll also need to figure out how you want to display the data. I know you can add stuff to the wordpress dashboard but this isn't something we can show you how to do via StackOverflow.
However, below is a very simple (JUST FOR REFERENCE) purposes only on how one could achieve what you're trying to do. However this is just an example to guide you along the process.
For this demo, you'll need a MySQL database with a DBName of test and and a record created called application_version with 3 rows. ID, Name, Version.
<?php
$servername = "localhost"; // Your MySQL Server
$username = "root"; // Your MySQL Username
$password = "password"; // Your MySQL Password
$dbname = "test"; // The name of your MySQL database
$id = "904280696"; // The ID of the applicaiton you're wanting to check
function search($searchTerm){
// Construct our API / web services lookup URL.
$url = 'https://itunes.apple.com/lookup?id=' . urlencode($searchTerm);
// Use file_get_contents to get the contents of the URL.
$result = file_get_contents($url);
// If results are returned.
if($result !== false){
// Decode the JSON result into an associative array and return.
return json_decode($result, true);
}
// If we reach here, something went wrong.
return false;
}
function updateVersion($id, $name, $version) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Save the Version information
$sql = "UPDATE application_version SET name='" . $name . "', version='" . $version . "' WHERE id='" . $id . "'";
echo $sql;
echo "<br>";
// Run the Insert into MySQL
if ($conn->query($sql) === TRUE) {
// Print On Success
echo "Record Updated Successfully";
echo "<br>";
} else {
// We dun goofed
echo "Error: " . $sql . "<br>" . $conn->error;
echo "<br>";
}
$conn->close();
}
function getLocalVersion($id) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM application_version WHERE ID = " . $GLOBALS['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Found Application ID Entry in database";
echo "<br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Version</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["version"]."</td></tr>";
$GLOBALS['storedVersion'] = $row["version"];
}
echo "</table>";
echo "<br>";
} else {
echo "No Application ID Entry found in database";
echo "<br>";
}
$conn->close();
}
// Search for your requested ID
$searchResults = search($GLOBALS['id']);
$currentVersion = '0.0.0';
$storedVersion = '0.0.0';
$appName = 'null';
// Loop through the results.
foreach($searchResults['results'] as $result){
// Pass the current version to variable
$currentVersion = $result['version'];
$appName = $result['trackName'];
// Get the current version or what ever else information you need
echo 'Current Version: ' . $currentVersion;
echo "<br>";
echo "<br>";
}
// Get Local Version from database
getLocalVersion($id);
if ($currentVersion > $storedVersion) {
echo "You have an old version friend";
echo "<br>";
// Write what you want it to do here
updateVersion($id, $appName, $currentVersion);
} else {
echo "You're all up to date";
echo "<br>";
// Write what you don't want it to do here
}
?>
Again, this is just quick and dirty. You'd want to do a lot of additional checks and balances. One I see right off the bat would be in the check for inserting.
I've made a simple PHP script to update a mysql database. When I run this script as a standalone script, it works as expected. However when I call this script from within an AngularJS Service it does not do the job.
This is my script:
<?php
include('../connection/connection.php');
$data = json_decode(file_get_contents("php://input"));
date_default_timezone_set('CET');
$cursist_id = $data->cursist_id;
$id_ggv = $data->id_ggv;
$cursist_id = intval($cursist_id+1);
$id_ggv = intval($id_ggv+1);
try {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = " UPDATE crskrt_ggv
SET cursist_id = '$cursist_id'
WHERE id_ggv ='$id_ggv' ";
$db->exec($q);
//echo json_encode($id);
}
catch(PDOException $e)
{
echo $q . '</br>' . $e->getMessage();
}
echo "cursist_id: ". $cursist_id;
echo "id_ggv: " . $id_ggv;
echo $q;
When I check the network tab in the developers console, I can see that the right variables are returned. However, the database is not updated.
Anyone have any idea?
I am trying to authenticate users' login against LDAP(Server is Mac El Capitan).
I can successfully connect and bind to the ldap server.
I can search and sort the result.
But when I perform "ldap_get_entries",I received "Zero" entry.
I've tried everything from StackOverFlow to Google's second page.
Any Suggestions or idea why this might be happening?
MY CODE -
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$usernameLogin=$_POST['email'];
$passwordLogin=$_POST['password'];
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
echo "User name is ".$username;
echo "</br>";
$ldapUser = "uid=xxxxxx,cn=users,dc=dns1,dc=xxxxxxxx,dc=com";
$ldapPass = "xxxxxxxxxxx";
$url = "ldap://dns1.xxxxxxx.com:389";
$ldap = ldap_connect("$url") or die("Could not connect to LDAP server.");
$baseDN = "cn=users,dc=dns1,dc=xxxxxxxxx,dc=com";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS,0);
$bind = ldap_bind($ldap, $ldapUser, $ldapPass);
if($bind) {
echo "Connected To LDAP";
echo "</br>";
$filter="(sAMAccountName=$username)";
echo "Filter = ".$filter;
echo "</br>";
$result = ldap_search($ldap,$baseDN,$filter) or die("Could not search.");
echo "Result = ".$result;
echo "</br>";
$sort = ldap_sort($ldap,$result,"uid");
echo "Sort = ".$sort;
echo "</br>";
$number = ldap_count_entries($ldap, $result);
echo "Count Entries = ".$number;
echo "</br>";
$info = ldap_get_entries($ldap, $result);
echo "Data for " . $info["count"] . " items returned:<p>";
echo "Info = ".$info;
echo "</br>";
echo '<pre>'; print_r($info); echo '</pre>';
echo "</br>";
$fentry= ldap_first_entry($ldap, $result);
echo "First Entry = ".$fentry;
for ($i=0; $i<$info["count"]; $i++)
{
if($info['count'] > 1)
break;
echo "<p>You are accessing <strong> ". $info[$i]["sn"][0] .", " . $info[$i]["givenname"][0] ."</strong><br /> (" . $info[$i]["samaccountname"][0] .")</p>\n";
echo '<pre>';
var_dump($info);
echo '</pre>';
$userDn = $info[$i]["distinguishedname"][0];
}
ldap_close($ldap);
}
else{
echo "Cannot Connect To LDAP.";
}
}}
?>
I can connect - bind - search But "ldap_get_entries()" returns zero.
First: You can skip the or die "Could not connect to LDAP Server" as that will almost never happen. ldap_connect only checks the parameter for syntactical correctness and does not actually connect to the server. The actual connection happens on the first call to the server which usually is ldap_bind. That's why conncetion issues often surface on ldap_bind and not on ldap_connect.
Second: Where did you get samAccountName from? That's a field that's usually used by ActiveDirectory. In Apples OpenDirectory the user is usually identified by the uid-attribute. So your filter should be sprintf('uid=%s', $username).
Third: I doubt that only Users in the group "Open Directory Administrators" are allowed to bind agains the LDAP. They for sure are the only ones allowed to edit the directory but every other user can bind as well.
Fourth: ldap_sort is deprecated by now. It's not sorting on the server side but on the client side. So only the returned results are sorted. When you have paged results that means that - even though you sorted the result - there still will be entries that would fit right in between your results. I'm currently working on a way to use server-sided sorting but that relies on the feature to be available on the server. So you can use ldap_sort but you can also implement your own sorting on the result set.
So change the filter to uid=$username and you'll get the expected results. The mail attribute might also contain the full email-address and might therefore then fail! You can also adapt the filter to search more than one field. Have a look at this slide for short examples.
Solved it. I used "mail" instead of "sAMAccountName".
Here's the details -
1 ) From
$filter="(sAMAccountName=$username)";
to
$filter="(mail=$username)";
2 ) From
$sort = ldap_sort($ldap,$result,"uid");
to
$sort = ldap_sort($ldap,$result,"mail");
That's it.
Lessons learn from here -
Use "LDAP Admin Tool" or some sort of LDAP Tool to understand the structure of your LDAP environment before jumping into coding. Big lesson learnt.
I recently had my eureka moment when I finished my first database connection. After closing my browser and reopening the html form, the output suddenly changed to code instead of the database values?
HTML form:
<form action="formulier3.php" method="post">
Hoogte: <input type="text" name="height"><br>
Breedte: <input type="text" name="width"><br>
<input type="submit">
</form>
PHP Page:
<?PHP
$user_name = "root";
$password = "root";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM price WHERE height = " . $_POST["height"] . " AND width = " . $_POST["width"] . "";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['ID'] . "<BR>";
print $db_field['value'] . "<BR>";
print $db_field['height'] . "<BR>";
print $db_field['width'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
This is my output:
"; print $db_field['value'] . "
"; print $db_field['height'] . "
"; print $db_field['width'] . "
"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?>
Does anyone knows what's going on here?
Thank you in advance!
Somehow your server has stopped processing your php pages through the php processor (apache module or fastcgi or whatever).
What you see is the effect of presenting your php code as html. The fact that you don't see all your code but rather a small part of it, it is because the part from the first < (in <?php) until the first > (in print $db_field['ID'] . "<BR>"; is being parsed by the browser as an html tag and so it is not printed. If you look at the page source you'll see the full php code.
So there has been some server-side change that has produced that php files are directly server to the browser instead of parsed by the php engine.
One possible cause, is that you are developing in your local computer and when it worked you typed in your browser something like http://localhost/your_page.php but now you are opening the php file directly from the filesystem, so the browser shows something like file:///xampp/htdocs/your_page.php. You should always open your php pages through the web server (ie. using http://localhost/....) and never by double-clicking on the file in the file explorer.