# Script Name: powerssh # Version: 1.1.0 (9. July, 2014) # Author: Sveinn Steinarsson # Description: Use Powershell to connect to a remote server via SSH and run a shell script/command # Prerequisite: # plink.exe in script path (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) # Examples: # With key file (*.ppk) and script file # .\powerssh.ps1 -server hostname -login username -key keyfile.ppk -script task.sh # With key file and command # .\powerssh.ps1 -server hostname -login username -key keyfile.ppk -cmd "ls; pwd" Param ( [string]$server = $(Throw "Please provide a server hostname/ip"), [string]$login = $(Throw "Please provide a login username"), [string]$key, [string]$pw, [string]$script, [string]$cmd, [switch]$batch = $false, [switch]$agentForwarding = $true, [switch]$verbose = $false, [switch]$acceptHostKey = $true # For convenient. Make sure the server is the computer you think it is. ) $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path $plinkPath = Join-Path -Path $scriptPath -Childpath "Plink.exe" if (-not (Test-Path $plinkPath)){ Throw "Missing Plink.exe in script path. Please download it from http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe" } if ($key -eq "" -and $pw -eq "") { Throw "You must supply either a password or key file." } if ($script -eq "" -and $cmd -eq "") { Throw "You must supply either a shell script file or command." } if ($key -ne "" -and $pw -ne "") { Write-Output "Notice: Only password or key file is required. Using key file." } if ($script -ne "" -and $cmd -ne "") { Write-Output "Notice: Only script file or command is required. Using script file." } if ($acceptHostKey -eq $true) { $command = "echo Y|" + $plinkPath } else { $command = $plinkPath } $command += " -ssh " + $server + " -l " + $login if ($key -ne "") { $command += " -i " + $key } else { $command += " -pw " + $pw } if ($batch -eq $true) { $command += " -batch" } if ($agentForwarding -eq $true) { $command += " -a" } if ($verbose -eq $true) { $command += " -v" } if ($script -ne "") { $command += " -m " + $script } else { $command += ' "' + $cmd + '"' } $command += " 2>&1" if ($verbose -eq $true) { Write-Output "Command to Plink:" Write-Output $command # Write out the command for debugging Write-Output "" } $output = Invoke-Expression $command if ($LastExitCode -ne 0) { Throw $output } else { Write-Output $output Exit 0 }