Run Scripts from PHP - php

I have a question about interaction PHP and Linux system.
I want to launch Steam from WebPage, and address of this page is
http://site.eu/cp/user/services/21/steaminstall
And internal path to WebPage from where im running command is
/var/www/wwwuser/data/www/site.eu/panel.php?(here goes $_POST[''] data)
and the Steam Client is
/var/www/wwwuser/data/Steam/SteamInstall
The thing is, i know how to access this script, also i can execute simple
echo "Script is Runing"
But when my actions comes to this code
#!/bin/bash
wget -P /var/www/aftersoft/data/Servers/Steam/ http://media.steampowered.com/client/steamcmd_linux.tar.gz &&
tar xvfz /var/www/aftersoft/data/Servers/Steam/steamcmd_linux.tar.gz -C /var/www/aftersoft/data/Servers/Steam/ &&
sh /var/www/aftersoft/data/Servers/Steam/steamcmd.sh +login anonymous +quit &&
rm /var/www/aftersoft/data/Servers/Steam/steamcmd_linux.tar.gz &&
echo "Steam Installation and Update Completed"
It's not doing anything if im running it from WebPage, but it works when im trying to run it under the SSH user (same as apache user with permissions to write to this folder)
So my question, what am i doing wrong?
UPDATE:
My php code to run script is
if($path[2] === 'steaminstall')
{
$InstallSteam = exec('/var/www/aftersoft/data/Servers/Steam/SteamInstall', $Output, $Error);
if($Error === 0)
{
$Status = $DB->SteamStatus($_SESSION['username']);
if($Status)
{
header('Location: /cp/'.$_SESSION['username'].'/services/');
}
else
{
$Smarty->assign('InstallStatus', 'Database Error Occured');
$Smarty->display('steaminstall.tpl');
}
}
if($Error === 2)
{
$Smarty->assign('InstallStatus', $Output);
$Smarty->display('steaminstall.tpl');
}
}
And this is my database query function
public function SteamStatus($Username)
{
$Status = '1';
$Statement = $this->DBConnection->prepare("UPDATE account set steaminstalled = ? where username = ?");
$Statement->bindParam(1, $Status);
$Statement->bindParam(2, $Username);
$IStatus = $Statement->execute();
if($IStatus)
{
return true;
}
else
{
return false;
}
}

Problem solved, you just need to specify direct path to your script (as if you dont, the script itself dont know where to download and where to extract)
So the final bash script (PHP part is perfectly fine):
#!/bin/bash
wget -P /var/www/aftersoft/data/Servers/Steam/ http://media.steampowered.com/client/steamcmd_linux.tar.gz &&
tar xvfz /var/www/aftersoft/data/Servers/Steam/steamcmd_linux.tar.gz -C /var/www/aftersoft/data/Servers/Steam/ &&
sh /var/www/aftersoft/data/Servers/Steam/steamcmd.sh +login anonymous +quit &&
rm /var/www/aftersoft/data/Servers/Steam/steamcmd_linux.tar.gz &&
echo "Steam Installation and Update Completed"

Related

How to answer to command response? (shell_exec, exec)

I should enter confirmation code after my function execute. My command wait an answer but I can't reply.
$cmd = 'cd/ && cd .... && ....';
echo shell_exec($cmd);
I tried:
shell_exec($confirmation_code);
I must enter confirmation code after get permission for some access.
Try this
$cmd = 'echo "Yes"| cd/ && cd .... && ....';
echo shell_exec($cmd);
Replace "Yes" by what you want
Symphony Process command can do this for you:
https://symfony.com/doc/current/components/process.html#streaming-to-the-standard-input-of-a-process

shell_exec not giving any result, and not doing anything

So I have question which in my head should seem very simple to solve.
I want to ssh to a server, which I have done a ton of times, and then make a shell execute which I have done a ton of times as well, but it is not working.
The code i am using
<?php
$ip = '1.2.3.4';
$cmd = "ssh user#".$ip;
$result = shell_exec($cmd." 'sudo /bin/systemctl stop wildfly.service'");
echo "<pre>output: $result</pre>";
echo "<div class='alert alert-success'><strong>SUCCESS</strong><br>Wildfly node has now restarted</div>";
?>
Running the command directly from the terminal
ssh user#1.2.3.4 sudo /bin/systemctl stop wildfly.service
It works, but running it within php gives me nothing, and it not doing anything.
Can someone maybe guide me to what I am doing wrong with my shell_exec?
Thanks in advance!
function execPrint($command) {
try {
$result = array();
exec($command.' 2>&1', $result);
foreach ($result as $line) {
print($line . "\n");
}
echo '------------------------' . "\n" . "\n";
} catch (\Exception $e) {
print($e);
}
http_response_code(200);
}
i made this function to get result
add 2>&1 in last of the CMD
use print with every line
use try and catch to catch any error
The user attempting to execute those shell commands from php is likely _www and not you. Try this code in your php to gain insight:
$shellscript = 'whoami';
$sr = shell_exec($shellscript);
echo '['.$sr.']';
Make sure the shell_exec function is not disabled. It usually is disabled by default in CPanel accounts PHP.ini and PHP-FPM .ini files.
You can check it using this validation
if (is_callable('shell_exec') && (false === stripos(ini_get('disable_functions'), 'shell_exec'))) {
echo "shell_exec enabled";
} else {
echo "shell_exec disabled";
}
It's the most common reason i've found for shell_exec to return always empty
You can also execute a quick command for testing purpouses
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo "Command: shell_exec('ls -lart')";
try {
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
} catch (Exception $e) {
echo $e->getMessage();
}

Can't execute powershell script function using PHPs shell_exec

I'm trying to pass arguments from a PHP page's POST request into a powershell script.
This is the relevant PHP snippet:
$selectedPartner = $_POST['partner'];
$selectedGroup = $_POST['group'];
$script = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe AddRemPartners";
if (isset($_POST['partner']) && isset($_POST['group'])){
if (isset($_POST['AddButton']) && $selectedPartner !== "Select Partner" && $selectedGroup !== "Select Group") {
echo "<br>";
echo "Adding " . $selectedPartner . " to " . $selectedGroup . "...<br>";
$cmd = $script . " -Add $selectedPartner $selectedGroup";
echo "command is:<br>" . $cmd;
shell_exec($cmd);
//shell_exec('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe C:\\xampp\\htdocs\\admin\\AddRemPartners.ps1 -Add $selectedPartner //$selectedGroup');
//$command = shell_exec('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe telnet 10.11.14.32 4444');
//echo "User added successfully!";
}
if (isset($_POST['RemoveButton']) && $selectedPartner !== "Select Partner" && $selectedGroup !== "Select Group") {
echo "<br>";
//echo "selection was REMOVE";
}
}
And this is my powershell script:
Param([switch]$Add, [switch]$Remove, [string]$User, [string]$Group)
$secpasswd = ConvertTo-SecureString "P#sSw0rd" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("userPortal", $secpasswd)
$server = "host.fqdn"
function AddRemPartners
{
if ($Add){
Write-Host "Add var = $Add"
Write-Host "Add was selected"
Add-ADGroupMember -Server $server -Credential $creds -Identity $Group -Member $User
}
if ($Remove) {
Write-Host "Remove var = $Remove"
Write-Host "Remove was selected"
Remove-ADGroupMember -Server $server -Credential $creds -Identity "$Group" -Member "$User" -Confirm:$false
}
}
AddRemPartners -Add $Add -Remove $Remove -User $User -Group $Group
Things I know:
The php post parameters are good. I captured the request in burpsuit and know that all the correct args are getting sent
The resultant ps query that is built is also good. I output it to the screen and it looks like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe AddRemPartners -Add Dude1 Dude1Group
No network issues. If I run the above command directly from within PowerShell is executes correctly.
I've sourced my script using . .\AddRemPartners.ps1 so I can call my function directly as such:
PS > AddRemPartners -Add User Group
PS > AddRemPartners -Remove User Group
I've narrowed it down to this: I can't execute my ps script from cmd like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe AddRemPartners -Add User Group
As that errors out with this:
AddRemPartners : The term 'AddRemPartners' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
I believe this to be suspect/culpable since I need run that in PHP. So PHP is probably running into the same issue. So why won't cmd recognize my script if I call powershell at the same time as execution?
Any tips and guidance greatly appreciated. I'm at wits end unfortunately. :/
First parameter for PS should be full path of script. Then you should respect parameter definition of PS, on command line as in the script.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe C:\whereis\AddRemPartners.ps1 -Add -user User -group Group
First line of the script should be parameter definition and defaults.
param([string]$user, [string]$group, [switch]$Add, ...);

Login to Docker Hub from PHP script

I am trying to login and push Docker images from a PHP script as part of our CICD process. Here is the code:
<?php
include '../php/database.php';
$duser = 'username';
$dpass = 'password';
$dmail = 'email';
$tag = 'from system';
function tagImage($tag) {
$getImageID = "SELECT `imageID` FROM `docker_images` WHERE `tag` = :tag ";
$params = array(':tag' => $tag);
$results = dataQuery($getImageID, $params);
if(!empty($results)) {
$image = $results[0]['imageID'];
global $repo = $results[0]['repo']; // I know this is a bad idea, will change it when all else is working
$last = system("sudo docker tag -f $image $repo 2>&1", $retval);
}
return $retval;
}
$tagStatus = tagImage($tag);
if(0 == $tagStatus) {
echo '<pre>';
$login = system("sudo docker login --username=$duser", $retval);
var_dump($login);
var_dump($retval);
// push it real good
$last = system("sudo docker push $repo 2>&1", $retval1);
var_dump($last);
var_dump($retval1);
}
?>
This returns the following:
string(0) ""
int(1)
The push refers to a repository [app/ap-name] (len: 1)
21d623eb89a9: Image push failed
Please login prior to push:
Username: EOF
string(13) "Username: EOF"
int(1)
The push is failing because the login is not working from the PHP script, however, when I login from the command line the login is successful.
What am I doing wrong? Can I login to Docker Hub with PHP like this? Or should the technique be different?
EDIT: The PHP script will be called via AJAX, effectively making it run as if it were being run from the browser. I am running it from the browser for testing purposes.
The login requires all of the credentials including password and email address associated with the Docker hub repo:
$login = system("sudo docker login --username $duser --password $dpass --email $dmail 2>&1", $retval);
var_dump($login);
var_dump($retval);
Using this syntax returns the following (expected):
WARNING: login credentials saved in /root/.dockercfg.
Login Succeeded
string(15) "Login Succeeded"
int(0)
Past that point the push works properly and returns no errors.

Pinging an IP address using PHP and echoing the result

I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.
function pingAddress($ip){
$pingresult = shell_exec("start /b ping $ip -n 1");
$dead = "Request timed out.";
$deadoralive = strpos($dead, $pingresult);
if ($deadoralive == false){
echo "The IP address, $ip, is dead";
} else {
echo "The IP address, $ip, is alive";
}
}
When I call this function using the example:
pingAddress("127.0.0.1")
The echo result is always 'dead' - no matter what.
Could someone please help me where I'm going wrong?
And/OR is there a better method of doing this with the same result?
Many thanks.
Update: Have amended code to include the double quotes but still getting the same (incorrect) results.
NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly
I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.
But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.
<?php
function pingAddress($ip) {
$pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
if (0 == $status) {
$status = "alive";
} else {
$status = "dead";
}
echo "The IP address, $ip, is ".$status;
}
pingAddress("127.0.0.1");
This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,
function pingAddress($ip) {
$pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);
if ($status==0) {
$status = "alive";
} else {
$status = "dead";
}
$message .= '<div id="dialog-block-left">';
$message .= '<div id="ip-status">The IP address, '.$ip.', is '.$status.'</div><div style="clear:both"></div>';
return $message;
}
// Some IP Address
pingAddress("192.168.1.1");
This worked perfectly for me, finally.
I referred this from http://www.phpscriptsdaily.com/php/php-ping/
Hope this will help
Well I want to modify this as it is working fine on my localhost but not on my live server
For live server, I got another thing which now works for both local as well as live.
$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }
Then I show the Server is up for 0 and down for 1.
This works perfectly for me. I got this from Ping site and return result in PHP Thanks #karim79
I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.
Implement the following class:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}
return false;
}
}
$ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
i just wrote a very fast solution by combining all knowledge gain above
function pinger($address){
if(strtolower(PHP_OS)=='winnt'){
$command = "ping -n 1 $address";
exec($command, $output, $status);
}else{
$command = "ping -c 1 $address";
exec($command, $output, $status);
}
if($status === 0){
return true;
}else{
return false;
}
}
this works fine for me..
$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);
echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it
if (strpos($output, 'out') !== false) {
echo "Dead";
}
elseif(strpos($output, 'expired') !== false)
{
echo "Network Error";
}
elseif(strpos($output, 'data') !== false)
{
echo "Alive";
}
else
{
echo "Unknown Error";
}
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
https://github.com/geerlingguy/Ping
Based on the great answer of #tiamiyu-saheed-oluwatosin I wrote this small function in shorthand if/else (ternary) style, working on both Windows and Linux, to check if a second PHP server is up and running in my LAN.
function running($ip) {
exec("ping -{strtolower(PHP_OS)=='winnt'?'n':'c'} 1 $ip", $out, $res);
return ($res === 0 ? true : false);
}
Use :
if(running('192.168.1.20') {
// execute some code...
}
This works fine with hostname, reverse IP (for internal networks) and IP.
function pingAddress($ip) {
$ping = exec("ping -n 2 $ip", $output, $status);
if (strpos($output[2], 'unreachable') !== FALSE) {
return '<span style="color:#f00;">OFFLINE</span>';
} else {
return '<span style="color:green;">ONLINE</span>';
}
}
echo pingAddress($ip);
Do check the man pages of your ping command before trying some of these examples out (always good practice anyway). For Ubuntu 16 (for example) the accepted answer doesn't work as the -n 3 fails (this isn't the count of packets anymore, -n denotes not converting the IP address to a hostname).
Following the request of the OP, a potential alternative function would be as follows:
function checkPing($ip){
$ping = trim(`which ping`);
$ll = exec($ping . '-n -c2 ' . $ip, $output, $retVar);
if($retVar == 0){
echo "The IP address, $ip, is alive";
return true;
} else {
echo "The IP address, $ip, is dead";
return false;
}
}
This is work with me:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}return false;
}
}
$ip_addr = "192.168.1.1";
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
I use this function :
<?php
function is_ping_address($ip) {
exec('ping -c1 -w1 '.$ip, $outcome, $status);
preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
return ( $arr[1] == 100 ) ? false : true;
}

Categories