How can we create windows VM image with RDP disabled for VMs created from that image? I want publish an RDP hardened image.
You can do this with a Custom Script Extension for Windows
Create a PowerShell scripts which disables RDP and reference it:
{
"fileUris": ["https://mystorage.blob.core.windows.net/privatecontainer/script1.ps1"],
"commandToExecute": "powershell.exe script1.ps1",
"managedIdentity" : {}
}
Powershell script to disable RDP in registry:
Invoke-Command –Computername "customname" –ScriptBlock {Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value 1}
Related
How to add the following custom extension to run the powershell script in already existing VM ? How to refer to existing VM ?
{
"condition":"[empty(parameters ('DR User Secret'))]",
"type":"Microsoft.Compute/virtualMachines/extensions",
"name":"[concat(parameters('vmName'),'/', 'customscript')]",
"apiVersion":"2015-06-15",
"location":"[resourceGroup().location]",
"properties":{
"publisher":"Microsoft.Compute",
"type":"CustomScriptExtension",
"typeHandlerVersion":"1.9",
"autoUpgradeMinorVersion":true,
"settings":{
"fileUris":[
]
},
"protectedSettings":{
"commandToExecute":"[concat('powershell -ExecutionPolicy Unrestricted -file ', 'C:\\test.ps1', ' -AdminPass ', parameters('Password'))]"
}
}
}
Here is an alternate way you may also try.
I created a VM using the ARM template.
Reference: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/ps-template
And I use the below following command that uses the Custom Script extension to download a script from a GitHub repository onto the target virtual machine and then run the script.
fileUris: The locations where the script files are stored.
Set-AzVMCustomScriptExtension -ResourceGroupName "v-rash18" -VMName "SampleVM" -Name "myCustomScript"
-FileUri "https://raw.githubusercontent.com/neilpeterson/nepeters-azure-templates/master/windows-custom-script-simple/support-scripts/Create-File.ps1"
`
-Run "Create-File.ps1" -Location "Central US".
Reference: https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/features-windows#run-vm-extensions
To check the extension is set on the existing VM is Get-AzVMExtension
I have a windows Azure VM and need to execute “%windir%\system32\sysprep” and then execute “sysprep /generalize” both from admin mode from my local machine through Powershell. How can I do that ?
For your requirements, as I know you can use a PowerShell script to achieve it. First, you can take a look at the Sysprep, it can be run in a PowerShell command C:\WINDOWS\system32\sysprep\sysprep.exe /generalize /shutdown /oobe. Put this command inside a script, then you can use two ways to run this script in the VM from your local machine. One is that use the Invoke command.
In Azure CLI:
az vm run-command invoke --command-id RunPowerShellScript -g group_name -n vm_name --scripts #script.ps1
In PowerShell:
Invoke-AzVMRunCommand -ResourceGroupName 'rgname' -VMName 'vmname' -CommandId 'RunPowerShellScript' -ScriptPath 'sample.ps1'
Another is that use the VM extension. It's a little complex. You can take a look at the Azure PowerShell command Set-AzVMCustomScriptExtension.
Output after running:-
Value[0] :
Code : ComponentStatus/StdOut/succeeded
Level : Info
DisplayStatus : Provisioning succeeded
Message :
Value[1] :
Code : ComponentStatus/StdErr/succeeded
Level : Info
DisplayStatus : Provisioning succeeded
Message :
Status : Succeeded
Capacity : 0
Count : 0
I could't make sysprep work with Invoke-AzVMRunCommand, It run with succeeded status, but the VM was not shutdown.
Finally found https://developercommunity.visualstudio.com/t/devops-sysprep-public-agents/1375989 and it make sense.
So just use Invoke-AzVMRunCommand to run sysprep won't work, I am thinking to reset a local admin user password and run the process as local admin might be a workaround.
My (dotNET) application is built (using a Windows Hosted agent), from a build pipeline, and in the subsequent Release pipeline, I provision a 16GB-Win2016 VM (enabling RDP, HTTP, HTTPS, WinRM and SSH), into which I RDP manually (there is a Manual Intervention task here), and configure WinRM (following this article: https://learn.microsoft.com/en-us/azure/marketplace/cloud-partner-portal/virtual-machine/cpp-configure-winrm-after-vm-creation#configure-vm-to-enable-winrm). Everything is fine until here. The next task is a Azure File Copy task, which essentially copies the Build artifacts (from $(System.DefaultWorkingDirectory)) and pastes into a directory I specify. Works like a charm. The next task I have is to create a VHD of this whole VM (essentially after the copying is done).
I know I can manually RDP into the VM (again) and sysprep (with oobe/generalize/shutdown), then maybe go back to the Azure Portal and Disk Export the OS Disk (specifying the SAS URL expiration time at whatever (36000 per the article)) BUT can this all be automated?
So, long story short - I'd like to know if sysprep oobe/generalize/shutdown can be performed remotely preferably over a PS task. I understand the other part of it (exporting the disk and all) can be, but if sysprep can be done remotely nothing like it.
I tried this and got what I wanted:
$sysprep= 'C:\Windows\System32\Sysprep\Sysprep.exe'
$arg1 = '/generalize'
$arg2 = '/oobe'
$arg3 = '/shutdown'
$arg4 = '/quiet'
& $sysprep $arg1 $arg2 $arg3 $arg4 -Wait
Make sure you do NOT use Azure custom script extension to run sysprep.
Azure scripts run under the LocalSystem user context: source
Custom Script Extension will run under the LocalSystem Account
This is problematic because sysprep does NOT support running under a system user context: source
Sysprep cannot be run under the context of a System account. Running Sysprep under the context of System account by using Task Scheduler or PSExec, for example, is not supported.
Providing this so that people avoid my mistake :)
So, you dont have to configure winrm manually, you can script it\configure it while provisioning the vm. and if\when winrm is working you can just use powershell remoting to issue a command against the vm with:
Invoke-Command -ComputerName dnsname\ipaddress_goes_hehe
-ScriptBlock { sysprep /shutdown /generalise}
https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-winrm-windows
You can implement this using an Azure custom script extension. There is a github project:
https://github.com/jlongo62/AzureVMToImage containing powershell scripts to image a VM. These scripts were built to preserve VM when creating an image, instead of destroying the original VM. The scripts can be called from Azure Devops. There is no need to authenticate against the VM.
The meat of what you need is:
1- create a storageaccount blob containing the following script (the -Wait is very important):
Start-Process -FilePath C:\Windows\System32\Sysprep\Sysprep.exe -ArgumentList '/generalize /oobe /quiet /quit' -Wait
2 - invoke it on the VM:
$response = Set-AzureRmVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Location $vm.Location `
-Name $ExtensionName `
-FileUri $blobUri `
-Run $FileName
I have a simple configuration that I am trying to apply to an Azure VM using PowerShell DSC extension
Configuration DSCTest
{
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Import-DscResource -ModuleName xPSDesiredStateConfiguration
Node "localhost"
{
File ESETInstaller
{
Type = 'Directory'
DestinationPath = 'C:\ESETInstaller'
Ensure = "Present"
}
}
}
DSCTest
I've published this using
Publish-AzVMDscConfiguration "D:\Test\DSCTest.ps1" -OutputArchivePath "D:\Test\DSCTest.ps1.zip"
and then I uploaded this zip file in Azure BLOB storage.
After that, I tried to apply this configuration to a VM using the following command:
Set-AzVMDscExtension -ResourceGroupName 'TestDSC' -VMName 'TestDSCVM' -ArchiveStorageAccountName 'test***********' -ArchiveResourceGroupName '******' -ConfigurationName $configurationName -ArchiveBlobName "DSCTest.ps1.zip" -ArchiveContainerName 'dsc' -Name "DSCTest" -Version 2.76
In the target machine, I can see that the DSC folder appears
But on the console I get the error:
Although, I am able to successfully apply the configuration in the target machine by manually executing the command from inside that VM.
Please let me know if anyone has ever faced this issue before. Thanks.
The logs inside the target machine showed that the issue is with the execution policy.
In my script I changed "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned" to "Set-ExecutionPolicy -ExecutionPolicy ByPass -Scope CurrentUser -Force" and it worked fine.
I am trying to install the Microsoft Antimalware extension to an existing virtual machine.
Steps to reproduce the problem:
Using Visual Studio
1) Connect to Azure from VS
2) Select Server from Virtual Machines
3) Open Configuration properties.
4) Select Microsoft Antimalware from extensions and click Add.
5) Click Update. Outputs...
Updating virtual machine myVM...
Failed to update virtual machine. The probe setting for the endpoint group HTTP-80 is null. An external endpoint HTTP cannot specify a probe setting.
Using PowerShell
When following these MS instructions to install Antimalware using the Powershell , I get the error:
PS C:\> Update-AzureVM -Name $service -ServiceName $name -VM $vm.VM
Update-AzureVM : Could not find a deployment for 'myVM' in 'Production' slot.
At line:1 char:1
+ Update-AzureVM -Name $service -ServiceName $name -VM $vm.VM
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Update-AzureVM], ApplicationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.UpdateAzureVMCommand
To install antimalware via the powershell:
Make sure you are using the latest Azure Powershell version (version 0.8.12)
Get-Module
Now create a configuration file on disk in json format:
$JsonString="{ 'AntimalwareEnabled': true }"
$JsonString |Out-File $home\downloads\AzureAntimalware.json
Then select and update your VM:
Get-AzureVM -Servicename "myService" -Name "myVM" | Set-AzureVMMicrosoftAntimalwareExtension -AntimalwareConfigFile $home\downloads\AzureAntimalware.json | Update-AzureVM
This will install System Center Endpoint Protection onto the virtual machine.
When you try and launch System Center Endpoint Protection from the start menu you may be presented with the following error message:
Your system administrator has restricted access to this app.
To fix this issue, open a command prompt on the VM and enter:
cd "c:/program files/microsoft security client"
configsecuritypolicy cleanuppolicy.xml
This will create the necessary config files and fix the problem.
You will now be able to launch System Center Endpoint Protection from the start menu and configure the program in the usual way.
I'm a little late replying so you've probably solved the issue.
This is how I resolved it using Powershell:
http://go.microsoft.com/fwlink/?LinkID=394789&clcid=0x409 – Download the VM agent and install on the virtual machine
Activate the VM agent with the following:
$vm = Get-AzureVM –serviceName $svc –Name $name
$vm.VM.ProvisionGuestAgent = $TRUE
Update-AzureVM –Name $name –VM $vm.VM –ServiceName $svc
You can check if it’s running by opening task manager and clicking the details tab – Look for WaAppAgent.exe, WindowsAzureGuestAgent.exe, WindowsAzureTelemetryService.exe
Once running you can install AntiMalware with the following:
$servicename = "<SERVICE NAME HERE>"
$name = "<NAME HERE>"
# Get the VM
$vm = Get-AzureVM –ServiceName $servicename –Name $name
# Add Microsoft Antimalware Agent to the Virtual Machine
Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM
# Update the VM which will install the Antimalware Agent
Update-AzureVM -Name $servicename -ServiceName $name -VM $vm.VM
You can check it works by looking in services.msc for Microsoft Antimalware service