ssh connection from php - php

I need to ssh to the server using the username user has entered on my webform.
How can this be done?

If what you mean is, "How do I connect via SSH from my website (to another server)", then you can do this with the PECL ssh2 library.
See:
http://pecl.php.net/package/ssh2
Walkthrough (untested): http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/

At first, there are no PuTTy commands. These are shell commands.
To run PHP script in shell, you need to use php-cli:

maybe you could use Command Line Scripting in PHP, it depends on what you want. http://php.net/manual/en/features.commandline.php

I am not sure but I think(correct me if I am wrong) that you want to click somewhere on a link on the webpage and open putty(on the user's computer) to connect to a server.
You can configure Putty to handle ssh:// links. How to do it you can find out here.
When that is configured all you have to do is to have a link similar to this:
Click here to connect
Have in mind that this will work only on systems that are configured to handle the ssh:// link type
I hope that this answers your question.

This is how you use putty via PHP (not dependent of cli). Note that the passwords are not protected and that an interactive ssh session would be much more involved. However, HTTPS and mcrypt (if needing to store passwords and/or bash scripts) can make this a safe solution.
<?php
// EDIT: added escapeshellcmd() to following vars
$user = escapeshellcmd($_POST['user']); // username
$host = escapeshellcmd($_POST['host']); // domain
$pass = escapeshellcmd($_POST['pass']); // password
// create a string that will be loaded into a bash file for putty
// String can easily be made dynamically.
$bash_sh = <<<EOF #START OF BASH
\#!/bin/bash
echo "BASH ON SSHD SIDE"
for (( i=1; i<=5; i++ )) # BASH FOR LOOP
do
echo "echo \$i times in bash" #\$i is BASH not PHP, so have to escape
done
EOF; #END OF BASH
// creates a temp file called 'bash.sh' using the bash script above
file_put_contents("bash.sh", $bash_sh);
// executes putty using the args -ssh, -pw, -t, -m
// -ssh tells putty to use ssh protocol
// -pw tells putty to enter the password automaticaly
// -t tells putty to use a psudo terminal.
// -m tells putty read and execute bash.sh once logged in
exec("putty.exe -ssh ".$user."#".$host." -pw ".$pass." -t -m bash.sh");
// delete bash file since it has been sent
unlink('bash.sh');
?>

Related

How to get result from a command executed in PHP on remote SSH server using PuTTY?

I'm trying to execute a command on my Raspberry Pi via SSH and get the result of it in my PHP script on my Windows machine. Currently I can execute the command on my RasPi, but I do not get any results back into the PHP script.
The code I'm Using for this:
<?php
$cmd = "C:\\path_to_putty\\putty.exe -ssh pi#RasPiIP -pw raspberry -m C:\\path_to_test.txt\\test.txt";
$result = shell_exec($cmd);
echo $result;
?>
For sending commands to my RasPi the code works. I have tested multiple times by as example changing test.txt to sudo reboot and it worked as intended.
I'm using PuTTY to send my command (test.txt is currently nfc-list which returns connected Scanners etc not important right here) to the RasPi.
What I want to achieve is that $result contains the returned data when my command is executed.
Is it even possible to do that? If yes how (any help appreciated). If no, are they maybe other ways to approach this?
Addressing the possible duplicate: I am using a Windows Machine and also I'm trying to get the result (of the one command) to reuse in my PHP script. In the other question, user is trying to save the full console log and save it to another file.
First, do not use PuTTY. PuTTY is a GUI application intended for an interactive use. Use Plink, which is command-line/console equivalent of PuTTY intended for command automation. Being a console application, it has a standard output, which can be read in PHP (PuTTY as a GUI application does not have standard output).
With Plink, you can also specify the command on Plink command line, so you do not need to create the test.txt command file.
In any case, there's no way to make PuTTY or Plink separate an output of command only (at least not from a command-line).
But what you can do, is to print some header/trailer to distinguish the start and end of the command output, like:
plink.exe -ssh pi#RasPiIP -pw raspberry "echo start-of-command && command && echo end-of-command"
And then in PHP, you can look for the start-of-command and end-of-command to identify what part of Plink output is really the command output.
In any case, you better use a PHP SSH library to achieve what you want, rather then driving an external application. For example phpseclib. But that's a completely different question.

running ssh -t to spawn a remote screen

On my home network, I would like to run a python script on server2 remotely from server1. Both servers are on the home network. I need to upload a file to server2 and run the python script. The python script takes several hours to complete and so I would like to run it inside a screen on server2. I'm trying to implement this using php and some bash scripting.
My php script on server 1 runs a bash script on the same server. The bash script uses: [ssh -t user#server screen 'sudo python pyth_script.py'] to attempt to run the python script on server2. Please note that I am using the -t option. The bash script also has a scp command to copy a file from server1 to server2. I have used keys to enable ssh commands from server1 to server2 without requiring a password.
When I run the bash script from the command line, it functions perfectly. The screen on server2 is activated and the python program runs inside it. I have run the bash script as the normal user, as root and as www-data (the php script is run through apache and is user www-data). Under any of the users, the bash script works as expected when run from the command line.
When I run the bash script via the php script (click on an html form that fires off the php script), then the scp command works correctly and the file is transferred, however the python script does not run. The output from the php line containing "ssh ... screen ..." returns "Must be connected to a terminal.", but I'm using the -t option and as I mentioned, the bash script runs as expected when run from the command line.
Any ideas what I'm doing wrong?
What is the best way to run a python script remotely using a web interface?
Thanks,
rb3
My guess: ssh doesn't do tty if it, itself, isn't being run in a tty, which exec() probably isn't doing.
man ssh says "Multiple -t options force tty allocation, even if ssh has no local tty" but it's not clear to me what it means by "no local tty".
idk... I'm kinda thinking maybe you ought to use phpseclib, a pure PHP SSH2 implementation. eg.
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('screen 'sudo python pyth_script.py'');
?>
And if you need PTY / TTY check this out:
http://phpseclib.sourceforge.net/ssh/pty.html
That said, keep in mind I'm not a screen expert. Maybe you want to be using nohup and &? Maybe you should tag your question screen too idk.

Using SSH via PHP with different user

I have a PHP file in which upon clicking the submit button, another PHP script is being executed. Within the second PHP script a shell script is being executed in which an SSH connection is being done to another server.
The issue I have is that the SSH connection to another server can only be done by a particular user. However the PHP script is being executed by www-data and for such reason I cannot change user, to the user that needs the ssh connection as it requires a password each time.
I also tried to execute the shell script from the first PHP file but still with no success.
My OS is UBUNTU.
Can this be done, and if yes, how can this be achieved?
Thanks
You can use sudo command. For passing password to it, there is a -S option
Do you have the option (access and rights etc.) of using private/public keys for SSH? If yes, then your second PHP script would contain something like
ssh -l <particular-username> <hostname> -i <private_key_file>
How are you logging in? SSH requires a username. Are you providing www-data as that username or the "particular name" as the username?
If you have or can install sshpass ( http://sourceforge.net/projects/sshpass/ ) you can give that a go, it allows username+password on the commandline, example here:
https://askubuntu.com/questions/282319/how-to-use-sshpass

PHP - execute command as root

I'm trying to execute a command as su from php.
When I put the command in terminal or with php /var/www/script.php it works perfect, but when I open script.php through browser it returns - sudo: no tty present and no askpass program specified
Thanks.
According to this:
ssh does not allocate a tty by default when running a remote command.
Without a tty, sudo cannot disable echo when prompting for a password.
You can use ssh's "-t" option to force it to allocate a tty.
Alternately, if you do not mind your password being echoed to the
screen, you can use the "visiblepw" sudoers option to allow this.
I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS
You can get a real bash shell as root. You can then either trigger your php script or execute the commands directly in bash.
After downloading you would simply use the following code:
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd('yourFirstCommand');
$return2 = $shell->exeCmd('yourSecondCommand');
//the return will be a string containing the return of the script
echo $return1;
echo $return2;
//or if you want to trigger your script as root
$return3 = $shell->exeCmd('php /my/script.php');
echo $return3;
//If your script contains code to make an SSH connection to another server
//there is a much easier way to do that using the project:
$shell = \MTS\Factories::getDevices()->getRemoteHost('ip_address')->getShellBySsh('username', 'secretPassword');

Php : running ssh from Windows to login to a Linux and run a script

Here's my goal :
I have a Windows XP PC with all the source code in it and a development database.
Let's call it "pc.dev.XP".
I have a destination computer that runs Linux.
Let's call it "pc.demo.Linux".
Here's what I've done on "pc.dev.XP" (just so you get the context) :
installed all cygwin stuff
created a valid rsa key and put it on the dest
backup computer so that ssh doesn't
ask for a password
rsync works pretty well this way
If i try to do this on "pc.dev.XP" via a command line :
cd \cygwin\bin
ssh Fred#pc.demo.Linux "cd /var/www && ls -al"
this works perfectly without asking a password
Now here's what I want to do on the "pc.dev.XP":
launch a php script that extract the dev. database into a sql file
zip this file
transfer it via ftp to the "pc.demo.Linux"
log to the "pc.demo.Linux" and execute "unzip then mysql -e "source unzipped file"
if I run on "pc.dev.XP" manually :
putty -load "myconf" -l Fred -pw XXX -m script.file.that.unzip.and.integrates.sql
this works perfectly.
Same for :
cd \cygwin\bin
ssh Fred#dest "cd /var/www && ls -al"
If I try to exec() in php (wamp installed on "pc.dev.XP") those scripts they hangs. I'm pretty sure this is because the user is "SYSTEM" and not "Fred", and putty or ssh ask for a password but maybe I'm wrong.
Anyway I'm looking for a way to automate those 4 tasks I've described and I'm stuck because exec() hangs. There's no problem with safe_exec_mode or safe_exec_dir directives, they're disabled on the development machine, thus exec() works pretty well if I try some basic stuff like exec("dir")
Any idea what I could do / check / correct ?
I'm not sure if this is what you need, but I typically use a construct like this to sync databases across machines:
php extractFromDb.php | ssh user#remote.com "mysql remoteDatabaseName"
This executes the PHP script locally, and pipes the SQL commands the script prints out through SSH straigt into the remote mysql process which executes them in the remote database.
If you need compression, you can either use SSH's -C switch, or integrate the use of your compression program of choice like this:
php extractFromDb.php | gzip -9 | ssh user#remote.com "gunzip | mysql remoteDatabaseName"
You want to do this from PHP running under apache, as in I go to http://myWebserver.com/crazyScript.php and all this happens? Or you just want to write your scripts in PHP and invoke them via cmd line?
If you want the first solution, try running your apache/iss under a different user that has credentials to perform all those tasks.
"if I run on the development PC manually this works perfectly.".
Why not do it like that? When you run that script, I assume you're connecting to the local SSH server on the dev machine. When you do this, you are using the credentials Fred, so everything works. When you run the PHP script, you are right that it is probably running as SYSTEM.
Try either changing the user that apache is running as or use php to connect to the local ssh thereby using alternate credentials.
Here's what I did :
a batch file that :
Calls a php file via "php.exe my_extract_then_compress_then_ftp.php"
Calls rsync to synchronize the source folder
Calls putty -l user -pw password -m file_with_ssh_commands_to_execute
It works like a charm.

Categories