I want to know: How to send mail via Shell command line through this code
#!/usr/local/vesta/php/bin/php
<?php
error_reporting(NULL);
if (empty($argv[1])) {
echo "Error: not enough arguments\n";
exit(3);
}
$options = getopt("s:f:");
define('NO_AUTH_REQUIRED',true);
include("/usr/local/vesta/web/inc/main.php");
// Set system language
exec (VESTA_CMD . "v-list-sys-config json", $output, $return_var);
$data = json_decode(implode('', $output), true);
if (!empty( $data['config']['LANGUAGE'])) {
$_SESSION['language'] = $data['config']['LANGUAGE'];
} else {
$_SESSION['language'] = 'en';
}
require_once('/usr/local/vesta/web/inc/i18n/'.$_SESSION['language'].'.php');
// Define vars
$from = 'Vesta Control Panel <vesta#'.gethostname().'>';
$to = $argv[3]."\n";
$subject = $argv[2]."\n";
$mailtext = file_get_contents("php://stdin");
// Send email
if ((!empty($to)) && (!empty($subject))) {
send_email($to,$subject,$mailtext,$from);
}
This code is available on my server, link file: /usr/local/vesta/web/inc/mail-wrapper.php and my server use Vesta CP Thank for helping me.
Related
I have a php script that sends an email with an attachment. When I manually execute the php script below via a web browser, everything works well and the email is sent instantly. However, when I try to execute the php file using a crontab command, the email is not sent. Any idea why this is? The cron command isn't generating any errors...
Further, the email_output.log shows success but the email doesn't come through, as if it is piling up in the outgoing box but never actually sent.
Crontab command:
/Applications/MAMP/bin/php/php5.6.10/bin/php /my/path/emailApp.php > /my/path/email_console.log 2> /my/path/email_error.log
Thanks in advance.
<?php
include_once(__DIR__ . '/mailer/swift_required.php');
$transport = Swift_SmtpTransport::newInstance('mail.myhost.com', 25)
->setUsername('name#myhost.com')
->setPassword('password');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$mailTo = Array('testemail#gmail.com');
$subject ="report";
$attach = 'report.pdf';
$message = Swift_Message::newInstance($subject)
->setFrom(array('name#mydomain.com' => 'Bob Dole' ))
->attach(Swift_Attachment::fromPath($attach)->setFilename($attach))
->setTo($mailTo);
$message->setBody("attached",'text/html');
// Send the message
$result = $mailer->send($message);
if($result == 0){
echo 'Error';
} else {
echo 'Success';
}
I'm currently putting together a small web-based GUI to generate kickstart-scripts. I got a confirmation page that's sending the relevant data via POST to the PHP-page where the actual shell script is called to build the iso. So far it's working, but the page seems to execute the script before it outputs anything else (for example, the 'echo' I put in at the beginning of the page ...), and I'm absolutely clueless why. Would anyone care to enlighten me?
Here's the code to the PHP-page that's executing the shell script ...
echo 'Generating your ISO; this might take a while...';
sleep(20);
if (!isset($_POST['auth'])) {
$ad = 'N';
}
else {
$ad = 'Y';
}
if (!isset($_POST['oracle'])) {
$oracle = 'N';
}
else {
$oracle = 'Y';
}
if ((!isset($_POST['ip'])) or (!isset($_POST['hostname'])) or (!isset($_POST['rhsel'])) or (!isset($_POST['submit'])) or (!isset($_POST['gw'])) or (!isset($_POST['nm']))) {
die('Please use the correct form !');
}
if (isset($_POST['ip'])) {
$ip = trim($_POST['ip']);
}
if (isset($_POST['gw'])) {
$gw = trim($_POST['gw']);
}
if (isset($_POST['nm'])) {
$nm = trim($_POST['nm']);
}
if (isset($_POST['hostname'])) {
$hostname = trim($_POST['hostname']);
}
if (isset($_POST['rhsel'])) {
$rhsel = $_POST['rhsel'];
}
passthru("/usr/bin/sudo /data/skripte/webconfig.sh $rhsel $oracle $ad $ip $gw $nm $hostname 2>&1");
PHP scripts accessed via a browser are request-response, meaning all processing is done on the server prior to headers and content being sent to the client. This means you will not get a continually updating output like you would see on the command line. There is no way around this. Sorry.
I am using EFUMultiple Uploader to receive files on my site. Does anyone know of a tutorial that will teach me how I can be notified each time there is a new file or batch of files in my uploads folder?
It will become annoying, fast, I can promise you that.
But either way, in your upload script, you'll want to use either the mail() function or, for example the PHPMailer library if you don't have a SMTP server configured on your PHP installation.
Consider this (untested) script:
#!/usr/bin/env php
<?php
// Warning: this script and UPLOADED_FILES_DB, for security reasons, should not be in UPLOAD_PATH.
define('UPLOAD_PATH', '...');
define('UPLOADED_FILES_DB', 'uploaded_files');
define('MAIL_TO', 'you#example.com');
define('MAIL_FROM', 'cron#example.com');
define('MAIL_SUBJECT', 'Uploaded files');
// Get old files:
if (file_exists(UPLOADED_FILES_DB)) {
$old_files = unserialize(file_get_contents(UPLOADED_FILES_DB));
} else {
$old_files = array();
}
// Get current files:
$current_files = array();
foreach (new DirectoryIterator(UPLOAD_PATH) as $file_info) {
if (!$file_info->isDot()) {
$current_files[$file_info->getFilename()] = filemtime($file_info->getFilename());
}
}
// Update database:
file_put_contents(serialize($current_files), UPLOADED_FILES_DB);
// Compute differences:
$added_files = array_diff(array_keys($old_files), array_keys($current_files));
$removed_files = array_diff(array_keys($current_files), array_keys($old_files));
$changed_files = array_diff_assoc($old_files, $current_files);
// Send message:
$headers = 'From: ' . MAIL_FROM . "\r\n";
$message = 'Added files: ' . implode(', ', $added_files);
mail($to, $subject, $message, $headers);
Then you would put that script on a cron job to execute every day or so, or you can include it in wherever your upload code is — though, the latter approach would get annoying quickly.
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:~".