Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys, time, os, uuid, re
- import pycurl, pexpect
- import atexit
- import subprocess
- import threading
- import shlex
- from pipes import quote#@TODELETE
- actions = ["status", "on", "off", "reboot"]
- def get_power_status(_, options):
- output = run_command(options, create_command(options, "status"))
- match = re.search('[Cc]hassis [Pp]ower is [\\s]*([a-zA-Z]{2,3})', str(output))
- status = match.group(1) if match else None
- return status
- def set_power_status(_, options):
- run_command(options, create_command(options, options["--action"]))
- return
- def reboot_cycle(_, options):
- output = run_command(options, create_command(options, "cycle"))
- return bool(re.search('chassis power control: cycle', str(output).lower()))
- def create_command(options, action):
- cmd = options["--ipmitool-path"]
- # --lanplus / -L
- if "--lanplus" in options and options["--lanplus"] in ["", "1"]:
- cmd += " -I lanplus"
- else:
- cmd += " -I lan"
- # --ip / -a
- cmd += " -H " + options["--ip"]
- # --username / -l
- if "--username" in options and len(options["--username"]) != 0:
- cmd += " -U " + quote(options["--username"])
- # --auth / -A
- if "--auth" in options:
- cmd += " -A " + options["--auth"]
- # --password / -p
- if "--password" in options:
- cmd += " -P " + quote(options["--password"])
- else:
- cmd += " -P ''"
- # --cipher / -C
- if "--cipher" in options:
- cmd += " -C " + options["--cipher"]
- # --port / -n
- if "--ipport" in options:
- cmd += " -p " + options["--ipport"]
- if "--privlvl" in options:
- cmd += " -L " + options["--privlvl"]
- # --action / -o
- cmd += " chassis power " + action
- # --use-sudo / -d
- if "--use-sudo" in options:
- cmd = options["--sudo-path"] + " " + cmd
- return cmd
- def run_command(options, command, timeout=None, env=None):
- if timeout is None and "--power-timeout" in options:
- timeout = options["--power-timeout"]
- if timeout is not None:
- timeout = float(timeout)
- try:
- process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
- except OSError:
- print("Unable to run %s\n" % command)
- sys.exit(1)
- thread = threading.Thread(target=process.wait)
- thread.start()
- thread.join(timeout)
- if thread.is_alive():
- process.kill()
- print "Connection timed out"
- sys.exit(1)
- status = process.wait()
- (pipe_stdout, pipe_stderr) = process.communicate()
- process.stdout.close()
- process.stderr.close()
- return (status, pipe_stdout, pipe_stderr)
- def get_multi_power_fn(connection, options, get_power_fn):
- status = "off"
- plugs = options["--plugs"] if "--plugs" in options else [""]
- for plug in plugs:
- try:
- options["--uuid"] = str(uuid.UUID(plug))
- except ValueError:
- pass
- except KeyError:
- pass
- options["--plug"] = plug
- plug_status = get_power_fn(connection, options)
- if plug_status != "off":
- status = plug_status
- return status
- def set_multi_power_fn(connection, options, set_power_fn, get_power_fn, retry_attempts=1):
- plugs = options["--plugs"] if "--plugs" in options else [""]
- for _ in range(retry_attempts):
- for plug in plugs:
- try:
- options["--uuid"] = str(uuid.UUID(plug))
- except ValueError:
- pass
- except KeyError:
- pass
- options["--plug"] = plug
- set_power_fn(connection, options)
- time.sleep(int(options["--power-wait"]))
- for _ in range(int(options["--power-timeout"])):
- if get_multi_power_fn(connection, options, get_power_fn) != options["--action"]:
- time.sleep(1)
- else:
- return True
- return False
- def fence_action(connection, options, set_power_fn, get_power_fn, get_outlet_list=None, reboot_cycle_fn=None):
- result = 0
- try:
- status = None
- if not "no_status" in options["device_opt"]:
- status = get_multi_power_fn(connection, options, get_power_fn)
- if status != "on" and status != "off":
- sys.exit(1)#@TODELETE fail(EC_STATUS)
- if options["--action"] == status:
- if not (status == "on" and "force_on" in options["device_opt"]):
- print("Success: Already %s" % (status.upper()))
- return 0
- if options["--action"] == "on":
- if set_multi_power_fn(connection, options, set_power_fn, get_power_fn, 1 + int(options["--retry-on"])):
- print("Success: Powered ON")
- else:
- sys.exit(1)#@TODELETE fail(EC_WAITING_ON)
- elif options["--action"] == "off":
- if set_multi_power_fn(connection, options, set_power_fn, get_power_fn):
- print("Success: Powered OFF")
- else:
- sys.exit(1)#@TODELETE fail(EC_WAITING_OFF)
- elif options["--action"] == "reboot":
- power_on = False
- if options.get("--method", "").lower() == "cycle" and reboot_cycle_fn is not None:
- for _ in range(1, 1 + int(options["--retry-on"])):
- if reboot_cycle_fn(connection, options):
- power_on = True
- break
- if not power_on:
- sys.exit(1)#@TODELETE fail(EC_TIMED_OUT)
- else:
- if status != "off":
- options["--action"] = "off"
- if not set_multi_power_fn(connection, options, set_power_fn, get_power_fn):
- sys.exit(1)#@TODELETE fail(EC_WAITING_OFF)
- options["--action"] = "on"
- try:
- power_on = set_multi_power_fn(connection, options, set_power_fn, get_power_fn, int(options["--retry-on"]))
- except Exception as ex:
- print("%s", str(ex))
- if power_on == False:
- print('Timed out waiting to power ON\n')
- print("Success: Rebooted")
- elif options["--action"] == "status":
- print("Status: " + status.upper())
- if status.upper() == "OFF":
- result = 2
- elif options["--action"] == "monitor":
- pass
- except pexpect.EOF:
- sys.exit(1)#@TODELETE fail(EC_CONNECTION_LOST)
- except pexpect.TIMEOUT:
- sys.exit(1)#@TODELETE fail(EC_TIMED_OUT)
- except pycurl.error as ex:
- print("%s\n", str(ex))
- sys.exit(1)#@TODELETE fail(EC_TIMED_OUT)
- except socket.timeout as ex:
- print("%s\n", str(ex))
- sys.exit(1)#@TODELETE fail(EC_TIMED_OUT)
- return result
- def atexit_handler():
- try:
- sys.stdout.close()
- os.close(1)
- except IOError:
- print ("%s failed to close standard output\n", sys.argv[0])
- sys.exit(1)
- def fence_ipmilan_main(ip, username, password, action):
- atexit.register(atexit_handler)
- options = {'--ipmitool-path': '/usr/bin/ipmitool', '--ipport': '623', '--power-timeout': '20','--privlvl': 'ADMINISTRATOR', '--method': 'ONOFF', '--delay': '0',
- 'device_opt': ['ipaddr', 'login', 'no_login', 'no_password', 'passwd', 'diag', 'lanplus', 'auth', 'cipher', 'privlvl', 'sudo', 'ipmitool_path', 'method', 'ipport', 'inet4_only', 'inet6_only',
- 'passwd_script', 'sudo_path', 'help', 'debug', 'verbose', 'version', 'action', 'agent', 'power_timeout', 'shell_timeout', 'login_timeout', 'power_wait', 'retry_on', 'delay', 'port_as_ip', 'port', 'separator'],
- '--separator': ',', '--shell-timeout': '3', '--power-wait': 2, '--retry-on': '1', '--sudo-path': '@SUDO_PATH@', '--lanplus': '', '--login-timeout': '5'}
- if action not in actions:
- print "Action not supported!"
- sys.exit(1)
- options['--action'] = action
- options['--ip'] = ip
- options['--username'] = username
- options['--password'] = password
- result = fence_action(None, options, set_power_status, get_power_status, None, reboot_cycle)
- sys.exit(result)
- if __name__ == "__main__":
- fence_ipmilan_main(ip='*.*.*.*', username='username', password="password", action="status")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement