Automatic Script for SSH Command and SFTP Download In Git Bash

Here’s a script I wrote today to automatically execute a command over SSH using Putty’s PLINK and subsequently download a file using Putty’s PSFTP from a remote Linux host.

My exact use case is using this to execute a remote command that pulls a file from a Docker container to a temp directory. Then I download that file to my local Windows computer.

This pairs well with another blog post I wrote that allows you to automatically set up a public/private key pair and simply copy paste to a notepad located at the below link.

https://garrett.dev/2019/06/13/bash-script-for-automatic-creation-and-generation-of-public-private-key-for-linux-server-login/

Automate everything – that’s my philosophy.

#Ensure nothing happens outside the directory this script is ran from
cd "$(dirname "$0")"
SCRIPT_DIRECTORY=$(pwd)

REMOTE_HOSTNAME="hostname.com"
REMOTE_USERNAME="username"

REMOTE_COMMAND="bash -c 'cd /remoteDirectory/subDirectory/ && sh getFromDockerContainer.sh'"

#Double slash is for git bash path conversion compatibility
REMOTE_FILENAME="//remoteDirectory/subDirectory/file.extension"
LOCAL_FILENAME="$SCRIPT_DIRECTORY/file.extension"

LOCAL_PRIVATE_KEY="$SCRIPT_DIRECTORY/private_key.ppk"

PLINK="/c/Program Files/PuTTY/plink.exe"
PSFTP="/c/Program Files/PuTTY/psftp.exe"

rm -f "$LOCAL_FILENAME"

"$PLINK" -i "$LOCAL_PRIVATE_KEY" "$REMOTE_USERNAME@$REMOTE_HOSTNAME" "$REMOTE_COMMAND"

TEMP_BATCH_FILE="$SCRIPT_DIRECTORY/psftp.batch"

echo "get $REMOTE_FILENAME" > "$TEMP_BATCH_FILE"

"$PSFTP" -i "$LOCAL_PRIVATE_KEY" -b "$TEMP_BATCH_FILE" "$REMOTE_USERNAME@$REMOTE_HOSTNAME"

rm -f "$TEMP_BATCH_FILE"

One thought on “Automatic Script for SSH Command and SFTP Download In Git Bash

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s