SFTP uses a single TCP connection. In general, TCP connection is stateful. As such, once opened both sides can send data to each other. Only the passive side of the connection needs to initially have a well known port number opened (22 for SSH/SFTP in this case). The active side opens a random port number that the passive side learns from the TCP connection initiation packed. This passive-side port closes with the TCP connection. While the active-side port is kept open for future TCP connections.
The SFTP protocol uses strictly request-response model. I.e. although the TCP allows both sides to send data anytime, with the SFTP, the server never sends data on its own, but always in a response to client request. Note that this does not mean, that no unsolicited data flows from the server to the client on network level, as in both underlying protocols of the SFTP (the TCP and the SSH) both sides of connection can send (and send) packets anytime.
Simplified flow is:
- SFTP client initiates TCP connection to remote port 22 (this causes implicit open of random local port on client side, this is done by operating system).
- SSH protocol initialization and authentication occurs.
- SFTP client requests SSH server to start SFTP server. Note that SFTP server is not a continuously running process. It is a sub-process/sub-service of SSH server, which is continuously running (=listening on port 22)
- SFTP protocol initialization occurs.
- SFTP (contrary to FTP protocol) is stateless, as such it does not have a concept of a working directory. As such changing remote working directory with the
cd
command is simulated on client side. The SFTP server is not aware at all of client remote working directory. SFTP client typically only verifies existence of the new working directory with the SFTP server.
- The
ascii
command: The OpenSSH sftp
client does not have ascii
command. You should get "Invalid command." Unless you use other client than OpenSSH.
- The
get
command: For file transfers the SFTP protocol offers a similar block-level API as most operating systems (contrary to a stream API of FTP protocol). So SFTP client sends "open file" request, over the existing connection, followed by repetitive "read block" requests and "close file" request. As with any SFTP requests, responses go back over the same TCP connection.
- At the end, the TCP connection is terminated and connection-specific random local port is closed.