Home / Articles

SFTP connection over SSH tunnel


This article describes how to connect to an SFTP server over an SSH tunnel.

Assume you want to connect to the SFTP server (bar.example.com) which can only be accessed from a specific host (foo.example.com):

Network diagram.

On Windows, WinSCP allows you to configure the connection to go through an SSH tunnel:

WinSCP advanced site settings dialog.

But WinSCP does not run on macOS, or you may be using a computer without a graphical shell. You can use the sftp program to achieve the same goal. For example:

sftp \
  -o ProxyCommand='ssh \
  -W %h:%p \
  foo@foo.example.com' \

The command above means an SSH connection to foo.example.com as the foo user will be established first, then the SFTP connection to bar.example.com as the bar user will be established over the SSH connection.

Another example:

sftp -i bar.key \
-P 8022 \
-o ProxyCommand='ssh -i foo.key \
  -W %h:%p \
  -p 18022 \
  foo@foo.example.com' \

Similar to the previous example, however:

Note that you use the -P (uppercase) option to specify the port when using the sftp program, while you use the -p (lowercase) option to specify the port when using the ssh program.