Snippets

Edel SM ZENORADIO Scripts

Created by Edelberto Mania last modified
#!/usr/bin/env python
# query nagios page and print servers' name and ip in csv
# Edelberto Mania <ed@zenoradio.com>
# 20160801

import requests
from bs4 import BeautifulSoup

nagios_page='https://nagios.zenoradio.com/nagios/cgi-bin/status.cgi?hostgroup=all&style=overview'
username='edz-test'
password='XXXX'

enabled_ssl_warning=True

if enabled_ssl_warning:
    ## 2-line, to silence SSL warning
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

r=requests.get(nagios_page,auth=(username,password),verify=False)

if r.status_code==200:
    s=BeautifulSoup(r.text,'html.parser')
    for t in s.find_all('a'):
        if t.get('title') is not None:
            print('{0},{1}'.format(t.string,t.get('title')))
            
#!/usr/bin/env python
# script to check /_zstatus and checks RTAPI nodes been took out and put in route
# and sends slack and email message 
# Edelberto Mania <ed@zenoradio.com>
# 20160707

node_env='STAGING'
rtapi="https://stage-rtapi.zenoradio.com/_zstatus"
#rtapi="https://rtapi-lb.zenoradio.com/_zstatus"

slack_webhook_url='https://hooks.slack.com/services/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'
slack_channel='edel_s-playground' # system-status, zeno-sysadmins

email_username='noreply@zenoradio.com'
email_password='XXXX'
email_server='smtp.gmail.com:587'
email_from='RTAPI Node Messenger <noreply@zenoradio.com>'
email_to=['ed@zenoradio.com','ed@zenoradio.com']
email_cc=['edel@iconstrategiesbpo.com']
email_bcc=['sierra2@gmail.com']

import requests,json,sys,datetime,smtplib,email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from socket import gethostname
from time import sleep

def send_slack_message(webhook_url=None,bot_name='bot',channel=None,message=None,emoji=None):
    if bot_name is not None: bot_name=gethostname()
    if channel is None:channel=slack_channel
    if webhook_url is None:webhook_url=slack_webhook_url
    slack_data={"channel": "#{0}".format(channel),"username":bot_name,"text":message,"icon_emoji":emoji}
    m=requests.post(webhook_url,data=json.dumps(slack_data),headers={'content-type':'application/json'})
    return(m)

def send_email(
    from_addr,
    to_addrs,
    cc_addrs,
    bcc_addrs,
    subject,
    message,
    login,password,smtpserver='smtp.gmail.com:587',secured=False):
    message_id=email.utils.make_msgid()
    
    msg=MIMEMultipart('alternative')
    msg['Subject']=subject
    msg['From']=from_addr
    msg['To']='%s\n'%','.join(to_addrs)
    msg['Cc']='%s\n'%','.join(cc_addrs)
    msg['Bcc']='%s\n'%','.join(bcc_addrs)
    msg.add_header("reply-to",from_addr) # does not work, even with plain email address
    msg.add_header("Message-ID",message_id)
    
    email_list=[]
    email_list.extend(to_addrs)
    email_list.extend(cc_addrs)
    email_list.extend(bcc_addrs)

    ## remove empty in the list (the u'') - yes, ugly line of code
    while u'' in email_list:email_list.remove(u'')
    
    part1=MIMEText(message,'plain')
    part2=MIMEText(message,'html')
    
    msg.attach(part1)
    msg.attach(part2)
    
    try:
        server=smtplib.SMTP(smtpserver)
        if secured:
            server.starttls()
            server.ehlo()
        else:server.ehlo()
        server.login(login,password)
        problems=server.sendmail(from_addr,email_list,msg.as_string())
        server.quit()
    except(Exception):return False
    return True

def query_rtapi_status(url):
    return(requests.get(url).text.split('\n'))
    
in_route=[]
out_of_route=[]
c=0

if __name__=='__main__':
    try:
        while(True):
            print 'routed:',in_route
            print 'not routed:',out_of_route
            in_route_total=len(in_route)
            out_of_route_total=len(out_of_route)
            r=query_rtapi_status(rtapi)
            for i in r:
                if i.endswith('up'):
                    h=i.strip().split()[0]
                    if h not in in_route:
                        if h in out_of_route:
                            out_of_route.remove(h)
                        in_route.append(i.split()[0])
                        if c>0: ## skip sending message when we'er starting up
                            _date=datetime.datetime.now().strftime("%a, %B %d %Y at %H:%M:%S")
                            _stats='{0}/{1}'.format(in_route_total+1,out_of_route_total-1)
                            subject='RTAPI node {0} is now IN route'.format(h)
                            message='[{1}] *{3}* node {0} is *now in route* ({2})'.format(h,_date,_stats,node_env)
                            send_slack_message(message=message)
                            message='{0}<br><br>You can also follow updates via https://zenoradio.slack.com/messages/{1}/<br><br>--<br>System-generated message. Please do not reply (ESM 20160707).'.format(message,slack_channel)
                            s=send_email(from_addr=email_from, to_addrs=email_to, cc_addrs=email_cc,bcc_addrs=email_bcc,subject=subject,message=message,login=email_username,password=email_password,smtpserver=email_server,secured=True)
                            print(s)
                elif i.endswith('DOWN'):
                    h=i.strip().split()[0]
                    if h not in out_of_route:
                        if h in in_route:
                            in_route.remove(h)
                        out_of_route.append(i.split()[0])
                        if c>0:
                            _date=datetime.datetime.now().strftime("%a, %B %d %Y at %H:%M:%S")
                            _stats='{0}/{1}'.format(in_route_total-1,out_of_route_total+1)
                            subject='RTAPI node {0} is now OUT of route'.format(h)
                            message='[{1}] *{3}* node {0} was *removed* from route ({2})'.format(h,_date,_stats,node_env)
                            send_slack_message(message=message)
                            message='{0}<br><br>You can also follow updates via https://zenoradio.slack.com/messages/{1}/<br><br>--<br>System-generated message. Please do not reply (ESM 20160707).'.format(message,slack_channel)
                            s=send_email(from_addr=email_from, to_addrs=email_to, cc_addrs=email_cc,bcc_addrs=email_bcc,subject=subject,message=message,login=email_username,password=email_password,smtpserver=email_server,secured=True)
                            print(s)
            c+=1
            sleep(1)
    except KeyboardInterrupt:
        print('Exiting...')
        sys.exit(0)        
    except:
        print('Unexpected error: ',sys.exc_info())        
        sys.exit(1)

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.