Skip to content

Instantly share code, notes, and snippets.

@miticojo
Created June 12, 2016 07:20
Show Gist options
  • Save miticojo/e6666f45ae310d3013ac82973d5f97ae to your computer and use it in GitHub Desktop.
Save miticojo/e6666f45ae310d3013ac82973d5f97ae to your computer and use it in GitHub Desktop.
Execute passed command if IP present on machine (cluster util)
#!/usr/bin/env python
__author__ = 'Giorgio Crivellari'
__version__ = "0.1"
import os
import sys
import re
import subprocess
import socket
from subprocess import call
def checkLocalIPs(ip):
"""
Return True if passed IP is on local machine
:rtype : Boolean
"""
ret = []
co = subprocess.Popen(['ifconfig'], stdout=subprocess.PIPE)
ifconfig = co.stdout.read()
ip_regex = re.compile(
'((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-5][0-9]|[01]?[0-9][0-9]?))')
for match in ip_regex.findall(ifconfig, re.MULTILINE):
if ip in match[0]: return True
return False
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.stderr.write("CMDVIP execute passed command only when VIP is assigned on a local network interface.\n\n"
"Usage:\n\t"
"cmdvip <VIP> <COMMAND>\n"
)
sys.exit(1)
if os.getuid() != 0:
sys.stderr.write("User must have root privileges to check network interfaces")
hostname = sys.argv[1]
command = sys.argv[2:]
try:
addr = socket.gethostbyname(hostname)
except socket.gaierror, ex:
sys.stderr.write("VIP %s has no resolution." % hostname)
sys.exit(2)
if checkLocalIPs(addr):
#call(command)
os.startfile(command)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment