如何使用python运行Azure CLI命令? [英] How to run Azure CLI commands using python?

查看:131
本文介绍了如何使用python运行Azure CLI命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Azure CLI获取资源组中所有VM的列表.但是我想使用python脚本实现相同的功能.

I want to use Azure CLI to get the list of all the VMs in my resource group. But I want to implement the same using a python script.

例如,我将在Azure CLI中使用以下命令列出我的资源组中的VM:

For example, I will use the following command in Azure CLI to list the VMs in my resource group:

"az虚拟机列表-g MyResourceGroup"

" az vm list -g MyResourceGroup "

但是,我希望python脚本执行相同的操作,而我只需要在python程序中合并CLI命令即可.

But, I want the python script to do the same, where I just have to incorporate the CLI command in the python program.

推荐答案

在过去的几天中,我一直在执行此操作. @cbehrenberg提供的方法主要是我使用的方法,但是我发现您可以在不使用临时文件的情况下进行操作.而是直接从azure客户端捕获输出.认为这可能有用.

I have been implementing this over the last couple days. The method that @cbehrenberg provides is mostly what I used, but I found that you can do it without using a temporary file. Instead catch the output directly from the azure client. Thought it might be useful.

from azure.cli.core import get_default_cli

def az_cli (args_str):
    args = args_str.split()
    cli = get_default_cli()
    cli.invoke(args)
    if cli.result.result:
        return cli.result.result
    elif cli.result.error:
        raise cli.result.error
    return True

然后以相同的方式调用:

Then invoked the same way:

from azhelper import az_cli

response = az_cli("vm list")
print("vm's: %s" % (response))

这篇关于如何使用python运行Azure CLI命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆