Skip to content

Instantly share code, notes, and snippets.

@jasondgreene
Created August 26, 2019 16:59
Show Gist options
  • Save jasondgreene/872fe9592ae254e819de0301b057b76f to your computer and use it in GitHub Desktop.
Save jasondgreene/872fe9592ae254e819de0301b057b76f to your computer and use it in GitHub Desktop.
Change Linux VM passwords via PowerCLI
# PowerCLI password script
# By: Jason Greene
# Get vCenter login
$vCenter = Read-Host -Prompt "Enter the vCenter hostname:"
Write-Host "Enter vCenter login credentials"
$cred1 = (Get-Credential)
# Ask for new/old password
$oldpw = Read-Host -Prompt "Enter the OLD root password" -AsSecureString
$newpw = Read-Host -Prompt "Enter the NEW root password" -AsSecureString
# Decrypt for use
$oldpw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServies.Marshal]::SecureStringToBSTR($oldpw))
$newpw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServies.Marshal]::SecureStringToBSTR($newpw))
# Connect to vCenter
Connect-VIServer -Server $vCenter -Credential $cred1 -Force > $null
# Get VMs
$vms = Get-VM -Name <vms here> | where {$_.PowerState -eq "PoweredOn"
# Connect to each and change pw
foreach ($vm in $vms){
Write-Host "Connecting to $vm..."
Write-Host "Changing root password on $vm..."
Invoke-VMScript -VM $vm -ScriptText "cat /etc/shadow |grep root" -ScriptType Bash -GuestUser root -GuestPassword $oldpw | Select-Object ScriptOutput
# Sent to > $null becuase the output is an error but the command works.
Invoke-VMScript -VM $vm -ScriptText "echo -e '$newpw''\n''$newpw' | passwd" -ScriptType Bash -GuestUser root -GuestPassword $oldpw > $null
Invoke-VMScript -VM $vm -ScriptText "cat /etc/shadow |grep root" -ScriptType Bash -GuestUser root -GuestPassword $oldpw | Select-Object ScriptOutput
}
Disconnect-VIServer -confirm:$false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment