启动管理vm虚拟机

# /usr/bin/python3
'''
#命令管理虚拟机 list, running list, start,stop
https://askubuntu.com/questions/445284/how-to-start-a-virtualbox-machine-via-command-line-without-gui
vboxmanage list vms
vboxmanage startvm "k8s-node1" --type headless
vboxmanage controlvm "k8s-node1" poweroff
'''

import subprocess
import sys

# get vm list
def get_vm_list():
    try:
        commandResult = subprocess.Popen(["/usr/bin/vboxmanage", "list", "vms"], stdout=subprocess.PIPE)
        vm_list = (str(commandResult.communicate()[0], "UTF-8")).split("\n")
        if len(vm_list) == 0:
            sys.exit(2)
        return vm_list,None
    except Exception as e:
         return [],e

#get running vm list
def get_running_vms():
    vm_list = []
    try:
        command_result = subprocess.Popen(["/usr/bin/vboxmanage", "list", "runningvms"], stdout=subprocess.PIPE)
        vm_list = (str(command_result.communicate()[0], "UTF-8")).split("\n")
        if len(vm_list) == 0:
            sys.exit(2)
        return vm_list,None
    except Exception as e:
        return [],e

def start_vms():
    try:
        vm_list,err1 = get_vm_list()
        if err1 != None:
            print(f"get running vm list failed:{err1.__str__()}")
            sys.exit(2)
        running_vm_list,err2 = get_running_vms()
        if err2 != None:
            print(f"get running vm list failed:{err2.__str__()}")
            sys.exit(2)

        for vm in vm_list:
            if vm.__contains__("harbor-server") or str(vm).strip() == "":
                continue
            if vm in running_vm_list:
                print(f"【{vm}\tis already started")
                continue
            name = str(vm).strip().split()[0].replace('"','')
            commad = subprocess.Popen(["/usr/bin/vboxmanage","startvm", name,"--type","headless"],stdout=subprocess.PIPE).communicate()[0]
            print(str(f"{str(commad).strip()}"))
    except Exception as e:
        print(e.__str__())

def stop_vms():
    try:
        running_vm_list,err = get_running_vms()
        if err != None:
            print(f"get running vm list failed:{err.__str__()}")
            sys.exit(2)
        for vm in running_vm_list:
            if str(vm).strip() == "":
                continue
            print(str(f"Stop【{vm}】"))
            name = str(vm).strip().split()[0].replace('"','')
            command = subprocess.Popen(["/usr/bin/vboxmanage","controlvm", name,"poweroff"],stdout=subprocess.PIPE).communicate()[0]
            print(str(f"Stop【{vm}】:{str(command).strip()}"))
    except Exception as e:
        print(e)

def print_running_vms():
    run_list,err = get_running_vms()
    if err != None:
        print(f"get running vm list failed:{err.__str__()}")
        sys.exit(2)
    for vm in run_list:
        if str(vm).strip() == "":
            continue
        print(f"{vm}")

def print_vms_list():
    run_list,err = get_vm_list()
    if err != None:
        print(f"get running vm list failed:{err.__str__()}")
        sys.exit(2)
    for vm in run_list:
        if str(vm).strip() == "":
            continue
        print(f"{vm}")



if __name__ == "__main__":

    if len(sys.argv) < 2:
        print(f"usage: ./{sys.argv[0]} [list|running|start|stop]")
        sys.exit(0)
    else:
        if str(sys.argv[1]) == "":
            print(f"usage: ./{sys.argv[0]} [list|running|start|stop]")
            sys.exit(0)
        else:
            flag = str(sys.argv[1]).strip()
            if flag == "list":
                print_vms_list()
            elif flag == "running":
                print_running_vms()
            elif flag == "start":
                start_vms()
            elif flag == "stop":
                stop_vms()
            else:
                print(f"usage: .{sys.argv[0]} [list|running|start|stop|]")

上一篇:算法与数据结构-各种循环的时间复杂度分析(英语)


下一篇:SAP云平台CloudFoundry环境里route 超过quota的错误处理