如何通过RunCommandResult判断命令执行错误?基于Java代码实现Azure Linux虚拟机远程脚本非0退出码时抛出异常是否可行?
我来帮你解答这两个关于Azure VM远程执行命令的问题:
问题1:如何通过RunCommandResult对象判断远程执行的命令是否出现错误?
要判断远程命令是否执行出错,你可以从RunCommandResult返回的InstanceViewStatus集合里提取关键信息:
- 检查状态码(code):正常执行完成的状态码通常是
ProvisioningState/succeeded,如果是失败会是类似ProvisioningState/failed的格式 - 查看显示状态(displayStatus):失败时会显示
Failed,成功则是Succeeded - 解析消息内容(message):这是最关键的部分,里面会包含脚本的执行日志,包括退出码(比如
exit code: 0表示成功,非0则是错误)。你可以通过匹配消息里的exit code:字段来获取具体的退出值
举个简单的判断逻辑:
for (InstanceViewStatus res : runResult.value()) { // 先检查整体执行状态 if (res.code().contains("failed") || res.displayStatus().equals("Failed")) { System.out.println("命令执行失败"); } // 再提取退出码确认 if (res.message().contains("exit code:")) { String exitCodeStr = res.message().split("exit code:")[1].trim(); int exitCode = Integer.parseInt(exitCodeStr); if (exitCode != 0) { System.out.println("脚本退出码非0,执行错误,退出码:" + exitCode); } } }
问题2:当脚本退出码不为0时,是否可以抛出异常?
当然可以!你只需要在解析出脚本退出码不为0的时候,主动抛出自定义异常或者RuntimeException即可。结合你给出的代码,我修改一下示例:
public static void main(String[] args) { String subscriptionId=""; AppServiceMSICredentials appServiceMsiCredentials = new AppServiceMSICredentials(AzureEnvironment.AZURE); Azure azure = Azure .configure() .withLogLevel(LogLevel.NONE) .authenticate(appServiceMsiCredentials) .withSubscription(subscriptionId); final String rgName1 = "testlinux_group"; final String linuxVMName = "testlinux"; try { VirtualMachine virtualMachine = azure.virtualMachines().getByResourceGroup(rgName1, linuxVMName); System.out.println("Running Command"); List<String> commands = new ArrayList<>(); // 改成一个会返回非0退出码的脚本测试,比如"ls non_existent_file" commands.add("ls non_existent_file"); RunCommandInput runParams = new RunCommandInput() .withCommandId("RunShellScript") .withScript(commands); RunCommandResult runResult = azure.virtualMachines().runCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), runParams); boolean hasError = false; int exitCode = 0; for (InstanceViewStatus res : runResult.value()) { System.out.println("code : " + res.code()); System.out.println("status : " + res.displayStatus()); System.out.println("message : " + res.message()); // 检查执行状态和退出码 if (res.code().contains("failed") || res.displayStatus().equals("Failed")) { hasError = true; } if (res.message().contains("exit code:")) { String exitCodeStr = res.message().split("exit code:")[1].trim(); exitCode = Integer.parseInt(exitCodeStr); if (exitCode != 0) { hasError = true; } } } // 如果标记为错误,抛出异常 if (hasError) { throw new RuntimeException("脚本执行失败,退出码:" + exitCode); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { System.out.println("final"); } }
说明一下:
- 我添加了
hasError标记和exitCode变量来记录执行状态和退出码 - 在遍历
InstanceViewStatus时,同时检查整体执行状态和脚本退出码 - 最后如果检测到错误,就抛出一个RuntimeException(你也可以自定义一个业务异常类)
- 抛出的异常会被下面的catch块捕获,打印错误信息
内容的提问来源于stack exchange,提问作者11ohina017
相关产品推荐
相关产品推荐

