Powershell script to run ssh commands on multiple devices

One day I was in need to add backup settings on 140 juniper devices, and to not cause death due to boringness I decided to script up this task, and here is the script:

This script is easy to change for any purpose you need, I just used it to set up an SCP backup repository. The biggest challenge was that PowerShell is working with CSV data as with objects and to make it work we need to first – Transform it to a string and then strip out any spaces and next line symbols. After that, it’ll work perfectly fine.

Get-Credential is requesting credentials to access the switch via SSH. Also, you need to install the Posh-SSH module from the PS repository via Install-Module Posh-SSH.

Set-ExecutionPolicy Unrestricted -Force
Import-Module Posh-SSH

$CSV = Import-Csv C:\TEMP\Switches.csv
$Creds = Get-Credential


foreach ($Switch in $CSV)
{

$SwitchIP = $Switch.IP | Out-String
$SwitchName = $Switch.Name | Out-String
$SwitchIP = $SwitchIP  -replace '\s','' -replace '\n','' -replace '\s+',''
$SwitchName = $SwitchName  -replace '\s',' ' -replace '\n','' -replace '\s+',''
$SCP = "scp://username@address/$SwitchName/"
$Pass = "SuperSecurePassword"

Write-Host -ForegroundColor Yellow "Connecting to $SwitchIP"

New-SSHSession -ComputerName $Switch.IP -Credential $Creds -AcceptKey

Write-Host -ForegroundColor Yellow "Sending config"

$SSHStream = New-SSHShellStream -Index 0
$SSHStream.WriteLine("configure")
Start-Sleep -s 5
$SSHStream.read()
$SSHStream.WriteLine("rollback 0")
Start-Sleep -s 5
$SSHStream.read()
$SSHStream.WriteLine("set security ssh-known-hosts host YOURSERVERIPADDRESS ecdsa-sha2-nistp384-key AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBB7IyHKzLr5zYt9YspKYyBqm/bZZkZlC8dPdmpOHh3XGp28apRNHcFMd2i0JSQ0WbNRftsFXytKYst/RkDurfBXqe3NOoDWJA7jvliZB3EhM0yuRlNtuarrQzc0voX47bg==")
Start-Sleep -s 5
$SSHStream.read()
$SSHStream.WriteLine("edit system archival configuration")
Start-Sleep -s 5
$SSHStream.read()
$SSHStream.WriteLine("set archive-sites $SCP password $Pass")
Start-Sleep -s 5
$SSHStream.read()
$SSHStream.WriteLine("set transfer-on-commit")
Start-Sleep -s 5
$SSHStream.read()
$SSHStream.WriteLine("commit")
Start-Sleep -s 30
$SSHStream.read()
$SSHStream.WriteLine("commit")
Start-Sleep -s 30
$SSHStream.read()

Write-Host -ForegroundColor Yellow "Disconnecting"

Remove-SSHSession -Index 0



}

CSV file has a format: Name,IP

Have a nice day 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.