Skip to content

Instantly share code, notes, and snippets.

@sschmeier
Created February 18, 2017 19:08
Show Gist options
  • Save sschmeier/1c45ee393aa2d4e200f4122bf5ef1fd2 to your computer and use it in GitHub Desktop.
Save sschmeier/1c45ee393aa2d4e200f4122bf5ef1fd2 to your computer and use it in GitHub Desktop.
Ping server and calc package loss. If loss, sent message to slack channel.
#!/usr/bin/env python
import sys, subprocess, requests
def msg2slack(msg, channel, user):
url = "<URL>" # your Slack incomming webhook url
payload = {"channel": '#%s' % channel,
"username": user,
"text": msg,
"icon_emoji": ":computer:"}
r = requests.post(url, json=payload)
# for testing uncomment:
result = r.text
print(result)
def main():
hosts = ['<host1>', '<host2>', ...]
for hostname in hosts:
# We will ping a server 10 time and calc package loss.
# If it loss detected we shoot off a message
cmd = "ping -c 10 %s | grep -oP '\d+(?=%% packet loss)'"
proc = subprocess.Popen([cmd % hostname],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
(out, err) = proc.communicate()
# package loss?
if int(out)>0 or err:
# message to slack
msg2slack(msg="%s cannot be reached" % hostname,
channel="mynotes",
user="webhookbot")
if __name__=='__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment