Operation: A meeting of Windows+python+route

Source: Internet
Author: User
Tags python script

    • Himself

As a network operations engineer, has been fascinated by scripting language since he contacted Linux. From the Shell to Java to the expect to python, slowly become accustomed to writing operations tools to solve the daily operations and maintenance problems.

This write operation tools let me get to a lot of new skills, I feel it is necessary to put thoughts, process detailed records, so that later review review. The tool is actually a Python program used to detect routes on Windows. I am a python chicken, please all the way the great God to teach more!


    • Function Description:

Every day 4 o'clock in the morning from the remote server to obtain the specified list of scheduled domain names, the scheduling domain names are parsed. TRACERT path tracking for each IP in the parsing results. If the specified egress node is not in the path, the detection failure is determined. The IP that detects the failed domain name is written into the message body. If the message body content is not empty, it means that there is a failed domain name detected, sending the message to the designated OPS mailbox.


    • Implementation ideas:

1, Linux in order to implement a daily 4 o'clock in the morning to execute a program, the use of contab will be very convenient. But in the Windows system to implement regular execution, it is necessary to use the Windows comes with the task and plan (let the program every time, sleep 24 hours can also be achieved, but the effect is certainly not task and planning and flexibility);

2, the use of wget way from the remote server to get the list of scheduled domain name (feel wget than ftp\tftp to come to a more powerful Tintin), the rest of the parsing, detection, send mail and so on with Python script implementation. Python is selected because Python scripts can also be used on Linux systems for easy post-adjustment. (It feels cygwin to run shell scripts or Java without the convenience of Python);

    • Implementation process:

1, on the remote server 1.1.1.1 to put the designated list of scheduled domain name, open Apache service

[Email protected] ~]# Cat/var/www/html/diaodu.txt Data.video.qiyi.comg3.letv.comk.youku.compl.youku.comdata.vod.itc.cnv2.tudou.comips.ifeng.comv.iask.comwtv.v.iask.comvv.v Ideo.qq.comzb.v.qq.com

2, using Python to get a list of scheduling domain names, and complete the analysis, detection and a series of functions

# coding:utf-8 "" "Document Description: The software is used to dispatch automatic detection 1, from the server wget dispatch domain Name list file 2, read the scheduled domain name from the file and Tracert3, Judge tracert results, If the path contains 30.207.4.250 indicates that the schedule is normal 4, if not normal, trigger the alarm, issue the alarm message 5, in the task and plan of Windows, execute the Python script 6 on a daily basis, run the log output directly in the cmd window (optional) "" "#-----Important: Will ' Node name ' changed to the corresponding node name, such as Nap= ' Hebei ' #----------Import module-----------import smtplibimport subprocess,refrom  email.mime.text import mimetext#----------Mail Send function-----------def sendmail ():              #定义发送邮件的函数     nap= ' Guizhou '           #给本机定义个名称, which test machine emits     sender= ' iptracker2<[for recipient-differentiated messages Email protected]> '     #发件人昵称及邮箱地址     receivers=[' [email  Protected] ', ' [email protected] ', ' [email protected] ']    subject=nap+ ' dispatch detection anomaly found!!! '          #邮件标题          Smtpserver= ' smtp.163.com '                  #发件人邮箱smtp服务器设置      Username= ' [email protected] '          #发件人邮箱账号      password= ' 123456 '                   #发件人邮箱密码     content= "\ n". Join (detected)           #列表detected中每个元素以回车分割, returns a string     print  (' exception content is: ' +content)           #将content内容打印         msg=mimetext ( Content, ' text ', ' utf-8 ')     msg[' Subject ']=subject    msg[' to ']= '; Join (receivers)          #列表receivers元素以分号分隔     msg[ ' From ']=sender    smtp=smtplib. SMTP ()     smtp.connect (' smtp.163.com ')     smtp.logiN (Username,password)     smtp.sendmail (sender,recivers,msg.as_string ())      smtp.close () #----------get the Dispatch domain name file-----------#下载日志记录于wgetlog. txt, the download file is saved in c:/python34 to diaodu.txt command print   ("Get started File") Subprocess.call (' Wget -a wgetlog.txt -o diaodu.txt -p c:\ Python34 http://1.1.1.1/diaodu.txt ') print  ("file updated") #----------resolve the scheduled domain name, get the dispatch IP----------r_getip=r ' \d+\. +\d+\.+\d+\.+\d+ '      #定义过滤IP地址的正则表达式file =open ("C:\Python34\diaodu.txt")           #打开文件file. Seek (0,0)               #设置指针到行首r_watone =r ' 30.207.4.250|30.207.6.154|10.30.96.10 '     #定义指定出口的正则表达式detected =[ ]count=1for name in file:         #遍历调度域名列表      name=name.strip (' \ n ')          #去除域名后面的 \ n symbol to prevent parsing errors      resolve=subpRocess.getoutput (' nslookup  ' +name)      #解析调度域名, save the results in resolve     Track_ip=re.findall (r_getip,resolve)         track_ip.pop (0)           #过滤出resolve中所有的IP地址 and remove the first IP (the first IP is the DNS address)                  print  (name+ ' resolution succeeded, IP is: ')      print  (TRACK_IP)     print  (' Start checking these IPs individually, wait patiently ... ') #--- ------Tracking the dispatch IP and judging---------    for ip in track_ip:          #对解析出来的IP遍历         traceroute= Subprocess.getoutput (' tracert -d  ' +ip)      #保存路径跟踪结果          find=re.findall (R_watone,traceroute)              if len (Find) ==0:&NBsp;        #在路径中搜索出口IP并放入列表find, if the length of 0 means not to go from the exit              detected.append (name+ "corresponding IP:" +ip+ "Detection failed!) ")              #将检测到域名及IP放入列表detected中      print  ("+str (count) +" Domain detection end!) ")     count+=1       #-----exception information to organize and send an alert message---------try:     if len (detected)!=0:     #若detected列表长度不为0, representing domain name and IP being written          print  ("Discovery")          SendMail ()              #发送告警邮件          print  ("Mail has been sent!     else:        print  ("No anomalies found this time") except  Exception:    print  ("program has an exception") finally:     close=file.close ()          #关闭文件if  close  is None:    print  ("File closed successfully, detection ended! ")      #确认文件关闭成功else:    print  (" File close failed, please check! ")

3, in order to protect the file is not modified by others, speed up the execution of the script, the Python script to compile. Copy the compiled PYc file to the C:/python34 directory and change the name to IPTRACKER2.PYC

>>> Import py_compile>>> py_compile.compile (' c:/python34/iptracker2.py ') ' C:/python34\\__pycache __\\iptracker2.cpython-34.pyc ' >>>

4. Copy the Wget.exe to the C:/python34 directory and create a batch file Auto.bat to create the task and plan later. Open Auto.bat with Notepad, write:

CD C:/python34python C:\PYTHON34\IPTRACKER2.PYC

5, create tasks and plans, open Control Panel--management tools--tasks and plans

①, Click ' Create Task ' at the top right of the page

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/79/94/wKiom1aVCNfDVfjrAAB31aCCWqE224.png "title=" QQ picture 20160112220404.png "alt=" Wkiom1avcnfdvfjraab31accwqe224.png "/>

②, fill in the Task name and choose whether or not the user is logged in is executed (this way does not pop up the cmd interface, directly in the background run)

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/79/93/wKioL1aVCQmzoz5YAACup1RhbK0343.png "title=" QQ picture 20160112220431.png "alt=" Wkiol1avcqmzoz5yaacup1rhbk0343.png "/>

④, new Trigger, select 4 hours per day as the trigger condition.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/79/93/wKioL1aVCQrhoAeFAADw9xMfNQk520.png "title=" QQ picture 20160112220445.png "alt=" Wkiol1avcqrhoaefaadw9xmfnqk520.png "/>

⑤, create action, execute batch script auto.bat

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/79/94/wKiom1aVCNuBCrt5AACqW2-J7oc981.png "title=" QQ picture 20160112220456.png "alt=" Wkiom1avcnubcrt5aacqw2-j7oc981.png "/>

⑥ the following two tick in settings to prevent task execution from failing. Click Confirm, enter the Windows password click to confirm

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/79/94/wKiom1aVCNyR1JEGAAB9AqDt4b4596.png "title=" QQ picture 20160112220505.png "alt=" Wkiom1avcnyr1jegaab9aqdt4b4596.png "/>

⑦, Viewing the task IpTracker2 status in the task List is ready, indicating that the creation was successful

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/79/94/wKiom1aVCN3jBwS4AAChiXYX1hw815.png "title=" QQ picture 20160112220515.png "alt=" Wkiom1avcn3jbws4aachixyx1hw815.png "/>

    • Results display, Alarm message content:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/79/93/wKioL1aVEu3CHQdBAAAcHxea65o590.png "title=" QQ picture 20160112225015.png "alt=" Wkiol1aveu3chqdbaaachxea65o590.png "/>


This article is from the "Tiandaochouqin" blog, make sure to keep this source http://cckevin.blog.51cto.com/3934525/1734392

Operation: A meeting of Windows+python+route

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.