Script implements SSH login email alert _linux Shell

Source: Internet
Author: User
Tags auth base64 ereg explode php class ssh

Login protection is a very important link, the following through an illustrated way to give you detailed explanation:


Two days ago, @cyy sent me a picture.

Then I thought about the Ushq SSH login app notification feature, and then just like if you had this deployed to your own server. At least one more layer of safety factor.

First of all, thanks to @legion for helping to fix a couple of bugs and geo2ip json conversion. (P.S. This person is the automation of the great God-level figures, now serving in Germany, a data statistics enterprises. )

Of course, I am compared with him I am the five scum ... We must learn more @Legion ~ ~

The next thing you need to do:

SendMail or Postfix.
Php
Bash
Centos/debian/ubuntu
If your production environment does not have PHP sendmail postfix and other components, please go to:

@Legion: Linux uses shell script to implement SSH login alarm

Reference documents

First, the alert script file.

Shell

#!/bin/sh ######################################################################### # File name:login-alert.sh # Author:jason # email:master#deamwork.com # Created time:tue June 2015 21:23:16 PM CST ############################## ########################################### #require JQ #wget Http://stedolan.github.io/jq/download/linux64/jq-O/ USR/LOCAL/BIN/JQ #chmod +x/usr/local/bin/jq #if error, please # following one #PATH =/usr/local/nginx/sbin:/usr/local/ph P/bin:/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin #Geo2IP by Legion (http:// www.dwhd.org/) eval ' curl-s "http://ip.taobao.com/service/getipinfo.php?ip=${ssh_client%% *}" | JQ. | Awk-f ': |[]+| ' ' {if ($3~/^ (country|area|region|city|isp) $/) {print $ = ' $}} ' #html Mail content cat >> mail-no-base64.html < <eof #请自行准备邮件模板, the following are the variables that may be used #输出主机名 ' hostname ' #输出登录端口 ${ssh_client##*} #输出登录来源IP ${ssh_client%% *} #输出IP地址归属地 {Country }_${area}_${region}_${city}_${isp} #输出登录时间 ' Date ' EOF #Base64 Encoding base64 mail-no-base64.html > mail-base64.html #使用Sendmail #sendmail-T >/dev/null 2>&1 & Lt;<eof #to: example@example.com #from:example<example@example.com> #subject: [' hostname '] Server login alert # ' Cat
Mail-no-base64.html ' #EOF #使用postfix #cat >> mail.php <<eof #<?php #\ $to = "example@example.com";
#\ $subject = "[' hostname '] server login alert";
#\ $message = "' Cat mail-base64.html '"; #\ $headers = "mime-version:1.0".
"\ r \ n"; #\ $headers. = "content-type:text/html; Charset=\ "Utf-8\" ".
"\ r \ n"; #\ $headers. = "Content-transfer-encoding:base64".
"\ r \ n"; #\ $headers. = ' from:example<example@example.com> '.
"\ r \ n";
#\ $send = mail (\ $to, \ $subject, \ $message, \ $headers); #if (\ $send) {echo ' Mail send successful. '} Else{echo ' Failed.} #?> #EOF #使用 SMTP (require smtp-class.php) cat >> mail.php <<eof <?php require ("s 
Mtp-class.php ");
\ $smtpserver = "smtp.example.com";
\ $smtpserverport = 25;
\ $smtpusermail = "example@example.com"; \ $SMTPemailto = "example@example.com";
\ $smtpuser = "Example";
\ $smtppass = "password";
\ $mailsubject = "[' hostname '] server login alert";
\ $mailbody = "' Cat mail-base64.html '";
\ $mailtype = "HTML";
\ $smtp = new SMTP (\ $smtpserver, \ $smtpserverport, true,\ $smtpuser, \ $smtppass);
\ $smtp->debug = TRUE; 
\ $smtp->sendmail (\ $smtpemailto, \ $smtpusermail, \ $mailsubject, \ $mailbody, \ $mailtype); ?> EOF php mail.php Yes y |

 RM mail-no-base64.html mail-base64.html mail.php

And then how to trigger this script:

Shell

Copy Code code as follows:

echo "screen-fa-d-m-s wl/etc/login-alert.sh" >>/etc/profile

In this way, the new terminal or replication terminal will trigger the alarm.

If you are using the SMTP method, save the following file as smtp-class.php

Php

<?php class SMTP {/* public Variables */var $smtp _port;
  var $time _out;
  var $host _name;
  var $log _file;
  var $relay _host;
  var $debug;
  var $auth;
  var $user;

  var $pass;

  * Private Variables * * var $sock; /* Constractor/function smtp ($relay _host = "", $smtp _port = =, $auth = False, $user, $pass) {$this->debug = F
    Alse;
    $this->smtp_port = $smtp _port;
    $this->relay_host = $relay _host; $this->time_out = 30;
    is used in Fsockopen () $this->auth = $auth;//auth $this->user = $user;
    $this->pass = $pass; $this->host_name = "localhost";
    is used in HELO command $this->log_file = "";
$this->sock = FALSE; }/* Main function/function SendMail ($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $BCC = "", $addit
    Ional_headers = "") {$mail _from = $this->get_address ($this->strip_comment ($from)); $body = ereg_replace ("^|" (
    \ r \ n) (\.) "," \1.\3 ", $body); $header. = "Mime-version:1.0\r\n"; if ($mailtype = = "HTML") {$header. = "content-type:text/html; Charset=\ "Utf-8\" ".
      "\ r \ n"; $header. = "Content-transfer-encoding:base64".
    "\ r \ n"; $header. = "To:". $to. "
    \ r \ n "; if ($cc!= "") {$header. = "cc:". $cc. "
    \ r \ n "; $header. = "From: $from <". $from. "
    >\r\n "; $header. = "Subject:". $subject. "
    \ r \ n ";
    $header. = $additional _headers; $header. = "Date:". Date ("R"). "
    \ r \ n "; $header. = "X-mailer:by Tianhaitech (php/). Phpversion ().")
    \ r \ n ";
    List ($msec, $sec) = Explode ("", Microtime ()); $header. = "Message-id: <". Date ("Ymdhis", $sec). ($msec *1000000). ".". $mail _from. "
    >\r\n ";

    $TO = Explode (",", $this->strip_comment ($to));
      if ($cc!= "") {$TO = Array_merge ($TO, Explode (",", $this->strip_comment ($CC)));
    } if ($bcc!= "") {$TO = Array_merge ($TO, Explode (",", $this->strip_comment ($BCC)));
    } $sent = TRUE; foreach ($TO As $rcpt _to) {$rcpt _to = $this->get_address ($rcpt _to); if (! $this->smtp_sockopen ($rcpt _to)) {$this->log_write ("Error:cannot send email to". $rcpt _to. "
        \ n ");
        $sent = FALSE;
      Continue } if ($this->smtp_send ($this->host_name, $mail _from, $rcpt _to, $header, $body)) {$this->log _write ("e-mail has been sent to <". $rcpt _to. "
      >\n "); else {$this->log_write ("Error:cannot Send email to <". $rcpt _to. "
        >\n ");
      $sent = FALSE;
      } fclose ($this->sock);
    $this->log_write ("Disconnected from remote host\n");
  return $sent; }/* Private functions/function Smtp_send ($helo, $from, $to, $header, $body = "") {if (! $this-&GT;SMTP_PUTC
    MD ("HELO", $helo)) {return $this->smtp_error ("Sending HELO command"); } #auth if ($this->auth) {if (! $this->smtp_putcmd (! Auth LOGIN), Base64_encoDe ($this->user))) {return $this->smtp_error ("Sending HELO command"); } if (! $this->smtp_putcmd ("", Base64_encode ($this->pass)) {return $this->smtp_error ("Sendi
      ng HELO Command "); } if (! $this->smtp_putcmd ("MAIL", "from:<". $from. "
    > ") {return $this->smtp_error (" Sending MAIL from command "); if (! $this->smtp_putcmd ("RCPT", "to:<". $to. "
    > ") {return $this->smtp_error (" Sending RCPT to command ");
    } if (! $this->smtp_putcmd ("data")) {return $this->smtp_error ("Sending data Command");
    } if (! $this->smtp_message ($header, $body)) {return $this->smtp_error ("Sending message"); } if (! $this->smtp_eom ()) {return $this->smtp_error ("Sending <cr><lf>.<cr><lf&gt ;
    [EOM] "); } if (! $this->smtp_putcmd ("QUIT")) {return $this->smtp_error ("Sending QUIT command");
  return TRUE; The function Smtp_sockopen ($address) {if ($this->relay_host = = "") {return $this->smtp_sockopen_
    MX ($address);
    else {return $this->smtp_sockopen_relay (); The function Smtp_sockopen_relay () {$this->log_write ("trying to". $this->relay_host. ":" $this->smtp_p Ort. "
    \ n ");
    $this->sock = @fsockopen ($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out); if (!) ( $this->sock && $this->smtp_ok ()) {$this->log_write ("Error:cannot connenct to relay host". $ This->relay_host. "
      \ n "); $this->log_write ("Error:". $errstr. " (". $errno.")
      \ n ");
    return FALSE; $this->log_write ("Connected to relay Host". $this->relay_host. "
    \ n ");
  return TRUE;;;
    The function smtp_sockopen_mx ($address) {$domain = Ereg_replace ("^.+@ ([^@]+) $", "\1", $address); if (! @getmxrr ($domain, $MXHOSTS)) {$this->log_wRite ("error:cannot resolve MX \" ". $domain."
      \ n ");
    return FALSE; foreach ($MXHOSTS as $host) {$this->log_write ("trying to". $host. ":". $this->smtp_port. "
      \ n ");
      $this->sock = @fsockopen ($host, $this->smtp_port, $errno, $errstr, $this->time_out); if (!) ( $this->sock && $this->smtp_ok ()) {$this->log_write ("Warning:cannot Connect to MX host") . $host. "
        \ n "); $this->log_write ("Error:". $errstr. " (". $errno.")
        \ n ");
      Continue $this->log_write ("Connected to MX host". $host. "
      \ n ");
    return TRUE; $this->log_write ("Error:cannot connect to any MX hosts (". Implode (",", $MXHOSTS). ")
    \ n ");
  return FALSE; function Smtp_message ($header, $body) {fputs ($this->sock, $header.)
    \ r \ n ". $body); $this->smtp_debug (">". Str_replace ("\ r \ n", "\ n".) > ", $header." \n> ". $body."
    \n> "));
  return TRUE; The function Smtp_eom () {fputs ($thIs->sock, "\r\n.\r\n"); $this->smtp_debug (".
    [eom]\n ");
  return $this-&GT;SMTP_OK ();
    function Smtp_ok () {$response = Str_replace ("\ r \ n", "", Fgets ($this->sock, 512)); $this->smtp_debug ($response.)
    \ n ");
      if (!ereg ("^[23]", $response)) {fputs ($this->sock, "quit\r\n");
      Fgets ($this->sock, 512); $this->log_write ("Error:remote host returned \" ". $response."
      \ n ");
    return FALSE;
  return TRUE; 
      The function smtp_putcmd ($cmd, $arg = "") {if ($arg!= "") {if ($cmd = = "") {$cmd = $arg; ' Else {$cmd = $cmd. '
      ". $arg; } fputs ($this->sock, $cmd. "
    \ r \ n "); $this->smtp_debug (">". $cmd. "
    \ n ");
  return $this-&GT;SMTP_OK (); The function Smtp_error ($string) {$this->log_write ("Error:error occurred while". $string. ").
    \ n ");
  return FALSE;
    function Log_write ($message) {$this->smtp_debug ($message); IF ($this->log_file = = "") {return TRUE; $message = Date ("M D h:i:s"). Get_current_user ().
    [". Getmypid ()."]: ". $message; if (! @file_exists ($this->log_file) | |! ( $fp = @fopen ($this->log_file, "a")) {$this->smtp_debug ("warning:cannot open log file \" ". $this->log _file. "
      \ n ");
    return FALSE;;;
    Flock ($FP, LOCK_EX);
    Fputs ($fp, $message);
    Fclose ($FP);
  return TRUE;
    The function strip_comment ($address) {$comment = "\ ([^ ()]*\)";
    while (Ereg ($comment, $address)) {$address = Ereg_replace ($comment, "", $address);
  return $address;
    The function get_address ($address) {$address = Ereg_replace ([[\t\r\n]) + "," ", $address);
    $address = Ereg_replace ("^.*< (. +) >.*$", "\1", $address);
  return $address;
    The function Smtp_debug ($message) {if ($this->debug) {echo $message;

 }
  }

}

?>
Implementation effect:

There is a need for friends can refer to, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.