python 远程开启/关闭服务[python,spur]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 远程开启/关闭服务[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()

以上是关于python 远程开启/关闭服务[python,spur]的主要内容,如果未能解决你的问题,请参考以下文章

Python:远程服务器关闭后自动重新连接 ssh 隧道

#yyds干货盘点# 云服务器的CDN域名的远程鉴权配置,基于 Python

关于python利用thrift远程连接hive的问题

云服务器的CDN域名的远程鉴权配置,基于 Python

Python命令开启http.server服务器

如何在远程节点上使用selenium上传文件[Python] [关闭]