SCP (Secure Copy Protocol) is a command-line utility that allows users to transfer files between two machines over a network securely. Typically, SCP operates over the default SSH port, 22. However, there are situations where the SSH server is configured to use a non-standard port for enhanced security. In such cases, specifying a port number in the SCP command becomes essential.
In this guide, we’ll explore how to use SCP with a specified port number.
Specifying a Custom Port with SCP
To specify a custom port, use the -P flag followed by the port number. Note that the -P option in SCP is uppercase (-P) and not to be confused with the lowercase -p option, which preserves file attributes.
Here is a basic syntax:
scp -P [custom-port] [Source] [Destination]
Let’s go through some practical examples:
Example 1: Copying a File from a Local Machine to a Remote Server
Suppose you want to copy a file named example.txt from your local machine to a remote server running SSH on port 2222:
scp -P 2222 /home/user/example.txt user@remote_host:/home/user/
Explanation:
- -P 2222: Specifies the custom port number.
- /home/user/example.txt: Path to the source file on the local machine.
- user@remote_host:/home/user/: Remote destination, where user is the username and /home/user/ is the target directory on the remote server.
Example 2: Copying a Directory from a Remote Server to a Local Machine
Now, let’s copy an entire directory named project from a remote server to your local machine. The SSH service on the remote server runs on port 2222:
scp -P 2222 -r user@remote_host:/home/user/project /home/local_user/
Explanation:
- -P 2222: Specifies the port number.
- -r: Copies the entire directory recursively.
- user@remote_host:/home/user/project: Source directory on the remote server.
- /home/local_user/: Destination directory on the local machine.
Practical Use Cases for Specifying a Custom Port
1. Enhanced Security by Changing Default SSH Port
One of the most common reasons for specifying a custom port is to avoid using the default SSH port, 22. Changing the SSH port can mitigate automated attacks or bots scanning for open SSH ports, and administrators can reduce the likelihood of unauthorized access attempts using a non-standard port.
2. Multiple Services on the Same Host
In environments where multiple services need to be accessed over SSH, different ports can be used to differentiate between them. For instance, one service might use port 2222 while another uses 2022.
Conclusion
SCP is a powerful tool for secure file transfers between machines, and specifying a port number is often necessary in complex or hardened network environments. You can now ensure your file transfers are efficient and secure. You can now easily use scp to transfer files between multiple servers on dedicated server hosting from Atlantic.Net!