Showing posts with label Azure. Show all posts
Showing posts with label Azure. Show all posts

Tuesday, September 6, 2022

Powershellscript to get details of Azure users who have synced to Azure with diferent upn

 # Connecting to Azure Parameters
$tenantID = "mytenantid"
$ClientId = "myapplicationid"
$ClientSecret = "myclientsecret"



# Create a hashtable for the body, the data needed for the token request
# The variables used are explained above
$Body = @{
    'tenant' = $TenantId
    'client_id' = $ClientId
    'scope' = 'https://graph.microsoft.com/.default'
    'client_secret' = $ClientSecret
    'grant_type' = 'client_credentials'
}

# Assemble a hashtable for splatting parameters, for readability
# The tenant id is used in the uri of the request as well as the body
$Params = @{
    'Uri' = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
    'Method' = 'Post'
    'Body' = $Body
    'ContentType' = 'application/x-www-form-urlencoded'
}

$AuthResponse = Invoke-RestMethod @Params

$Headers = @{
    'Authorization' = "Bearer $($AuthResponse.access_token)"
}

#$url = "https://graph.microsoft.com/v1.0/users/?$select=displayName,givenName,postalCode,UserPrincipalName,onPremisesDistinguishedName,onPremisesUserPrincipalName"

$url = 'https://graph.microsoft.com/v1.0/users/?$select=UserPrincipalName,onPremisesDistinguishedName,onPremisesUserPrincipalName'

$userPurpose = @()

$UserData = Invoke-RestMethod -Method GET -headers $headers -Uri $url


$nexturl = $UserData.'@odata.nextLink'
$userPurpose+= $UserData
$count = 0
while($nexturl -ne "")
{

$nexturl = $UserData.'@odata.nextLink'
Write-host $nexturl -ForegroundColor Yellow
if(!$nexturl) {break;}
$UserData = Invoke-RestMethod -Method GET -headers $headers -Uri $nexturl


$userPurpose+= $UserData
$count++

}

 Write-host "Count of url: $count" -ForegroundColor Yellow

 $userPurpose.count

 $Users = @()
 Foreach($userdata in $userPurpose)
 {
   $Users+=$userdata.value
 }

$users | Export-csv -Path c:\temp\Azureusers1.csv -NoClobber -NoTypeInformation -Append

Wednesday, April 27, 2022

connect using ssh to Azure VM from powershell

If you are on windows 10 you can install the ssh client from Settings-Apps and Features.

During your VM creation in Azure it will ask to save the private key and if you have it saved. It might be with an extension of .pem.

Copy this private key to a directory where no one else has permissions except you. Or remove everyone from the security properties except yourself.

Open powershell and navigate to the directory where ssh is installed. 

Enter the command in the following format

.\ssh.exe -i C:\\ubuntukey.pem username@publicipfothevm

The username must have been created during the VM creation. 

The public ip can be seen in Azure portal.

 

If you dont have the VM username or key. You can reset the username and use your own public key using the following in command prompt.

 ssh-keygen.exe -m PEM -t rsa -b 4096.

This command will create two files in the directory you specify with extensions.  .pub and .pem

These are your pulic and privatekeys. Rename them to yourkey.pem and yourkey.pub.

Copy the contents of the .pub file and put that in the ssh public key section of reset password blade in Azure portal. Give an username you would like to be used as admin on the server.

user ssh.exe in the following format. 

ssh.exe -i c:\youdirectory\yourkey.pem username@publicipofthevm

Friday, February 25, 2022

Cannot open backup device. Operating system error 5(Access is denied.). RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3201)

Came across this error while trying to restore a SQL database backup which was stored in a container to Azure SQL managed instance.

Operating system error 5(Access is denied.).
RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3201)

The blob would connect properly and show the backup file.

Solution:

Deleted the stored credentials in the database and did the process again for restoring backup.





Thursday, December 2, 2021

Resize Azure VMs using Az powershell.

Script to resize Azure VM's from any subscription. If a VM is stopped it will resize it. If it is running it will stop the VM and resize it.


#$NewSize = "Standard_D8s_v3"

$NewSize = "Standard_E4s_v3" 

#$NewSize = "Standard_DS1_v2"

Function Out($message) {
$message = $(Get-Date -Format "MM/dd/yyyyTHH:mm:ss") + ":" + $message
Write-Output $message}

Out "Vm resize script starting...."

function Connect($tenantid)
{
$username = "username@contoso.com"
$password = ConvertTo-SecureString -AsPlainText -Force "password" 
$pscredential = New-Object -TypeName System.Management.Automation.PSCredential($username$password)
Connect-AzAccount -Credential $pscredential -Tenant $tenantId -EnvironmentName AzureUSGovernment
}

Function Resize-VM($VM)
{
 
  Out "Resizing $($vm.name) in $($vm.ResourceGroupName) from $($VM.HardwareProfile.VmSize) to $NewSize"          ## Change here
   $VM.HardwareProfile.VmSize = $NewSize
  Update-AzVM -ResourceGroupName $vm.ResourceGroupName -VM $VM 
}


Function CheckVM($VM)
{            
   if((Get-AzVM -Name $VM.Name -Status).PowerState -eq "VM running")
     {
       Out "$($VM.Name) is resized and Started"
     }
     else {
         Out "$($VM.Name) is resized and not started"
      }
     
}

Connect "put your tenant id here"


$VMList = @("VM1","VM2" ## comma separated list of VM's
)
$Allsubs = Get-AzSubscription 

foreach($sub in $Allsubs)

{
   Select-AzSubscription -SubscriptionId $sub.SubscriptionId | Out-Null
  $VMS = Get-AzVM -Status 
 
foreach($vm in $VMS)
{
 
 foreach($v in $VMList)
   {
     if($v -eq $Vm.name)
      {
        
      if($vm.PowerState -notmatch "VM running"## If the VM is switched off.We resize but dont start it.
        {
          #Resize the vm
          Out "VM $($VM.Name) is already powered off.Resizing...."
          Resize-VM $VM
          
        }

     Else # If the VM is turned on. Turn it off, resize and start it.
        {
          Out "VM is powered on. So Stopping $($VM.Name)"
          Stop-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
          Start-Sleep -Seconds 120
          #Get VM Status
          if((Get-AzVM -Name $VM.Name -Status).PowerState -eq "VM deallocated")
             {
               Out "$($VM.Name) is now off. Resizing...."
               Resize-VM $VM
               Start-AzVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName
               Start-Sleep -Seconds 300
               CheckVM $VM

         }
                 
      }
   }
}

}
}


Tuesday, May 18, 2021

Python script get vm and errors azure.core.exceptions.ServiceRequestError: [SSL: CERTIFICATE_VERIFY_FAILED]

 

 Script is pretty simple:

from azure.identity import ClientSecretCredential
from azure.mgmt.compute import ComputeManagementClient


print("Starting script")
SUBSCRIPTION_ID = "mysubscriptionid"
credential = ClientSecretCredential(
    tenant_id='mytenantid,
    client_id='myapplicationid,
    client_secret='myapplicationsecret'
)

compute_client = ComputeManagementClient(
    credential=credential,
    subscription_id=SUBSCRIPTION_ID,
    
)

print("Getting vms")
# List all Virtual Machines in the specified subscription
def list_virtual_machines():
    for vm in compute_client.virtual_machines.list_all():
        print(vm.name)

list_virtual_machines()
 
Errors encountered and fixes.
 
  •  Packages not found 
   Solution :    
                   Install the packages using 
                   pip install packagename
  • pip error while installing packages.
        pip install azure-storage
        Defaulting to user installation because normal site-packages is not writeable
        WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None,    
        status=None))            after connection broken by 'SSLError(SSLCertVerificationError(1,   
        '[SSL:                                                CERTIFICATE_VERIFY_FAILED] certificate verify   
        failed: self signed certificate in certificate             chain (_ssl.c:1091)'))': /simple/azure-
        storage/
 

    Solution :   

                    Use the following command to install packages

                    pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade pip

                    pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org Django==3.2

 
  • azure.core.exceptions.ServiceRequestError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain
   Solution :    Link to solution is below. Same solution can be used for the above problem

                        https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-                           failed-error.
Credit to user : Bruno Gabuzomeu
 

        On Windows, Python does not look at the system certificate, it uses its own located at                 ?\lib\site-packages\certifi\cacert.pem.

  1. download the certificate chain from portal.azure.com as *.crt or *pem file
  2. open the file in editor and copy it's content to clipboard. contents will be like below. Copy all of it.
      -----BEGIN CERTIFICATE-----
     bunch of gibbereshin between.
      -----END CERTIFICATE-----
  1. Find your cacert.pem location: from requests.utils import DEFAULT_CA_BUNDLE_PATH; print(DEFAULT_CA_BUNDLE_PATH)
  2. edit the cacert.pem file and paste your domain validation certificate at the end of the file.
  3. Save the file.

Wednesday, January 16, 2019

Adding a disk to Azure vm using powershell

Powershell Script to add a disk to Azure RM virtual machine.

$Credentials = Get-Credential
param([string] $VirtualMachineName,$DiskSize)

Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials

$Managed_Prod_Sub = Get-AzureRMSubscription -SubscriptionId "Your subscription id"
Select-AzureRMSubscription -SubscriptionId $Managed_Prod_Sub.SubscriptionId ##
$Managed_ProdVMS = Get-AzureRMVM


if($VM.name -eq $VirtualMachineName)
  {
  Write-host "Working on $($VM.name)" -ForegroundColor Yellow
     $rgName = $VM.ResourceGroupName
    $vmName = $VM.Name
    $location = $VM.location
    $storageType = 'Premium_LRS'
    $dataDiskName = $vmName + '_datadisk1'

   
    $diskConfig = New-AzureRmDiskConfig -AccountType PremiumLRS -Location $location -CreateOption Empty -DiskSizeGB $DiskSize -OsType Windows

    $dataDisk1 = New-AzureRmDisk -DiskName $dataDiskName -Disk $diskConfig -ResourceGroupName $rgName
   
    $vm = Get-AzureRmVM -Name $vmName -ResourceGroupName $rgName
    $vm = Add-AzureRmVMDataDisk -VM $vm -Name $dataDiskName -CreateOption Attach -ManagedDiskId $dataDisk1.Id -Lun 1

    Update-AzureRmVM -VM $vm -ResourceGroupName $rgName


   }

Tuesday, December 11, 2018

Get Azure VM status and ip address

Powershell script to get the list of virtual machines in Azure Gov with ip address.

$username = "parag.waghmare@contoso.com"
$Password = "Password"
$Credentials = New-Object System.Management.Automation.PSCredential ($username, $password)
Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials 
$subs = Get-AzureRmSubscription 
foreach ($Sub in $Subs) { 
   
    $SelectSub = Select-AzureRmSubscription -SubscriptionName $Sub.Name 

    $nics = get-azurermnetworkinterface | where VirtualMachine -NE $null #skip Nics with no VM


    $VMs = Get-AzureRMVM -Status

    foreach($nic in $nics)
{
    $vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
    $prv =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
    $alloc =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
    $data = $Sub.Name + "`t "+ $vm.Name + "`t "+ $prv + "`t "+ $alloc  + "`t " + $Vm.powerstate 
    Write-Host $data 
}

Monday, March 5, 2018

Operations management suite workspaces for Azure gov do not show up in SCOM

The default workspaces that you can connect to in SCOM are tied to Azure commercial.





After logging to the Azure account you will not see the workspaces you have created in the Azure government cloud. 

If you want to connect to an Azure Gov workspace download the respective mp's.
 


These are sealed management packs so you will have to delete the existing  ones before importing these.

 
Once done though,you shall see the dropdown for Azure Gov. After which you can login and the workspaces should show up.