Выполните команду на виртуальной машине.
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommand?api-version=2024-03-01
Параметры URI
Имя |
В |
Обязательно |
Тип |
Описание |
resourceGroupName
|
path |
True
|
string
|
Имя группы ресурсов.
|
subscriptionId
|
path |
True
|
string
|
Учетные данные подписки, которые однозначно идентифицируют подписку Microsoft Azure. Идентификатор подписки формирует часть URI для каждого вызова службы.
|
vmName
|
path |
True
|
string
|
Имя виртуальной машины.
|
api-version
|
query |
True
|
string
|
Версия API клиента.
|
Текст запроса
Media Types: "application/json", "text/json"
Имя |
Обязательно |
Тип |
Описание |
commandId
|
True
|
string
|
Идентификатор команды запуска.
|
parameters
|
|
RunCommandInputParameter[]
|
Параметры команды запуска.
|
script
|
|
string[]
|
Необязательный элемент. Выполняемый скрипт. Если это значение задано, заданный скрипт переопределит скрипт по умолчанию для команды .
|
Ответы
Имя |
Тип |
Описание |
200 OK
|
RunCommandResult
|
ОК
Media Types: "application/json", "text/json"
|
202 Accepted
|
|
Принято
Media Types: "application/json", "text/json"
|
Безопасность
azure_auth
Поток OAuth2 в Azure Active Directory
Type:
oauth2
Flow:
implicit
Authorization URL:
https://login.microsoftonline.com/common/oauth2/authorize
Scopes
Имя |
Описание |
user_impersonation
|
олицетворения учетной записи пользователя
|
Примеры
VirtualMachineRunCommand
Sample Request
POST https://management.azure.com/subscriptions/24fb23e3-6ba3-41f0-9b6e-e41131d5d61e/resourceGroups/crptestar98131/providers/Microsoft.Compute/virtualMachines/vm3036/runCommand?api-version=2024-03-01
{
"commandId": "RunPowerShellScript"
}
import com.azure.resourcemanager.compute.models.RunCommandInput;
/**
* Samples for VirtualMachines RunCommand.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-01/examples/runCommandExamples/
* VirtualMachineRunCommand.json
*/
/**
* Sample code: VirtualMachineRunCommand.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void virtualMachineRunCommand(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().runCommand("crptestar98131", "vm3036",
new RunCommandInput().withCommandId("RunPowerShellScript"), com.azure.core.util.Context.NONE);
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_run_command.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="24fb23e3-6ba3-41f0-9b6e-e41131d5d61e",
)
response = client.virtual_machines.begin_run_command(
resource_group_name="crptestar98131",
vm_name="vm3036",
parameters={"commandId": "RunPowerShellScript"},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-01/examples/runCommandExamples/VirtualMachineRunCommand.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-01/examples/runCommandExamples/VirtualMachineRunCommand.json
func ExampleVirtualMachinesClient_BeginRunCommand() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginRunCommand(ctx, "crptestar98131", "vm3036", armcompute.RunCommandInput{
CommandID: to.Ptr("RunPowerShellScript"),
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.RunCommandResult = armcompute.RunCommandResult{
// Value: []*armcompute.InstanceViewStatus{
// {
// Code: to.Ptr("ComponentStatus/StdOut/succeeded"),
// DisplayStatus: to.Ptr("Provisioning succeeded"),
// Level: to.Ptr(armcompute.StatusLevelTypesInfo),
// Message: to.Ptr("This is a sample script with parameters value1 value2"),
// },
// {
// Code: to.Ptr("ComponentStatus/StdErr/succeeded"),
// DisplayStatus: to.Ptr("Provisioning succeeded"),
// Level: to.Ptr(armcompute.StatusLevelTypesInfo),
// Message: to.Ptr(""),
// }},
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Run command on the VM.
*
* @summary Run command on the VM.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-01/examples/runCommandExamples/VirtualMachineRunCommand.json
*/
async function virtualMachineRunCommand() {
const subscriptionId =
process.env["COMPUTE_SUBSCRIPTION_ID"] || "24fb23e3-6ba3-41f0-9b6e-e41131d5d61e";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "crptestar98131";
const vmName = "vm3036";
const parameters = { commandId: "RunPowerShellScript" };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginRunCommandAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample Response
{
"value": [
{
"code": "ComponentStatus/StdOut/succeeded",
"level": "Info",
"displayStatus": "Provisioning succeeded",
"message": "This is a sample script with parameters value1 value2"
},
{
"code": "ComponentStatus/StdErr/succeeded",
"level": "Info",
"displayStatus": "Provisioning succeeded",
"message": ""
}
]
}
Location: https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/westus/operations/{operationId}&monitor=true&api-version=2024-03-01
Определения
InstanceViewStatus
Состояние представления экземпляра.
Имя |
Тип |
Описание |
code
|
string
|
Код состояния.
|
displayStatus
|
string
|
Короткая локализуемая метка состояния.
|
level
|
StatusLevelTypes
|
Код уровня.
|
message
|
string
|
Подробное сообщение о состоянии, в том числе для оповещений и сообщений об ошибках.
|
time
|
string
|
Время состояния.
|
Запись параметров виртуальной машины.
Имя |
Тип |
Описание |
commandId
|
string
|
Идентификатор команды запуска.
|
parameters
|
RunCommandInputParameter[]
|
Параметры команды запуска.
|
script
|
string[]
|
Необязательный элемент. Выполняемый скрипт. Если это значение задано, заданный скрипт переопределит скрипт по умолчанию для команды .
|
Описывает свойства параметра команды выполнения.
Имя |
Тип |
Описание |
name
|
string
|
Имя параметра команды запуска.
|
value
|
string
|
Значение параметра команды выполнения.
|
RunCommandResult
StatusLevelTypes
Код уровня.
Имя |
Тип |
Описание |
Error
|
string
|
|
Info
|
string
|
|
Warning
|
string
|
|