How to Specify Destination Port in SCP Command: Fixing SSH Port Connection Issues


2 views

Many developers encounter this common pitfall when trying to use SCP with non-standard SSH ports. The -p flag doesn't do what you might expect - it actually preserves file modification times, permissions and modes during transfer (similar to rsync).

To specify a custom SSH port for SCP, you need to use the -P flag (uppercase P):

scp -P 2222 svn_backup.tgz user@xxx.xxx.xx.xxx:/path/to/new/svn/

Note that this is the opposite of SSH's -p flag, which can be confusing. That's why you often see people trying the lowercase version by mistake.

If you frequently connect to servers on non-standard ports, consider these approaches:

# Using SSH config file (~/.ssh/config)
Host myserver
    HostName xxx.xxx.xx.xxx
    User username
    Port 2222

Then you can simply use:

scp svn_backup.tgz myserver:/path/to/new/svn/

If you're still having problems, add the verbose flag to see connection details:

scp -v -P 2222 svn_backup.tgz user@xxx.xxx.xx.xxx:/path/to/new/svn/

This will show you exactly which port SCP is attempting to use and can help identify authentication or network issues.

When using non-standard ports:

  • Ensure your firewall rules allow the custom port
  • Consider using key-based authentication instead of passwords
  • Regularly monitor your SSH service logs for unauthorized access attempts

Many developers encounter confusion when trying to specify a custom SSH port for SCP transfers. The -p flag in SCP doesn't control the connection port - it actually preserves file modification times, access times, and modes during transfer.

To specify a custom port, you need to use the -P flag (uppercase P) instead. Here's the proper syntax:

scp -P 2222 local_file.txt user@remotehost:/path/to/destination/

Alternatively, you can use the port specification in the target path:

scp local_file.txt user@remotehost:2222:/path/to/destination/

Basic file transfer with custom port:

scp -P 4567 project.tar.gz dev@server.example.com:/home/dev/backups/

Recursive directory transfer:

scp -P 2222 -r /local/directory/ admin@backup.server:/remote/backup/

Using SSH config aliases:

For frequent transfers, consider adding this to your ~/.ssh/config:

Host myserver
    HostName server.example.com
    User devuser
    Port 4567

Then simply use:

scp file.txt myserver:/destination/

If you're still experiencing connection problems:

  • Verify the remote SSH server is listening on your specified port (ss -tulnp | grep sshd)
  • Check firewall rules (sudo ufw status or iptables -L)
  • Confirm the SSH service is configured to accept connections on non-standard ports

When using non-standard ports:

  • Always combine with key-based authentication
  • Consider using VPN tunnels for sensitive data
  • Monitor your SSH logs for unauthorized access attempts