Saturday, October 10, 2015

Copy Files and Folders between Server and Client using scp

You may want to move files around between the server and client. This can be done easily for Unix systems using scp.

I am currently running Mac, and I'd like to copy the .vimrc file from Ubuntu to Mac so that I can use vim on my Mac as well. To do this, simply open up the terminal in Mac and run
$ cd ~
$ ls -a .vimrc
This command will show you that .vimrc does not exist in the home folder on Mac.

To copy the file, simply enter
$ scp <user_name>@<IP address>:<source_file_path> <destination_path>
In this case, it would be
$ scp linuxnme@ .
Enter the Linux login password, and you should see that the file has been successfully copied. Note that you do not have the tab completion feature for the remote computer, so make sure that you know the file path exactly.

NOTE: If you are printing something in bash when it starts up, scp may not work, as it expects to transfer the data via stdin and stdout. That is, do not put any echo statements in ~/.bashrc file or at least make sure that it is printing in the interactive mode only.

To see if it has been copied to my mac, simply re-enter the command
$ ls -a .vimrc

You will see that the file has been successfully copied! Note that this works only when ssh server is running. That is, if we had not installed openssh-server in the previous post, we would have not been able to do this! Let's test what happens then.

On Ubuntu, open up terminal and stop ssh server by entering
$ sudo stop ssh

Now switch to the Mac terminal and repeat the scp command again
$ scp linuxnme@ .

Well, this does not work as expected. To restart the ssh server on Ubuntu, open up terminal in Ubuntu and enter
$ sudo start ssh
This will start the ssh server.

I can also copy from Mac to Ubuntu by reversing source and destination. For example, if I were to copy ~/test.c from Mac to Ubuntu, I would simply enter from Mac terminal
$ scp ~/test.c linuxnme@
Note that tilde ~ refers to the home directory, and period . refers to the current directory.

To copy a folder, I can use -r option with scp. So, I have a folder test_folder in the current directory, and in the directory is a file called test. I will copy this entire folder to Ubuntu using scp with the following command
$ scp -r test_folder/ linuxnme@

To check whether it worked, I will remote into Ubuntu using ssh and voila! The test_folder along with its file test has been successfully copied!

No comments:

Post a Comment