创建客户端

  1. from azure.common.client_factory import get_client_from_cli_profile
  2. from azure.mgmt.compute import ComputeManagementClient
  3. subscription_id = "14a12b4a-xxxx-xxxx-xxxx-5436954d3e1b"
  4. client = get_client_from_cli_profile(ComputeManagementClient, subscription_id=subscription_id)

创建 poller

  1. resource_group_name = "UM-TEST"
  2. vm_name = "UMLinuxtest"
  3. command_id = "RunShellScript"
  4. run_command_line = ["hostname"]
  5. run_command_parameters = {
  6. 'command_id': command_id,
  7. 'script': run_command_line,
  8. 'parameters': [
  9. {'name': 'customer_name', 'value': "customer_name"},
  10. {'name': 'vm_region', 'value': "vm_region"},
  11. {'name': 'vm_id', 'value': "vm_id"},
  12. {'name': 'vm_name', 'value': "vm_name"}
  13. ]
  14. }
  15. poller = client.virtual_machines.run_command(resource_group_name=resource_group_name, vm_name=vm_name, parameters=run_command_parameters)

执行并取得结果

  1. result = poller.result(timeout=60)
  2. if os_platform == 'Windows':
  3. print(result.value[0].message)
  4. print(result.value[1].message)
  5. elif os_platform == 'Linux':
  6. print(result.value[0].message) # 'Enable succeeded: \n[stdout]\nUMLinuxtest\n\n[stderr]\n'

目标VM上的脚本位置

每台 VM 上的 agent 会在如下路径临时存储:

  • 脚本: /var/lib/waagent/run-command/download/<number>/script.sh
  • 标准输出:/var/lib/waagent/run-command/download/<number>/stdout
  • 错误输出:/var/lib/waagent/run-command/download/<number>/stderr