Introduction
When I was copying files or binaries from my Win machine into Raspberry or Azure VM, I was using WinSCP every time. It is ok when I have to do it once after a build. But when I have to copy it ten times in one hour, because I am fixing a problem, it is annoying.
So I decided to automate it. It is possible to use WinSCP from command line. But there is a better option – PowerShell Module POSH-SSH, which contains CmdLets for conneting via SSH, SCP or SFTP.
Example – A Script to Copy Files on Linux Machine and Switch with Previous Version
# install latest version of the module iex (New-Object Net.WebClient).DownloadString("https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev")
And the script itself:
$userName = "USER_NAME" $credentials = New-Object -TypeName System.Management.Automation.PSCredential ($userName, (new-object System.Security.SecureString)) $sshKey = "SSH_KEY_PATH" $localFolder = "LOCAL_FOLDER_PATH" $remoteFolder = "REMOTE_FOLDER_PATH" $computerName = "MACHINE_ADDRESS" $port = 22 $commands = @("CMD_1", "CMD_2", "CMD_3") Write-Host "Uploading data from $localFolder to $remoteFolder on $userName|$computerName|$port" -ForegroundColor Yellow Set-SCPFolder -LocalFolder $localFolder -RemoteFolder $remoteFolder -ComputerName $computerName -Port $port -AcceptKey -Credential $credentials -KeyFile $sshKey Write-Host "Done" -ForegroundColor Yellow Write-Host "Connecting to $userName|$computerName|$port to execute commands" -ForegroundColor Yellow $session = New-SSHSession -ComputerName $computerName -Port $port -AcceptKey -Credential $credentials -KeyFile $sshKey ForEach ($cmd in $commands) { Write-Host "Executing $cmd" -ForegroundColor Yellow $result = (Invoke-SSHCommand -SSHSession $session -Command $cmd).Output Write-Host $result.split("`n") } Remove-SSHSession -SSHSession $session
This code does following:
- It copies folder LOCAL_FOLDER_PATH into REMOTE_FOLDER_PATH on target machine via SCP (and SSH key)
- Next it connects via SSH (key) and executes commands CMD_1, CMD_2 and CMD_3.
So now, after each new build I can run this script and a new version of the project will be uploaded to the machine. Or this script can be set as a post build task into pipeline.