How to Transfer files securely using SCP Command in Linux

The scp(secure copy) command allows you to copy files or directories (use the -r option to copy directories) between remote systems. A connection is established, files are copied, and the connection closes.

Transfer file from local server to remote server

To copy a file to a remote system (upload), the format of the scp command is:

# scp [options] local-file [user@]to-host[:remote-file]

For example, to copy a file named test to the remote user’s home directory on host03 with user root.

# scp /var/tmp/test root@host03

To transfer the file to any other location on remote host than the user’s home directory :

# scp /var/tmp/test root@host03:/data

Transfer file to remote host with new name on remote host

To copy the same file to the same location but rename it to new_test use the below command.

# scp test root@host03:/var/tmp/new_test

Transfer file from remote server to local server

To copy a file from a remote system (download), the format of the scp command is:

# scp [options] [user@]from-host:remote-file local-file

For example, to copy a file named new_test from user’s home directory on remote host03:

# scp host03:new_test .

The dot (.) here represents the current directory of the user on local server.

To transfer file from remote host to local host with new name

To copy a file named new_test from user’s home directory on remote host03 and rename it to newer_test:

# scp host03:new_test newer_test

Transfer directories

To transfer directory from local server to remote server(host03) recursively use the -r option with scp command.

# scp -r /dir root@host03:/data

Similarly to transfer directory from remote server to local server recursively:

# scp -r root@host03:/data /var/tmp

Use different port than 22 with scp

By default the port used by ssh/scp commands is 22. If you want to use a port other than this use the -P switch with scp command. For example:

# scp -P 2222 testfile root@host03:/var/tmp
Related Post