Skip to content

Instantly share code, notes, and snippets.

@kornicameister
Created March 1, 2016 11:52
Show Gist options
  • Save kornicameister/78d9aed7b46deedb0eef to your computer and use it in GitHub Desktop.
Save kornicameister/78d9aed7b46deedb0eef to your computer and use it in GitHub Desktop.
Remotely turn on/off services [python, spur]
import random
import time
import spur
import multiprocessing
IT=0
HOST_LIST = {
"192.168.10.4": True,
"192.168.10.6": True,
"192.168.10.7": True,
"192.168.10.8": True
}
BOOL_TO_COMMAND = {
True: 'start',
False: 'stop'
}
COMMAND_TPL = 'sudo systemctl %s monasca-log-transformer'
def pick_random_host():
global IT
keys = HOST_LIST.keys()
length = len(keys)
if IT == length:
IT = 0
key = keys[IT]
IT += 1
return key
def get_command(val):
return COMMAND_TPL % BOOL_TO_COMMAND.get(val)
def run():
print 'Entering the loop, changing status by 60 seconds'
print 'Initial state of hosts %s' % HOST_LIST
while True:
print 'Waiting for 30 seconds'
time.sleep(30)
print '---------------------------------------------------------------'
try:
host_ip = pick_random_host()
status = HOST_LIST[host_ip]
command = get_command(not status)
HOST_LIST[host_ip] = not status
shell = spur.SshShell(hostname=host_ip,
port=22,
private_key_file=(
'/home/kornicameister/.ssh/id_rsa'),
missing_host_key=spur.ssh.MissingHostKey.accept,
username='vagrant',
password='vagrant')
res = shell.run(command.split(' '))
print '[', host_ip, ']', '[', HOST_LIST[
host_ip], ']', command, \
res.return_code, \
res.output
except Exception:
pass
print '---------------------------------------------------------------'
if __name__ == '__main__':
process = multiprocessing.Process(target=run)
process.start()
process.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment