Archived Forum Post

Index of archived forum posts


How to Change Directory in SSH/SFTP?

Sep 17 '17 at 07:50

How to change directory and upload file to desired path instead of RealPath?

Accepted Answer

The SFTP protocol (Secure File Transfer over SSH) is an entirely different protocol than FTP.

The FTP protocol specification is located here:
The SFTP protocol specification is located here:

Note 1: There are many different versions of the SFTP protocol specification, with later versions supporting minor additional features, but nothing related to this discussion.

Note2: "FTPS" (as opposed to "SFTP") is the FTP protocol using TLS for a secure communications channel.

In the FTP protocol is stateful, meaning it has the concept of "current remote directory". After logging in, you are "in the HOME directory of the FTP user account". There is a command to change the current remote directory. If you specify a remote filepath with no path, such as "xyz.pdf", then it is uploaded to the current remote directory.

The SFTP protocol, however, is NOT stateful. There is no concept of being in a "current remote directory". You can examine the protocol specifications, and in the case of SSH/SFTP, there are no commands to change remote directory. Therefore, each remote file path passed in an SFTP command must be either a remote path that is absolute on the server, or a path relative to the home directory of the SSH user accout. For example, let's say your SSH user account HOME directory is /home/billingsworth, and there is a file /home/billingsworth/abc/xyz.pdf. The path for this remote file may be specified in these ways:

  1. /home/billingsworth/abc/xyz.pdf
  2. abc/xyz.pdf

Other options of course include:

  1. ./abc/xyz.pdf
  2. ./abc/../abc/../abc/xyz.pdf

Why does it seem like FileZilla has a current remote directory with SFTP?

FileZilla is an application (not an API), and it is providing the appearance of a "current remote directory" with SFTP. In FileZilla, when you "change remote directory" to directory "abc", no command is actually sent to the SSH/SFTP server. FileZilla is simply noting that you are "in the directory abc". Thus, when you choose to upload or download a file, such as "xyz.pdf", FileZilla is the constructing a path to send (such as "abc/xyz.pdf" using the notion of what you see as your current remote directory. There there is no actual SFTP command to "change remote directory".

What is RealPath

The RealPath method is a command in the SFTP protocol that allows one to find the real absolute path on the server. For example, if "./abc/../abc/../abc/xyz.pdf" is passed to RealPath, then it should return "/home/billingsworth/abc/xyz.pdf". RealPath is simply a utility method to get remote path information in a consistent form.