Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Script Name: powerssh
# Version: 1.0.0 (24. June, 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"
# With password and no output
# .\powerssh.ps1 -server hostname -login username -pw password -quiet -script task.sh
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,
[string]$log = "powerssh.log",
[switch]$quiet = $false,
[switch]$noBatch = $false,
[switch]$agentForwarding = $true,
[switch]$verbose = $false,
[switch]$acceptHostKey = $true # For convenient. Make sure the server is the computer you think it is.
)
$plinkPath = Join-Path -Path $PSScriptRoot -Childpath "Plink.exe"
if (-not (Test-Path $plinkPath)){
Write-Host "Missing Plink.exe in script path. Please download it from http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe"
exit 1
}
if ($key -eq "" -and $pw -eq "") {
Write-Host "You must supply either a password or key file."
exit 1
}
if ($script -eq "" -and $cmd -eq "") {
Write-Host "You must supply either a shell script file or command."
exit 1
}
if ($key -ne "" -and $pw -ne "") {
Write-Host "Notice: Only password or key file is required. Using key file."
}
if ($script -ne "" -and $cmd -ne "") {
Write-Host "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 ($noBatch -ne $true) {
$command += " -batch"
}
if ($agentForwarding -eq $true) {
$command += " -a"
}
if ($verbose -eq $true) {
$command += " -v"
}
if ($script -ne "") {
$command += " -m " + $script
} else {
$command += ' "' + $cmd + '"'
}
if ($quiet -eq $true) {
$command += " > " +$log
} elseif ($log -ne "") {
$command += " | tee-object -filepath " +$log
}
if ($verbose -eq $true) {
Write-Host "Command to Plink:"
Write-Host $command # Write out the command for debugging
Write-Host ""
}
Invoke-Expression $command
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment