【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例

简介: 【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例

当需要通过代码的方式执行PowerShell脚本时,可以参考以下的示例。

 

 

 

Azure SDK中提供了两个方法来执行PowerShell脚本 (SDK Source Code: https://github.com/Azure/azure-libraries-for-java/blob/master/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImpl.java#L400)

  • public RunCommandResult runPowerShellScript(String groupName, String name, List<String> scriptLines, List<RunCommandInputParameter> scriptParameters)
  • public Observable<RunCommandResult> runPowerShellScriptAsync(List<String> scriptLines, List<RunCommandInputParameter> scriptParameters)

在使用的时候,需要注意的是参数scriptLines 和 scriptParameters。 下面部分为关键代码,以Java SDK的同步方法runPowerShellScript为例

Azure azure = null;
        azure = Azure.authenticate(credentials).withSubscription("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
        
        // 获取虚拟机对象
        VirtualMachine testvm = azure.virtualMachines().getById(
                "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vm resource group /providers/Microsoft.Compute/virtualMachines/vm name");
        //testvm.start();
        
        // 准备PowerShell脚本
        List<String> scriptLines = new ArrayList<String>();
        scriptLines.add(" param([string]$arg1, [string]$arg2 )");
        scriptLines.add(" Write-Host This is a sample script with parameters $arg1 and $arg2");
        scriptLines.add(" Get-Host | Select-Object Version");
        //设置参数arg1 和 arg2
        List<RunCommandInputParameter> scriptParameters = new ArrayList<RunCommandInputParameter>();
        RunCommandInputParameter arg1 = new RunCommandInputParameter(){};
        arg1.withName("arg1");
        arg1.withValue("test1");
        RunCommandInputParameter arg2 = new RunCommandInputParameter(){};
        arg2.withName("arg2");
        arg2.withValue("test2");
        scriptParameters.add(arg1);
        scriptParameters.add(arg2);
        //执行 PowerShell
        RunCommandResult rcresult = testvm.runPowerShellScript("vm-rg", "lbpstest01", scriptLines, scriptParameters);
        System.out.println(rcresult.value().get(0).message());
        System.out.println(rcresult.value().get(1).message());

注意:

  1. 在获取 azure对象时,需要通过AAD认证。并且当前使用的认证有权限操作所选择的虚拟机(VM)。获取认证信息部分参考博文 “使用Java代码启动Azure VM(虚拟机)
  2. 如PowerShell脚本中需要传入参数,则必须在脚本中进行声明,如:param([string]���1,[������]arg2 ),然后通过scriptParameters对象传入。
  3. PowerShell执行成功的结果包含在RunCommandResult对象的Value 1中,如果所输入的PowerShell脚本有语法等操作,则在Value 2中输出详细的异常消息.

在执行PowerShell脚本时,如发现脚本有错误。在RunCommandResult中会返回PowerShell提示的错误信息:

错误的PowerShell脚本
RunCommandResult中的提示消息

示例完整代码:

package org.example;
import java.util.ArrayList;
import java.util.List;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.credentials.ApplicationTokenCredentials;
import com.microsoft.azure.credentials.AzureTokenCredentials;
import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.compute.*;
/**
 * s Hello world!
 *
*/
public class App {
    public static void main(String[] args)
    {
        //使用AAD Application 方式获取 认证
        AzureTokenCredentials credentials = new ApplicationTokenCredentials("application id",
                "tenant id "securt key",
                AzureEnvironment.AZURE_CHINA);
        Azure azure = null;
        azure = Azure.authenticate(credentials).withSubscription("subscription id");
        
        // 获取虚拟机对象
        VirtualMachine testvm = azure.virtualMachines().getById("resource id");
        //testvm.start();
        
        // 准备PowerShell脚本
        List<String> scriptLines = new ArrayList<String>();
        scriptLines.add(" param([string]$arg1, [string]$arg2)");
        scriptLines.add(" Write-Host This is a sample script with parameters $arg1 and $arg2");
        scriptLines.add(" Get-Host | Select-Object Version");
        //设置参数arg1 和 arg2
        List<RunCommandInputParameter> scriptParameters = new ArrayList<RunCommandInputParameter>();
        RunCommandInputParameter arg1 = new RunCommandInputParameter(){};
        arg1.withName("arg1");
        arg1.withValue("test1");
        RunCommandInputParameter arg2 = new RunCommandInputParameter(){};
        arg2.withName("arg2");
        arg2.withValue("test2");
        scriptParameters.add(arg1);
        scriptParameters.add(arg2);
        //执行 PowerShell
        RunCommandResult rcresult = testvm.runPowerShellScript("vm-rg", "lbpstest01", scriptLines, scriptParameters);
        System.out.println(rcresult.value().get(0).message());
        System.out.println(rcresult.value().get(1).message());
        System.out.println("Hello World!");
    }
}

 

在POM.XML中引用的SDK Version:

   <dependency>

     <groupId>com.microsoft.azure</groupId>

     <artifactId>azure</artifactId>

     <version>1.37.1</version>

   </dependency>

执行结果的正确输出:

 

 

参考资料

使用Java代码启动Azure VM(虚拟机): https://www.cnblogs.com/lulight/p/14295089.html

Run PowerShell scripts in your Windows VM by using Run Command: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/run-command#azure-cli

azure-libraries-for-java VirtualMachineImpl.java : https://github.com/Azure/azure-libraries-for-java/blob/master/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImpl.java#L400

相关文章
|
JavaScript 前端开发 API
【Azure Developer】use @azure/arm-monitor sdk 遇见 ManagedIdentityCredential authentication failed.(status code 500)
【Azure Developer】use @azure/arm-monitor sdk 遇见 ManagedIdentityCredential authentication failed.(status code 500)
217 1
|
存储 Java API
【Azure 存储服务】Java Storage SDK 调用 uploadWithResponse 代码示例(询问ChatGTP得代码原型后人力验证)
【Azure 存储服务】Java Storage SDK 调用 uploadWithResponse 代码示例(询问ChatGTP得代码原型后人力验证)
280 0
|
API 开发工具 Python
【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
本文介绍如何使用Python SDK为中国区微软云(China Azure)中的虚拟机磁盘创建快照。通过Azure Python SDK的Snapshot Class,指定`location`和`creation_data`参数,使用`Copy`选项从现有磁盘创建快照。代码示例展示了如何配置Default Azure Credential,并设置特定于中国区Azure的`base_url`和`credential_scopes`。参考资料包括官方文档和相关API说明。
304 1
|
Kubernetes API 开发工具
【Azure Developer】通过SDK(for python)获取Azure服务生命周期信息
需要通过Python SDK获取Azure服务的一些通知信息,如:K8S版本需要更新到指定的版本,Azure服务的维护通知,服务处于不健康状态时的通知,及相关的操作建议等内容。
354 18
|
JavaScript 前端开发 开发工具
【Azure Developer】使用JavaScript通过SDK进行monitor-query的client认证报错问题
AADSTS90002: Tenant 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.
226 1
|
Java 开发工具
【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID
【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID
285 1
|
网络安全 开发工具 Python
【Azure事件中心】使用Python SDK(Confluent)相关方法获取offset或lag时提示SSL相关错误
【Azure事件中心】使用Python SDK(Confluent)相关方法获取offset或lag时提示SSL相关错误
189 1
|
API 开发工具 网络架构
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
207 0
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
|
Shell Go 开发工具
【Azure Developer】Go语言调用Azure SDK如何登录到中国区Azure环境
【Azure Developer】Go语言调用Azure SDK如何登录到中国区Azure环境
305 0
|
JSON Java API
【Azure API 管理】通过Java APIM SDK创建一个新的API,如何为Reqeust的Representation设置一个内容示例(Sample)?
【Azure API 管理】通过Java APIM SDK创建一个新的API,如何为Reqeust的Representation设置一个内容示例(Sample)?
225 0