how to run ansible command usin shell_exec() function in php - php

my ansible command won't run using shell_exec function in php but the other
commands like ls, pwd works just fine note that my php code is hosted on nginx web server
and i am logged in as a 'user' in both machines my local machine and my remote server which has this name 'dockerengine'
<%php
shell_exec("ansible dockerengine -m shell -a 'echo hello > /home/user/hello.txt'")
%>
when i execute the command ansible dockerengine ... (dockerengine is my remote server) in terminal it works perfectly
note also i configured ssh keys and sudoers file on my remote server to escalate privileges auto
//this code contained in a file with root priv hosted on nginx
<%php shell_exec("ansible dockerengine -m shell -a 'echo hello > /home/user/hello.txt'") %>
// this line is written in the sudoers file of my remote server (dockerengine)
user ALL=(ALL) NOPASSWD:ALL
// this line is written in the /etc/ansible/hosts file in my local machine
[docker]
dockerengine ansible_user=user

Related

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>";

executing a script from a php file

I have a php file which is called by a website:
example: serial_tx.php?v=W100
Within the php I write a log file where I can see which string v I received (W100 in this case).
The webserver is hosted on a Raspberry Pi and should send this data to the uart.
The files locations:
/SCRIPTS/serial_tx.php
/SCRIPTS/c/jmsend/serial_tx // the executable, compiled from a C script
If I am in the root of the webserver and, from the console of my Pi, I run
sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx W100
I get the command sent correctly.
With the php file I tried with system, shell_exec and exec without success.
shell_exec("sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx ".$ric);
$ric is the received command.
I tried with different path settings too (starting from Pi root or webserver root).
All the files have a 777 as permissions.
Something like this in /etc/sudoers should work to allow your web server user to run that particular command without issue:
Cmnd_Alias SERIAL = /var/www/html/SCRIPTS/c/jmsend/serial_tx *
www-data ALL=(ALL) NOPASSWD: SERIAL
Note that you must escape user input before using it:
$ric = escapeshellarg($_GET["v"]);
shell_exec("sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx $ric");
You should also be aware of the differences between exec() and shell_exec(), specifically that you can't check for a failure using shell_exec().
$ric = escapeshellarg($_GET["v"]);
exec("sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx $ric", $output, $return);
if ($return !== 0) {
// let the user know something didn't work
}
This assumes, of course, that your executable is written to return appropriate error codes.

How to automate apache retrieval of data from a MikroTik router?

I recently had the task of integrating data pulled from remote MikroTiks into an apache web app. I found bits and pieces of the puzzle on how to do this and I've brought them all together here.
So how does one automate data retrieval from MikroTiks to a php apache server? (Without installing PEAR or PECL modules.)
This example was performed on a CentOS machine.
MikroTik allows RouterOS commands to be executed via ssh. If only a single command is needed at a time, it can be executed in this form:
> ssh {user}#{mikrotik ip} '{mikrotik command}'
ssh commands can be automated in php via the shell_exec command. Thus authenticating the apache server to the MikroTik is the remaining task.
ssh-keys is the best way to automate ssh authentication. The apache user will need to have its own dsa key pair. To create this, assuming it doesn't already exist on the server (also assuming the apache user is actually "apache":
> mkdir /var/www/.ssh
> chmod 740 /var/www/.ssh
> chown apache:apache /var/www/.ssh
> cd /var/www/.ssh/
Now we need to create the ssh-keys as the apache user.
> sudo -u apache ssh-keygen -t dsa
The default file name is fine. Don't add a password. Double check that files have been created.
> ls
-- id_dsa
-- id_dsa.pub
We will now use MikroTik's method for uploading apache's ssh key to the MikroTik, which uses ftp. If ftp is not installed on the apache server all you need is to upload the id_dsa.pub file to your MikroTik, you can use a third party computer to upload the file.
> cd /var/www/.ssh
> ftp {mikrotik ip}
name: {admin}
Password: {password}
ftp> put id_dsa.pub
ftp> exit
You will need to authenticate during the previous ftp step. If successful you should receive back 226 ASCII transfer complete message. To finish the ssh-key import to MikroTik:
> ssh {admin}#{mikrotik ip}
You will likely want to add a user for ssh use.
[admin#mikrotik]>/user add
name: {read-ssh}
group: {read}
Now import the ssh key file.
[admin#mikrotik]> /user ssh-keys import public-key-file=id_dsa.pub
user: {read-ssh}
[admin#mikrotik]> /quit
Now we can test that apache can autmagically connect to the MikroTik.
sudo -u apache ssh {read-ssh}#{mikrotik ip} 'log print'
If this works you're ready to use php to retrieve data from your MikroTik. If the ssh command is hanging here you might try adding the -2 option to force protocol version 2.
$ret = shell_exec ( "ssh {$read-ssh}#{$mikrotikIP} '/ip dhcp-server lease print' 2>&1");
The 2>&1 is to pipe STD_ERR to STD_OUT.

Executing .exe file using PHP on Linux server

I'm new in using Linux, I'm trying to write a PHP code which can run .exe linux compatible file, I've made a short shell script
hello bash script:
#!/bin/bash
./program.exe file.mp4 // file.mp4 is an an input for .exe
echo "Hello World!"
shell.php:
<?php
$output = exec ("./hello ");
echo "<pre>$output</pre>";
?>
Now when I run shell.php using web browser it shows Hello World! but the .exe doesn't run, however when I run php using terminal command php shell.php, It works fine.
I think I'm having problems with permissions but I'm new with Linux and I don't know how to solve this.
Update:
I ignored the shell script and I used
<?php
$output = shell_exec ("cd /var/www/ && ./program.exe file.mp4 2>& " );
?>
also I granted access to program.exe
chmod 777 program.exe
the error I receive in the browser :could not open debug.bin!
use the absolute path to hello executable exec("sh path/to/the/file")
I'm using something similar to call an app compiled with mono on a remote ubuntu webserver and return it's output to the calling script.
For any of this to work properly wine needs to be already installed.
On Ubuntu systems try:
sudo apt-get -y install wine
You then need to know the owner of the web server process. If you are running the apache web server try the following:
cat /etc/apache2/envvars | grep "RUN"
The output will look something like this:
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
export APACHE_RUN_DIR=/var/run/apache2$SUFFIX
Now that you have the name of the process owner, which in this case is www-data you should ensure the file is owned the user and its group:
sudo chown www-data /var/www/program.exe
sudo chgrp www-data /var/www/program.exe
Finally, we can invoke the application from inside our PHP script by passsing it as a parameter to 'wine' and using its full file path.
<?php
$output = shell_exec("wine /var/www/program.exe file.mp4" );
?>
Any output from the above shell command sent to the command line will be saved in the PHP script variable $output.
It looks like you are trying to do some output redirection with your use of program.exe file.mp4 2>& so I've left that off of the example for clairity.
Try using the absolute path, such as exec("sh /path/to/file")
Generally, php is run as www or apache, so make sure that the execute access permission is granted to all user.

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().

Categories