I am trying to do the following.
Have php execute shell commands on our remote servers. This because i would like to be able to install scripts through bash So php is going to execute the bash scripts on the remote server.
The issue is the can't connect to the remote server for some reason. I have tried several way to do this and i have to do with the root and password. Later i can look at encrypting them or something like that, but i can't use a ssh key so that is not going to work. I am pretty new to php part of it so i need some help figuring out hot to connect to remote servers.
the code i am trying right now is
$ip = '37.130.000.00';
$user = 'admin';
$pass = 'xxxxxxxxx';
$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"uptime");
echo $shell;
For some reason this code is giving me the following error
Fatal error: Call to undefined function ssh2_connect() in
How can i make this work or what else should i do to properly connect to the remote servers and this all should be very flexible as we are talking around 100 server who should be able to connect this way.
Thanks for any input.
That function is provided by an optional extension that you don't seem to have installed. Provided you have libssh and other dependencies in your system, get pecl-ssh by executing
sudo pecl install ssh2 channel://pecl.php.net/ssh2-0.11.3
and then restart php-fpm or apache if you're using modphp.
Edit: btw, this question has been asked before and one of the wisest advises I've seen in regards to is was to switch over to a pure php implementation, no pecl extensions whatsoever:
php-function-ssh2-connect-is-not-working
I know this question has been asked before in many different ways but I'm still scratching my head over why I can't get this to work.
Firstly I have two SLES servers setup, these are Server A & Server B which are both running on a small private network which is only accessed by a dedicated team.
Server A is configured as a web server which is running Apache, PHP, MYSQL and ssh all of which are running problem free.
Server B is used to run menial tasks with ssh also installed and activated.
I have created my rsa key on Server A and installed it on Server B which when run at the command line logs me in straight away with out asking for a password. I have repeated this process for both root & nobody accounts on Server A.
I have added this a PHP page to Server A which looks like:
<?php
shell_exec('ssh root#192.162.0.5 ./StartTest.sh');
header("Location: archive.php?page=home");
?>
But when I run it it does not create my folder. If I run this from the command line it works for both (I think both, I can't recall if I did try this for the nobody account on the cli now) root & the nobody account. I even went as far as adding the nobody account to the root group but still no joy.
Have I missed some thing here. All I would like to do is connect from Server A to Server B via php & ssh to execute one command and redirect to a another page on the web site.
Any help would be graciously appreciated as my paracetamol stock is running low.
The built-in SSH support George Cummins speaks of is non-existent. It is an extension to PHP that's not included by default. It has to be compiled separately and is notoriously difficult to setup / use. My recommendation would be to use phpseclib, a pure PHP SSH implementation:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
You said "I have added this a PHP page", so I will assume that you are executing this script via your web server, rather than as a standalone script.
As such, the script may not be running from the directory you expect. You should use absolute (rather than relative) paths to ensure that the script finds the ssh binary and your script:
shell_exec('/path/to/ssh root#192.162.0.5 /home/yourdirectory/scripts/StartTest.sh');
You will also need to confirm that the webserver user had permissions to execute ssh and the StartTest.sh script.
I know that I'm too late at this answer but maybe can help someone:
To use shell_exec and ssh you need to add as parameter to ssh these
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=quiet
So the command doesn't try to create .ssh folder and you have a clear output without log of ssh
I have a shellscript with connects to a a different machine with ssh and a key so it does not need the username and password.
When i run this script from commandline it works fine.. but when I run this script from php shell_exec it does not work.
If I make an ssh connection with PHP and run the script as my own user it does work.
Now for my question :D
Is there a way to just running the script in shell_exec from php without making an connection over ssh as a different user?
Did you specify the private key file correctly?
If you are using Ubuntu or Debian the web server is running with the user name www-data. For other systems please check the web server configuration for the user name. You can simply test if this user (and your php web application) is able to do the SSH connection.
1) Become the user of your web server
sudo su www-data
2) Try connecting the remote host
ssh remoteUser#remoteHost
If you will get connected without entering a password there must be a different problem. If you have to enter a password, the key files were stored for a different user - not for www-data. You have already configured SSH to use the key. Do the same for your local user www-data and it will work.
It seems ssh connection does not work with shell_exec. If i run the shellscript under ssh2_exec it does seem to work.
Which is a little strange as the ssh connection is made in the script file with a public and private key.. I would assume this would just run :s
The webserver is allowed to execute the file, as there are other command in there who work as expected.
I have a strange issue. I'm trying to write a simple php webpage on my server, but mysql_connect() doesn't connect to any server, either local or otherwise. Here's where it gets strange. If I take the same php script and run it from the commandline, the script works. phpinfo() indicates that both the file (being run by apache) and the commandline (run as root) are calling the same version of php, mysql is loaded, and the php.ini is the same.
Furthermore, I'm running a MediaWiki installation on this same server, and it's using the mysqld installed locally and works just fine, so I'm completely at a loss as to why the code isn't working. The error I receive on runtime:
Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (13)
(The IP is x'd out for the privacy of the owner of the server I'm connecting to)
What operating system are you trying to connect from? It sounds like it may be an SELinux issue.
With SELinux, you can usually allow apache to make network connections by using
/usr/sbin/setsebool httpd_can_network_connect 1
OR
/usr/sbin/setsebool httpd_can_network_connect true
An operating system without SELinux may have a similar protection mechanism.
Check basic network connectivity. ping xxx.xxx.xxx.xxx from the webserver. If that doesn't work, check the network configuration on both ends.
Try running mysql from the webserver: mysql -h xxx.xxx.xxx.xxx -u user -p If that can't connect, track the cause: it could be a SELinux issue on either end (check the security log), or maybe there is an alias in /etc/hosts? Also enable verbose messages with -v -v -v on the mysql command line.
Check that the user is allowed to log on using the user administration feature of mysql.
I'd like to establish an ssh tunnel over ssh to my mysql server.
Ideally I'd return a mysqli db pointer just like I was connecting directly.
I'm on a shared host that doesn't have the SSH2 libraries but I might be able to get them installed locally using PECL.
If there's a way that uses native commands that would be great.
I was thinking something like this, but without those libraries it won't work.
$connection = ssh2_connect('SERVER IP', 22);
ssh2_auth_password($connection, 'username', 'password');
$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);
$db = new mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
'dbname', 3307, $tunnel)
or die ('Fail: ' . mysql_error());
Anyone have any ideas? I'm running a shared CentOS linux host at liquidweb.
Any thoughts on making the tunnel persistent? Is it possible to establish it with another script and just take advantage of it in PHP?
Thanks.
I would use the autossh tool to create a persistent ssh tunnel to your mysql database. Then all you have to do in your PHP code is point it to localhost.
You can test this (without automatic restart) by doing:
ssh -L 3306:localhost:3306 user#domain.com
Setup a ssh key so that you don't need to use passwords, and tweak the .ssh/authorized_keys file on the mysql system to only allow it to be used for port forwarding.
For more info on ssh tricks see Brian Hatch's excellent series on SSH and port forwarding.
The tunnel must be keep open during the course of the SQL action(s). The following example from RJMetrics explains:
Here's the generic SSH command syntax:
ssh -f -L bind-ip-address:bind-port:remote-ip-address:remote-port \
username#remote-server [command] >> /path/to/logfile
Here's how to securely establish a remote database connection in just 2 lines of PHP code:
shell_exec("ssh -f -L 127.0.0.1:3307:127.0.0.1:3306 user#remote.rjmetrics.com sleep 60 >> logfile");
$db = mysqli_connect("127.0.0.1", "sqluser", "sqlpassword", "rjmadmin", 3307);
We use the shell_exec() function to create the tunnel with a 60 second opening window, and then use the mysqli_connect() function to open a database connection using the forwarded port. Note that we must use the "mysqli" library here because mysql_connect() does not allow us to specify a port and mysql_* functions are deprecated.
sleep 60: When it comes to tunnel connections, we basically have two options: leave the connection open all the time or open it and close it as needed. We prefer the latter, and as such we don't specify the -N option when establishing a tunnel, which would leave it open until the process is manually killed (bad for automation). Since -N is not specified, our tunnel will close itself as soon as its SSH session isn't being used for anything. This is ideal behavior, except for the few seconds between when we create the tunnel and when we get a MySQL connection up and running via the tunnel. To buy us some time during this period, we issue the harmless sleep 60 command when the tunnel is created, which basically buys us 60 seconds to get something else going through the tunnel before it closes itself. As long as a MySQL connection is established in that timeframe, we are all set.
I tried it by doing SSH both by root credentials and and public private key pair. It allows me to conect through command line but not through PHP code.
I also tried by creating a tunnel (by using SSH2 functions), and running shell commands from PHP code (system, exec, etc.); nothing worked.
Finally I tried SSH2 function to execute shell command and it finally worked :)
Here is my code, if it helps you:
$connection = ssh2_connect($remotehost, '22');
if (ssh2_auth_password($connection, $user,$pass)) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
$stream=ssh2_exec($connection,'echo "select * from zingaya.users where id=\"1606\";" | mysql');
stream_set_blocking($stream, true);
while($line = fgets($stream)) {
flush();
echo $line."\n";
}
Try this if want to use PHP functions specifically.
It is possible, but why? It's more complicated than it needs to be, and error prone.
Can you not run the database locally? If not, can you not use something like SQLite, XML files or something else that doesn't require a separate server daemon?
You really do not want to initialise the tunnel inside the PHP scripts. Initialising an SSH tunnel takes a long time (can easily be a second or two), so that will mean every page that connects to the database will have a 2 seconds delay while loading..
If you have to do this (which I strongly recommend against), the best method would be to have a script that maintains the connection in the background..
Setup a SSH keypair. Then using autossh, or a simple script which would execute the required SSH command, wait till the process died and start it again. It could be more intelligent and try and run a command every 10-20 seconds, reconnecting if it fails.
Using the SSH keypair, you wouldn't have to hardcode the remote users password in the script. I would recommend limiting what the remote user can do (by using a dedicated tunnel user, and giving it a restricted shell, see this question)
In short, I would strongly suggest trying SQLite first, then see how feasible it to store data using XML files, then try bugging your web-host about getting a local MySQL server, then look into the SSH tunnelling option.
Eric,
I think you are out of luck on this one. You can either use the ssh extension in your PHP code, or if you have access to the server, you could try to create a ssh tunnel on the command-line.
You probably need special permissions to do that, though. It also looks like you don't have ssh access to this hosting account.
--Joao
I think your best bet is to find a different hosting provider; I suggest a VPS solution (Virtual Private Server) which gives you full control over your web host. THat way, if you don't like the default configuration, you can upgrade it yourself.