Daily Shell Exercises (04)

Source: Internet
Author: User
Tags email account python script

1. Exercises

Design a script that monitors the surviving state of a remote host (assuming the IP address is 110.110.110.114) and sends a message to yourself when it finds an outage.

Tips:

    • You can use the ping command:
ping   -c  10 110.110.110.114
    • Scripts can be made into a dead loop.
2. Exercise Analysis

In fact, the demand is not difficult, the topic also gives the idea. The key is to determine a threshold that triggers a warning and sends a warning message when a result is detected that meets the threshold.

We can first try to execute the ping-c command on the host:

 [[email protected] work]# ping-c ten 192.168.188.203 ping 192.168.188.203 ( 192.168.188.203) bytes of data.64 bytes from 192.168.188.203:icmp_seq=1 ttl=128 time=1.53 ms64 bytes from 192.168. 188.203:icmp_seq=2 ttl=128 time=0.469 ms64 bytes from 192.168.188.203:icmp_seq=3 ttl=128 time=0.632 ms64 bytes from 192. 168.188.203:icmp_seq=4 ttl=128 time=0.562 ms64 bytes from 192.168.188.203:icmp_seq=5 ttl=128 time=0.785 ms64 bytes from 192.168.188.203:icmp_seq=6 ttl=128 time=0.591 ms64 bytes from 192.168.188.203:icmp_seq=7 ttl=128 time=0.569 ms64 bytes F Rom 192.168.188.203:icmp_seq=8 ttl=128 time=0.604 ms64 bytes from 192.168.188.203:icmp_seq=9 ttl=128 time=1.19 ms64 byte  s from 192.168.188.203:icmp_seq=10 ttl=128 time=0.643 ms---192.168.188.203 PING statistics---packets transmitted, 10 Received, 0% packet loss, time 9010msrtt Min/avg/max/mdev = 0.469/0.758/1.533/0.321 ms  

From the output results, the detection of host survival status is to detect the host can ping. The result report returned by the ping command, the most important one is the packet loss rate. When the host outage, the packet loss rate will be 100%, if the host is normal online, the packet loss rate will be 0%. In fact, when the packet loss rate is greater than 20%, the network connection status is already problematic.

Based on the above analysis, it is possible to set a threshold value of 20% for the triggering warning. When the packet loss rate is greater than 20%, you can send an email.

Next, as long as you can get the packet loss rate on it. In what way? Look at the answer script below.

3. Specific scripts
#!/bin/bashIP="110.110.110.114"to_mail="[email protected]"  # 你自己用来接收警告信息的邮箱地址while true  : doresult=`ping -c 10 $IP | grep "received" | awk -F‘received, |%‘ ‘{print $2}‘`if [ -z $result ];then  echo "script sth wrong."  exitelif [ $result -ge 20 ];then  # 这个python 脚本是用来实现发送邮件功能的,请参考  python /usr/local/sbin/work/mail.py $to_mail "host down"  "$IP is down"fisleep 30done

Analysis

    1. If you have a command in the script: Ping-c $IP | grep "Received" | Awk-f ' received, |% ' {print $} ', running is not very understanding, then you can follow the pipeline from left to right to execute again.

    2. Here's a technique for awk, awk-f options, which is very flexible to use. For example:-F ' #|: ', indicates that the delimiter can be either "#" or ":".

      So, back to our exercise,-f ' received, |% ', that means the delimiter is "received," note that received finally has a space, and the delimiter can also be "%".

    3. The variable result stores the packet drop rate. If condition, first determine whether the variable is empty, if empty, the script has a problem.

      If the variable result is not problematic and the drop rate is greater than 20, the Python script is called to send the message.

      The Python script references the following script.

      ?

Mail send script, reference:

[[email protected] work]# cat mail.py #!/usr/bin/env python#-*-coding:utf-8-*-import os,sysreload (SYS) Sys.setdefaultencoding (' UTF8 ') import getoptimport smtplibfrom email. Mimetext Import mimetextfrom Email. Mimemultipart Import mimemultipartfrom subprocess import *def sendqqmail (Username,password,mailfrom,mailto,subject,        Content): Gserver = ' smtp.163.com ' gport = try:msg = Mimetext (Unicode (content). Encode (' Utf-8 '))        Msg["from" = Mailfrom msg[' to '] = mailto msg[' reply-to '] = mailfrom msg[' Subject '] = Subject SMTP = Smtplib. SMTP (Gserver, Gport) smtp.set_debuglevel (0) Smtp.ehlo () Smtp.login (Username,password) Smtp.sen DMail (Mailfrom, mailto, msg.as_string ()) Smtp.close () except Exception,err:print "Send Mail failed. Error:%s "% errdef Main (): To=sys.argv[1] subject=sys.argv[2] content=sys.argv[3]# #定义发送警告信息的邮箱的账号和密码, # #你需要修改成你自己 Account number and password (please do not # #把真实的用户名和密码放到网上公开, otherwise you will die badly), # #我测试用的是163 NetEase's mailbox Sendqqmail (' [email protected] ', ' 888888 ', ' [email protected] ', to,subject,content) if __name__ = = "__ Main__ ": Main () # # # # # # # # #脚本使用说明 ###### #1. First, define the email account number and password # # in the script. Script execution commands are: Python mail.py target Mailbox "message subject" "Message content"

Analysis

The script that sends the mail, uses Python, needs the reader to expand the learning to understand.

4. Practice Results

Because 110.110.110.114 is a IP I assume comes out, so, certainly ping is different.

After running the shell script in the background, you will be able to receive the host downtime information in my QQ mailbox [email protected].

5. Conclusion

Today's exercises need to detect the status of the host, and then send an email notification. Functionality is simple, but for beginners, Python scripting can be a challenge. Writing scripts rarely write once can be 100% successful, so we need to write more practice, more debugging.

Daily Shell Exercises (04)

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.