I wanted to do this for months now. This afternoon, to procrastinate a slightly more complex task on my vacation bucket list, I finally took the time and created this PowerShell module.
It is quite simple but caters my need to manage clean configuration files.
!!!DISCLAIMER!!! no warranty - please test the behavior of this script for thoroughly your environment and make regular backups
How to use the module
Once the module is imported
Import-Module .\ManageSshConfig.psm1
it allows
a - to read the list of configured hosts into a HashTable
$hostList = Get-ConfigHostList
b - to add a new entry to this list of hosts
$hostList = Add-ConfigHostInList -HostList $hostList -HostName "dummy" -HostValues @{
identityfile = "~/.ssh/myprivatekey"
hostname = "dummy.somecloud.com"
user = "johndoe"
}
c - to update an existing entry in this list of hosts
$hostList = Update-ConfigHostInList -HostList $hostList -HostName "dummy" -HostValues @{
identityfile = "~/.ssh/myprivatekey"
hostname = "dummy.somecloud.com"
user = "johndoe"
}
d - to remove an existing entry from this list of hosts
$hostList = Remove-ConfigHostFromList -HostList $hostList -HostName "dummy"
e - and then write this list back to disk
Set-ConfigHostList $hostList
Features
Line breaks
The script should be able to identify the line breaks used in the config
file. This could be CR/LF on Windows and definitely are LF on Linux, macOS & alike.
If this sounds unfamiliar to you, check out Scott Hanselman's nice explanation on this topic.
on my Windows machine I forced Visual Studio Code to always safe it with LF line endings - just to be safe when copying this file back and forth between various OS platforms
Keywords
Keywords like IdentityFile
or HostName
are harmonized when
- reading from
config
file into HashTable - adding or updating entries
according to notation usually seen in documentation like.
JSON
Once list of hosts is loaded, it can also by converted to JSON:
$hostList = Get-ConfigHostList
$hostList | ConvertTo-Json
{
"dummy": {
"User": "johndoe",
"HostName": "dummy.somecloud.com",
"IdentityFile": "~/.ssh/myprivatekey"
}
}
This even allows to export SSH config to a JSON file, manage it in that format and then import it back:
$hostList = Get-ConfigHostList
$hostList | ConvertTo-Json -AsHashtable | Set-Content "ssh-config.json"
... do your magic here ...
$hostList = Get-Content "ssh-config.json" | ConvertFrom-Json -AsHashtable
Set-ConfigHostList $hostList
Top comments (1)
added JSON samples