Automate with ssh

Scenario

I have a bunch of Linux hosts to perform actions on. Updates, certificates, cleanup, you name it. I do all my work over “ssh” but for that to work the hosts must be trusted. Of course I can use “ssh-keyscan” to get the keys but my own “known_hosts” file gets pretty messed up when I add all the keys there. I would like to use a temporary solution. The best would be a parallel temporary solution so that I can handle a lot of hosts at once. Fortunately PowerShell allows such a thing. In this example the host has the name “4ab586fc-9a23-49eb-8d81-f2ca021203aa” (I really love GUIDs) and the full domain name would be “4ab586fc-9a23-49eb-8d81-f2ca021203aa.example.com”. Keeping this in mind the script that gets the key, performs the action (a simple “ls”) and deletes the key would look like this:

Start-Job -ScriptBlock {
	$Uuid = "4ab586fc-9a23-49eb-8d81-f2ca021203aa"
	$Domain = "$Uuid.example.com"
	ssh-keyscan "$Domain" >> "$Uuid.known_host"
	ssh -o UserKnownHostsFile="$Uuid.known_host" root@"$Domain" "ls" >> "$Uuid.output"
	Remove-Item -Path "$Uuid.known_host"
}

The catch here is, that the servers public key is temporary stored in a local file instead of the users “known_hosts” file and then referenced with the parameter “-o UserKnownHostsFile=$Uuid.known_host” in the ssh command. After completion the file is then removed and the access to the server was a success. Running this in a loop allows the execution of tasks on multiple servers at the same time.