Enable SSH on All ESXi Servers

Earlier, I published a quick note about basically using SSH from one ESXi host to manipulate settings across all ESXi hosts in the environment.  I've realized that it might be helpful if I include this note, around how I easily turn SSH on or off across an arbitrary number of ESXi hosts in the environment.

This script is super basic - run it after connecting your powerCLI session to whatever vCenter servers you're interested in.  Then, pass it the "-h" option and a regular expression that matches the hosts that you want it to manipulate (such as *esx1* or a specific hostname or even just *).  That's it; it'll turn on the SSH service on all of those hosts, which should open the required firewall ports automatically and everything will just work.

Turning SSH off again when you're done is just as simple.  Use the command the same way, but with the "-o" switch... and now the script will sweep through, turning SSH off for all hosts that match the string.  So: "set-ssh.ps1 -h *" turns SSH on for all hosts and "set-ssh -h * -o" turns SSH off for all hosts.  Easy, peasy, pudding and gherkins.


#Script to enable or disable SSH across a wide set of ESXi Hosts.  By default, the script enables SSH on the Hosts.  Use the -off switch to disable SSH.
#Author: Jason Coleman
#Syntax: set-SSH -h <hostname pattern match> [-off]

param
(
[alias("h")]
[string]$HostIn = $(read-host -Prompt "Enter the target Host"),
[alias("o")]
[switch] $off
)

$AllHosts = Get-VMHost -name $HostIn
foreach ($ThisHost in $AllHosts)
{
if (!$off)
{
Get-VMHostService -VMHost $ThisHost | ?{$_.Label -eq "SSH"} | Start-VMHostService
}
else
{
Get-VMHostService -VMHost $ThisHost | ?{$_.Label -eq "SSH"} | Stop-VMHostService -Confirm:$false
}
}

P.S. if you're just pulling this apart for how to start/stop the service and want to change it to start automatically, use this command:

get-vmhost | get-vmhostservice | ? {$_.key -like "*SSH"} | set-vmhostservice -policy on

Comments

Popular posts from this blog

PowerShell Sorting by Multiple Columns

Clone a Standard vSwitch from one ESXi Host to Another

Deleting Orphaned (AKA Zombie) VMDK Files