appzasGamesToolsDevLearnReferenceNetworkTimeCalculatorsCompareLLM prices

Copying files and port forwarding

Lesson 5 of 612 minBeginner

Transfer files with scp, sftp and rsync, then forward ports through an SSH connection.

Copy files with scp

scp report.pdf ana@server.example.com:/home/ana/        # upload
scp ana@server.example.com:/var/log/app.log .            # download to current dir
scp -r project/ ana@server.example.com:/home/ana/        # a whole directory
scp -P 2222 file.txt ana@server.example.com:~            # custom port: uppercase P

sftp and rsync

  • sftp ana@server.example.com opens an interactive session with ls, get, put and cd.
  • rsync -avz -e ssh project/ ana@server.example.com:/home/ana/project/ copies only what changed, so repeated transfers are fast. Mind the trailing slash: project/ copies the contents, project copies the folder itself.

Local port forwarding (-L)

A tunnel carries traffic for another service inside your SSH connection. Suppose a database listens only on localhost of a remote server. This makes it reachable on your laptop:

ssh -L 5433:localhost:5432 ana@db.example.com

Read it as -L local_port:destination_host:destination_port. Connections to localhost:5433 on your machine travel through SSH and come out on the server, which connects to localhost:5432 as seen from the server. Add -N to open the tunnel without a shell.

Remote (-R) and dynamic (-D) forwarding

  • -R 8080:localhost:3000 exposes a service on your machine through a port on the server. It is the reverse of -L.
  • -D 1080 starts a local SOCKS proxy. Point a browser at localhost:1080 and its traffic exits from the server.

CarefulTunnels punch holes through firewalls. Open them only for services you are allowed to reach, and close them when you finish.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which option copies a whole directory with scp?
2. Which flag sets the port in scp?
3. In `ssh -L 5433:localhost:5432 ana@db.example.com`, what is port 5433?
Hintssh -L local_port:host:port user@server

Key terms