Executing shell commands via PHP? - php

I am trying to ssh to a remote server to check to see if a specific file exists.
I am able to ssh in the command line but whenever I try to with my script it does not return anything / I have to type "exit" and hit enter to get back to the command line.
Steps:
ssh root#website.com
cd ..
ls ATMEXTRACT
I put all of these commands into ouputs so they look like this:
$output = shell_exec("ssh root#website.com");
$ouput1 = shell_exec("cd ..");
$ouput2 = shell_exec("ls *ATMEXTRACT*");
echo($output2);
I am confused as to why this works directly in the command line but is failing in the script. Any help is much appreciated

Here's what you do interactively:
Run ssh root#website.com in the current shell
Input cd .. in ssh
Input ls *ATMEXTRACT* in ssh
Input exit in ssh, which now exits
Find yourself back in your original shell
Here's what you do in your script:
Run ssh root#website.com in a new shell and exit it
Run cd .. in a second shell and exit it
Run ls *ATMEXTRACT* in a third shell and exit it
You could try to open and interact with an ssh command, but you can also just save yourself the trouble and use ssh's command line feature for specifying the commands to run:
$output = shell_exec("ssh root#website.com 'cd .. && ls *ATMEXTRACT*'");
Be aware that this is likely to fail from a PHP website script because you need to set up an authentication mechanism. This true even if ssh root#website.com connects without a password when you manually log in to the web server and try it.

I would recommend you to use ssh2 module of PHP. This will help you to connect any remote server which is reachable through appropriate SSH PORT.
You will need to check, if few modules like OpenSSL and ssh2 are installed on your host server.
if not please check this https://ehikioya.com/install-ssh2-php/ and install above modules.
once these modules are installed and enabled.
follow this code.
$server="website.com";
$server_pwd="Password";
//creating connection using server credentials
$connection = ssh2_connect($server, 22);
//authenticating username and password
if(ssh2_auth_password($connection, 'root', $server_pwd)){
echo "connected"
}else{
echo "could not connect to server";
}
ssh2_exec($connection, "ls /FULL_PATH/ATMEXTRACT"); //run your command here

Related

Find if current user's public SSH key is authorized for SSH on remote host using PHP or Bash

I need a PHP script to execute a script on a remote system.
It's working great where the current user is authorized on the remote system.
However, before running the script, I want to check if the public key on the local system is authorized in the authorized_keys file on the remote system.
Is there a way to do this? I tried executing something like this:
ssh -o ConnectTimeout=5 -o PubkeyAuthentication=yes -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no -o BatchMode=yes -o ChallengeResponseAuthentication=no host.address.com 2>&1 | grep "Permission denied"
but it just hangs the console when authentication is successful.
You can use command like this and grab the exit code:
ssh -q host exit
This will contact host host and execute command exit. Return code 0 mean everything is fine
If you want to grab exit code execute after ssh
EXIT_CODE=$?
and then check the variable

How to execute a local Shell Script with SSH commands on server?

I want to run a local shell script that have SSH commands on the server using PHP. And inside the script i am using ssh to run a command like ls -lart and save the result on a log file in the server, and then using scp to copy the remote file to my local host. Something like this:
/// my_local_shell.sh
#!/bin/bash
host=$1
user=$2
port=$3
ssh -p $port $user#$host 'ls -lart >> /home/remote/file.log'
scp -P $port $user#$host:/home/remote/file.log /home/local/file.log
If i run the script using the terminal user#local_host:~$ ./my_local_shell.sh everything works just fine. But if i use shell_exec() to execute the script using PHP like this:
/// index.php
$output = shell_exec("my_local_shell.sh 192.168.1.1 root 2222");
echo <pre>$output</pre>;
Nothing is printed on screen and the SSH commands inside the file are not executed.
I know I can use ssh2_shell(), but by using it I would have to send the commands inside the PHP, and it's not what i want.
I already gave the permissions needed to index.php and my_local_shell.sh
Any ideas how I can do this?
Apparently scp uses some sort of ncurses that you can't capture, so you could add the -v flag to your scp command in the shell script
scp -v -P $port $user#$host:/home/remote/file.log /home/local/file.log
or alternatively, since scp returns 0 on success you could write
scp -P $port $user#$host:/home/remote/file.log /home/local/file.log && echo Success
As for the PHP please check you have PHP opening and closing tags and correct your echo statement
echo "<pre>".$output."</pre>";

Phpseclib SSH2 - How to Suppress Sudo Prompt output on Exec

Been wrestling with this one for a little bit. I'm currently working on a PHP application that connects to a custom API as well as performs changes to a server via Phpseclib's SSH2 library.
$ssh = new Net_SSH2($server_name);
if(!$ssh->login("username", "password")) {
$result['result'] = 'ERROR';
$result['message'] = 'Login failed';
} else {
$result['propertyFolderDeleted'] = $ssh->exec("cd /var/www/sites; echo 'password' | sudo -S /usr/local/bin/delete_property.sh -sc $company_name -sp $property_name");
return '{"data":'.json_encode($result).'}';
}
Output generated:
{"data":{"propertyFolderDeleted":"[sudo] password for portals: "}}
Pretty straight-forward, my application uses SSH2 to exec some Bash scripts I have in place on my server. For the most part this works flawlessly, but for some reason, exec-uting this one Bash script ('delete_property.sh') outputs the sudo password prompt as a result.
I've tweaked my request and executing my Bash script via command-line (in Putty) no longer outputs the prompt text upon completion of the Bash script.
Why isn't this the case when using Phpseclib?
Just add the user to the sudorious file.
Open the terminal.
Type "sudo visudo"
Add at the end of the file "youruser ALL=(ALL) NOPASSWD:ALL" and just replace "youruser" with your real user.
Save and exit.
Now every one command with your user which is using sudo will be executed without asking the password.

phpseclib not working to execute commands remotely

I am stuck with a problem in php for the last 3 days. couldn't find a solution yet.
I have a Cent OS remote machine and an Ubuntu local machine. I have a php script named test.php in my local machine so that I want to run some Linux commands in the remote machine using that php script. I used phpseclib for connecting to remote machine. The following is the php script test.php.
<?php
include('Net/SSH2.php');
define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);
$ssh = new Net_SSH2('10.3.2.0');
if (!$ssh->login('makesubdomain','abcdabcd')) {
exit('Login Failed');
}
echo $ssh->exec('/usr/local/listdomain.backup/test/makedir.sh');
?>
I can't use root user here since root login has been disabled in remote cent os machine.
So I created this makesubdomain user and gave sudo privileges, that too without password by adding makesubdomain ALL=(ALL) NOPASSWD: ALL in /etc/sudoers file.The below one is the shell script which resides in 10.3.2.0
sudo -H sh -c '
mkdir /usr/local/testdir
if [ $? -eq 0 ];then
echo "success";
else
echo "not success";
fi
'
But now when I run the php script from terminal using command php test.php it showing error sudo: sorry, you must have a tty to run sudo. Ultimately, What shall I need to do with test.php and makedir.sh for creating a directory testdir as specified in .sh file using the given php script with user makesubdomain. Please advice as I am a very beginner in php.
(Note : I can run the makedir.sh file successfully in the remote machine, with the command sudo ./makedir as user makesubdomain, that too without prompting sudo password)
EDIT
I had commented Defaults requiretty in /etc/sudoers as given in http://www.unix.com/shell-programming-scripting/201211-sudo-sorry-you-must-have-tty-run-sudo.html, and it is working fine. Can i have any other option without doing this ?
Try calling $ssh->enablePTY() before doing $ssh->exec().

How can I use PHP to setup an interactive SSH session?

I'm trying to establish an interactive SSH connection to a remote server using PHP via the command line on Mac OS X 10.6. I'm currently using PHP's proc_open function to execute the following command:
ssh -t -t -p 22 user#server.com
This almost works. The -t -t options are supposed to force a pseudo terminal which they almost do. I am able to enter the SSH password and press enter. However, after pressing enter the terminal appears to simply hang. No output, no nothing - it's as if the SSH session has failed. I can't run commands or anything and have to kill the whole thing using Ctrl+C. I know the login is successful because I can execute a command like ssh -t -t -p 22 user#server.com "ls -la" and get the correct output.
I thought the problem must be related to the fact that I was using standard pipes in my proc_open call, so I replaced them with pty. I get the following error: "pty pseudo terminal not supported on this system..."
Does Mac OS X simply not support pty or pseudo terminals? (I'm pretty new at using all this shell terminology).
Here's the PHP code:
$descriptorspec = array(0 => array("pty"), 1 => array("pty"), 2 => array("pty"));
$cwd = getcwd();
$process = proc_open('ssh -t -t -p 22 user#server.com', $descriptorspec, $pipes, $cwd);
if (is_resource($process))
{
while (true)
{
echo(stream_get_contents($pipes[1]));
$status = proc_get_status($process);
if (! $status["running"])
break;
}
}
(Sorry - cannot for the life of me figure out SO's formatting instructions...)
What am I doing wrong? Why can't I use pty? Is this just impossible on Mac OS X? Thanks for your help!
You should use public key authentication rather than trying to programmatically bypass interactive password authentication.
The password prompt is supposed to be used from a tty and I believe it was made intentionally difficult to use otherwise. Also the -t -t argument only takes effect once you are connected to the remote host. And I don't believe the PHP function proc_open() can run a command inside a virtual terminal.
To setup public key authentication:
# Generate keypair
ssh-keygen -t rsa
# Copy public key to server
scp ~/.ssh/id_rsa.pub example.com:.ssh/authorized_keys
# Now you shouldn't be prompted for a password when connecting to example.com
# from this host and user account.
ssh example.com
# Since the web server (and thus PHP) probably has its own user account...
# Copy the ~/.ssh/id_rsa file somewhere else
cp ~/.ssh/id_rsa /some_path/id_rsa
# Change ownership of the file to the web server account
chown www-data:www-data /some_path/id_rsa
# Fix the file permissions (ssh ignore the keyfile if it is world readable)
chown 600 /some_path/id_rsa
# Try connecting to the server through the web server account
su -c "ssh -i /some_path/id_rsa -o UserKnownHostsFile=/some_path/known_hosts example.com" www-data
# Add the host to the known hosts file when prompted
Alternately, you could use plink (part of PuTTY for Linux) instead of OpenSSH as it can take the password on the command line plink -pw password example.com. But doing so presents a security risk as anyone who runs ps aux on the server can see the password in the process list.
There is also a program called sshpass that takes the password from an environment variable or command argument and passes it to ssh.
It looks like the problem is best solved using PHP's passthru() function. After alot more (rather painful) research I was able to issue a command through this function and could interact with the remote server through the terminal as if I had run ssh and svn export by hand (they both require passwords, therefore were good tests). What I'm going to have to do is construct a (potentially very long) string of commands separated by && and attach them to the end of the ssh command: ssh -t -t -p 22 hostname command1 && command2 ... The output will be sent to my terminal in Mac OS X even though the commands are being executed on the remote server. Looks like this is the solution I was looking for the whole time - pretty simple really! Thanks to everyone who helped me with this. I gave Alexandre the "green checkmark" because he was the only one who kept responding and was quite helpful in deducing the final answer to the problem. Thanks Alexandre!
This is old, but for any googlers out there, here is an actual solution using proc_open:
Pty descriptors are available in PHP, but have to be configured during compilation (see this 10yr old bug report https://bugs.php.net/bug.php?id=33147)
But in python however, we don't have that problem. So instead of running the ssh command directly, run this python script:
import sys
import pty
args = " ".join(sys.argv[1:])
pty.spawn(['/usr/bin/ssh', args])
About pty.spawn from python docs:
Spawn a process, and connect its controlling terminal with the current
process’s standard io. This is often used to baffle programs which
insist on reading from the controlling terminal.
Have you tried the PHP SSH2 extension?
Have you tried 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->read('username#username:~$');
$ssh->write("ls -la\n");
echo $ssh->read('username#username:~$');
?>
I wrote a ssh client on php with ssh2 extension, you can take a look to the source code on the github page https://github.com/roke22/PHP-SSH2-Web-Client
Please send some feedback.

Categories