优云智算,python开机关机脚本

开机关机脚本,实测,可以在实例中实现关机.需要填写自己的public_key和private_key ssh密码看不到,为了方便,也可以填上去
sdk安装 pip install --upgrade ucloud-sdk-python3

# -*- coding: utf-8 -*-
from ucloud.core import exc
from ucloud.client import Client
import inspect
import sys
import time
client = Client({
    "region": "cn-wlcb", # always cn-wlcb
    "public_key": "",  #  public_key and private_ket can be got from https://console.compshare.cn/uaccount/api_manage
    "private_key": "",
    "base_url": "https://api.compshare.cn" # always https://api.compshare.cn
})
# pip install --upgrade ucloud-sdk-python3
ssh_passwd = ''

current_state = 0
def main_get_func():
    """
    \n\n\n=== 使用 inspect 模块 ===
    类名: UCompShareClient

    方法:
    create_comp_share_instance
    create_ul_host_instance
    describe_comp_share_instance
    describe_ul_host_bundles
    describe_ul_host_instance
    get_ul_host_instance_price
    get_ul_host_renew_price
    invoke
    logged_exception_handler
    logged_request_handler
    logged_response_handler
    modify_ul_host_attribute
    poweroff_ul_host_instance
    reboot_comp_share_instance
    reboot_ul_host_instance
    reinstall_comp_share_instance
    reinstall_ul_host_instance
    reset_comp_share_instance_password
    reset_ul_host_instance_password
    start_comp_share_instance
    start_ul_host_instance
    stop_comp_share_instance
    stop_ul_host_instance
    terminate_comp_share_instance
    terminate_ul_host_instance

    属性:
    config = <ucloud.core.client._cfg.Config object at 0x7fe6315dddf0>
    credential = <ucloud.core.auth._cfg.Credential object at 0x7fe6315dddc0>
    logger = <Logger ucloud (INFO)>
    middleware = <ucloud.core.utils.middleware.Middleware object at 0x7fe6315b13d0>
    transport = <ucloud.core.transport._requests.RequestsTransport object at 0x7fe6313b1a00>
    """
    result = client.ucompshare()

    print("\n\n\n=== 使用 inspect 模块 ===")
    print(f"类名: {type(result).__name__}")

    # 获取所有成员
    members = inspect.getmembers(result)

    print("\n方法:")
    for name, member in members:
        if not name.startswith('_') and inspect.ismethod(member):
            print(f"  {name}")

    print("\n属性:")
    for name, member in members:
        if not name.startswith('_') and not inspect.ismethod(member) and not inspect.isfunction(member):
            print(f"  {name} = {member}")

def main_state():
    global ssh_passwd
    result = client.ucompshare().describe_comp_share_instance()  # 获取实例
    """
    {'TotalCount': 1, 'UHostSet': [{'Name': 'yolo_pytorch','State': 'Running', 'UHostId': 'uhost-1m5k20', 'Zone': 'cn-wlcb-01'}]}
    """

    print("\n\n\n=== 使用 inspect 模块 ===")
    print("func_state")
    total_count = result.get('TotalCount', 0)  # 提供默认值
    print(f"总实例数: {total_count}")
    print("-" * 60)
    for UHost in result.get('UHostSet', []):  # 默认为空列表
        print(f"名称:   {UHost.get('Name', 'none')}")
        print(f"状态:   {UHost.get('State', 'none')}")
        print(f"实例ID: {UHost.get('UHostId', 'none')}")
        print(f"可用区: {UHost.get('Zone', 'none')}")
        print(f"镜像:   {UHost.get('OsName', 'none')} {UHost.get('OsType', 'none')} {UHost.get('CompShareImageName', 'none')}")
        print(f"系统盘: {UHost.get('TotalDiskSpace', 0)}G")
        print(f"规格:   {UHost.get('CPU', 0)}核 {int(UHost.get('Memory', 0)/1024)}G")
        print(f"GPU:    {UHost.get('GPU', 0)}个{UHost.get('GpuType', 'none')}")
        print("-" * 30)
        print(f"SSH账号: {UHost.get('SshLoginCommand', 'none')}")
        print(f"SSH密码: {ssh_passwd}")
        print(f"系统密码: {UHost.get('Password', 'none')}")
        for soft in UHost.get('Softwares', []):
            print(f"{soft.get('Name', 'none')}: {soft.get('URL', 'none')}")
        print("-" * 60)

def main_stop():
    global current_state
    global ssh_passwd
    result = client.ucompshare().describe_comp_share_instance()  # 获取实例
    """
    {'TotalCount': 1, 'UHostSet': [{'Name': 'yolo_pytorch','State': 'Running', 'UHostId': 'uhost-1m5k20', 'Zone': 'cn-wlcb-01'}]}
    """

    print("\n\n\n=== 使用 inspect 模块 ===")
    print("func_stop")
    total_count = result.get('TotalCount', 0)  # 提供默认值
    print(f"总实例数: {total_count}")
    print("-" * 60)
    err=0
    for UHost in result.get('UHostSet', []):  # 默认为空列表
        print(f"名称:   {UHost.get('Name', 'none')}")
        print(f"状态:   {UHost.get('State', 'none')}")
        print(f"实例ID: {UHost.get('UHostId', 'none')}")
        print(f"可用区: {UHost.get('Zone', 'none')}")
        print(f"镜像:   {UHost.get('OsName', 'none')} {UHost.get('OsType', 'none')} {UHost.get('CompShareImageName', 'none')}")
        print(f"系统盘: {UHost.get('TotalDiskSpace', 0)}G")
        print(f"规格:   {UHost.get('CPU', 0)}核 {int(UHost.get('Memory', 0)/1024)}G")
        print(f"GPU:    {UHost.get('GPU', 0)}个{UHost.get('GpuType', 'none')}")
        print("-" * 30)
        print(f"SSH账号: {UHost.get('SshLoginCommand', 'none')}")
        print(f"SSH密码: {ssh_passwd}")
        print(f"系统密码: {UHost.get('Password', 'none')}")
        for soft in UHost.get('Softwares', []):
            print(f"{soft.get('Name', 'none')}: {soft.get('URL', 'none')}")
        print("-" * 60)
        # print(UHost)
        if UHost.get('State', 'none').lower()=="running":
            current_state+=1
            res=client.ucompshare().stop_comp_share_instance({
                'UHostId': UHost.get('UHostId', 'none'), 
                'Zone': UHost.get('Zone', 'none')
            })
            print("-" * 60)
            print(res)
            print("-" * 60)
        elif UHost.get('State', 'none').lower()=="stopped":
            err+=1
    # 全部关机
    if err>=total_count:
        current_state=-1


def main_start(WithoutGpu=True):
    global ssh_passwd
    result = client.ucompshare().describe_comp_share_instance()  # 获取实例
    """
    {'TotalCount': 1, 'UHostSet': [{'Name': 'yolo_pytorch','State': 'Running', 'UHostId': 'uhost-1m5k20', 'Zone': 'cn-wlcb-01'}]}
    """

    print("\n\n\n=== 使用 inspect 模块 ===")
    print("func_start->WithoutGpu:",WithoutGpu)
    total_count = result.get('TotalCount', 0)  # 提供默认值
    print(f"总实例数: {total_count}")
    print("-" * 60)
    for UHost in result.get('UHostSet', []):  # 默认为空列表
        print(f"名称:   {UHost.get('Name', 'none')}")
        print(f"状态:   {UHost.get('State', 'none')}")
        print(f"实例ID: {UHost.get('UHostId', 'none')}")
        print(f"可用区: {UHost.get('Zone', 'none')}")
        print(f"镜像:   {UHost.get('OsName', 'none')} {UHost.get('OsType', 'none')} {UHost.get('CompShareImageName', 'none')}")
        print(f"系统盘: {UHost.get('TotalDiskSpace', 0)}G")
        print(f"规格:   {UHost.get('CPU', 0)}核 {int(UHost.get('Memory', 0)/1024)}G")
        print(f"GPU:    {UHost.get('GPU', 0)}个{UHost.get('GpuType', 'none')}")
        print("-" * 30)
        print(f"SSH账号: {UHost.get('SshLoginCommand', 'none')}")
        print(f"SSH密码: {ssh_passwd}")
        print(f"系统密码: {UHost.get('Password', 'none')}")
        for soft in UHost.get('Softwares', []):
            print(f"{soft.get('Name', 'none')}: {soft.get('URL', 'none')}")
        print("-" * 60)
        # print(UHost)
        if UHost.get('State', 'none').lower()=="stopped":
            res=client.ucompshare().start_comp_share_instance({
                'UHostId': UHost.get('UHostId', 'none'), 
                'Zone': UHost.get('Zone', 'none'),
                'WithoutGpu': WithoutGpu
            })
            print("-" * 60)
            print(res)
            print("-" * 60)


def do_run():
    global current_state
    while True:
        try:
            print("help: state start start_gpu active  stop")
            if len(sys.argv) > 1:
                first_arg = sys.argv[1].lower()  # 转换为小写以便比较
                print("cmd: ",first_arg)

                if first_arg in ['1', 'start']:
                    main_start(True)
                elif first_arg in ['2', 'start_gpu']:
                    main_start(False)
                elif first_arg in ['0', 'state']:
                    main_state()
                elif first_arg in ['-1', '4', 'stop']:
                    main_stop()
                    current_state=0
                elif first_arg in ['3', 'active']:
                    main_start()
                    time.sleep(30)
                    main_state()
                    time.sleep(30)
                    main_state()
                    time.sleep(30)
                    main_state()
                    time.sleep(30)
                    main_state()
                    time.sleep(30)
                    main_state()
                    time.sleep(30)
                    main_stop()
                    current_state=0
                    time.sleep(30)
                    main_state()
                else:
                    main_stop()
            else:
                print("cmd: ","stop")
                main_stop()
        except exc.UCloudException as e:
            print(e)
        
        if current_state>0:
            time.sleep(60)  # 暂停 60 秒(即 1 分钟)# 为了防止想关机,但是没关掉的意外情况
        else:
            break


if __name__ == '__main__':
    do_run()
    pass
posted @ 2026-01-27 17:42  小城熊儿  阅读(0)  评论(0)    收藏  举报