Azure SDK: VM creation with custom command execution.

Prem Jha 140 Reputation points
2025-12-11T08:09:08.24+00:00

I am creating a windows VM using Azure python library but when I tried the below method few options gets stuck and when at the later stage when I try the RunOnce command it gets errored out due to incompletion of the older commands exectution.

Please help me comeup with a better approach to execute the commands so that none of the commands stuck in pending state.

Existing code approach:

            "windowsConfiguration": {

                  "provisionVMAgent": "false",

                  "winRM": {

                          "listeners": [

                                  {

                                          "protocol": "http"

                                  }

                          ]

                  },

                  "additionalUnattendContent": [

                          {

                                  "passName": "oobesystem",

                                  "componentName": "Microsoft-Windows-Shell-Setup",

                                  "settingName": "FirstLogonCommands",

                                  "content": '<FirstLogonCommands><SynchronousCommand><CommandLine>CMD /c netsh advfirewall firewall add rule name="RWPort445In" dir=in localport=445 action=allow protocol=TCP</CommandLine><Description>Open Port 445 In</Description><Order>2</Order></SynchronousCommand><SynchronousCommand><CommandLine>CMD /c netsh advfirewall firewall add rule name="RWPort445Out" dir=out remoteport=445 action=allow protocol=TCP</CommandLine><Description>Open Port 445 Out</Description><Order>3</Order></SynchronousCommand><SynchronousCommand>  
```</SynchronousCommand></FirstLogonCommands>'  
                              },

```go
                          {

                                  "passName": "oobesystem",

                                  "componentName": "Microsoft-windows-Shell-Setup",

                                  "settingName": "AutoLogon",

                                  "content": "<AutoLogon><Password><Value>{paswd}</Value><PlainText>true</PlainText></Password><Enabled>true</Enabled><LogonCount>2</LogonCount><Username>{user}</Username></AutoLogon>".format(paswd=password, user=username)

                          }

                  ]

            }

        },
```VM creates successfully but at the later stage when below code run it gets errored out due to incompletion of the above FirstLogonCommands.  
  
def check_first_logon_command_status(ipAddress, username, password):

```python
if username == "" or password =="" or ipAddress is None:

    logger.debug("Username,Password or ipAdress not found")

    return 2

cmd = "winexe -U '" + username + "%" + password + "' //" + ipAddress + " \"cmd /c REG QUERY HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce /f Unattend*\""

(code, out, err) = local_execute(shlex.split(cmd.encode('ascii')))

logger.info("Checking FirstLogonCommands: exitcode: %s, Output: %s, Error: %s" % (code, out, err))

return code
Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
{count} votes

1 answer

Sort by: Most helpful
  1. Himanshu Shekhar 1,860 Reputation points Microsoft External Staff Moderator
    2025-12-11T10:17:53.3533333+00:00

    Hello @Prem Jha - Thanks for reaching Microsoft QnA platform

    Instead of relying completely on FirstLogonCommands, please consider using run command, which supports asynchronous execution, and this allows you to run commands after the VM is deployed, independent of the boot process.

    Steps for Implementation:

    1. Enable the VM Agent
    2. Make sure the Azure VM Agent is enabled. It’s required for the Run Command feature to function properly.
    3. Use Run Command After VM Creation - Once the VM is up, use the Run Command API to execute your commands asynchronously:

    from azure.mgmt.compute import ComputeManagementClient

    # Assuming authentication and client setup are complete

    compute_client = ComputeManagementClient(credentials, subscription_id)

    # Run command example to open port 445

    run_command_parameters = {

    'script': [

    "CMD /c netsh advfirewall firewall add rule name='RWPort445In' dir=in localport=445 action=allow protocol=TCP",

    "CMD /c netsh advfirewall firewall add rule name='RWPort445Out' dir=out remoteport=445 action=allow protocol=TCP"

    ],

    'parameters': [],

    'run_as_user': '<your_username>', # Optional

    'run_as_password': '<your_password>' # Optional

    }

    response = compute_client.virtual_machines.run_command(

    resource_group_name='your_resource_group',

    vm_name='your_vm_name',

    parameters=run_command_parameters

    )

    please monitor Command Execution - You can check the execution results through the Run Command instance view to confirm success or investigate failures.

    Best Practices :

    1. Ensure scripts are idempotent to support retries without breaking functionality.
    2. Avoid commands that require user interaction.
    3. Keep commands short and simple to prevent syntax errors.
    4. Redirect outputs and errors to logs for better troubleshooting.

    Advantages of Using Run Command :

    1. Reduces dependency on FirstLogonCommands, minimizing risks of commands hanging.
    2. Enables modular command execution that’s easier to monitor and manage.
    3. Simplifies troubleshooting by decoupling your boot-time operations from post-deployment configuration.

    Useful References :

    1. Run scripts in your Windows VM using managed Run Commands
    2. Run Command Overview
    3. VM Assist for faster diagnostics
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.