DIY webhook for logging shell command outputs to email

The idea here is to be able to run a shell command on a remote linux box and have the results sent to you via email. In this case the linux box doesn't have SMTP so I use a 2nd commercial server that does to operate a HTTP/PHP to email "gateway". This can't be abused for spam even if discovered since the destination is always fixed (a filtered folder in my Gmail account). 

On the linux box:

#!/bin/bash
# syntax hook <whatever>, if pipes used put quotes around it.
# sends user agent as command

echo $@
outp=$(eval "$@" 2>&1)
echo $outp
curl --user-agent "$@" -H "x:`echo "$outp"|gzip|base64 -w0`"  "https://sever.com/hook_URL/"

Replace server.com with your own webserver (not the linux box). The basic idea is to save the output of the command as gziped text that's been base64 encoded so that it's a valid http header (we use a custom header since these seem to be unlimited in size up to 8k, unlike the URL itself).


Then on the server make this php file inside /hook_URL/
<?php
$sender = "hook@server.com";  // sender address used to notify user
$receiver = "me@gmail.com";  // email address to send records to
$command = $_SERVER['HTTP_USER_AGENT']; // we store the command text as the agent

$raw = apache_request_headers()["x"]; // text from custom header

$text = gzdecode( base64_decode($raw) ); // convert from base 64 to binary and then gunzip it to ascii

mail($receiver, // where it gets emailed
$command, // title
$text, // body
    "From: " . $_SERVER['REMOTE_ADDR'] . "_$sender", "-r $sender"); 
?>

then you can put in your cron or whatever:

hook "dmesg | tail"

you might ask why hook takes arguments rather than stdin; the reason is this way it can report what command was run rather than just the text sent to it via a pipe. Downside is you have to quote the command if it involves a pipe.

Comments

Email me

Name

Email *

Message *

Popular posts from this blog

Panasonic TH-42PX75U Plasma TV review: input lag and upscaling tested using the piLagTesterPRO

piLagTester PRO order page

A $5 TV Input Lag tester using a Raspberry Pi Zero