Run SFTP commands using Docker

Run SFTP transfers from an Alpine container with sshpass, without installing an SSH client on the host.

1 min read Updated

This script runs SFTP transfers from a throwaway Alpine container, installing the SSH client and sshpass on the fly. It is useful on hosts where you do not want to install an SSH client or manage credentials permanently. The script is reproduced below.

sftp.sh

bash
#!/bin/bash

set -u

docker.sftp() {
  docker run --rm -v $(pwd):/src -w /src -e SSHPASS=$SFTP_PASSWORD alpine sh -c "
    apk update
    apk add --no-cache openssh-client sshpass
    sshpass -e sftp -q -o BatchMode=no -o StrictHostKeyChecking=no $SFTP_USERNAME@$SFTP_SERVER << EOF
      $@
      bye
    EOF
  "
}

# list files
docker.sftp ls -l /

# download file x.zip
docker.sftp get path/to/x.zip .

Search articles

Type to filter articles. Use the arrow keys to move through results and Enter to open one. Press Escape to close.