Easy Way To Copy Files Over SSH

SSH is a protocol that can help you manage a remote computer, as well as let you upload and download files. You can also use SSH keys instead of a password!
Copying files requires the secure copy command, which is actually pretty simple:

scp [options] [original file] [destination_file]

The syntax for the [destination file]  portion is usually where users have the most difficulty. When you are addressing a remote file you should use this format:


The server, in this case, can either be an IP address or a URL. After the IP/URL address you'll just write the standard file path after a colon.. Here’s an example:

scp –P 40050 Desktop/filename.txt nms@

We used the -P flag here which let’s you specify the port you want to use. Otherwise, it'll just default to port 22. Note that this flag is case sensitive and should be uppercase.  Depending on how your system is configured you might not need to use this flag.
Then I just used the original file, which is “filename.txt,” and it is located in the “Desktop” directory. The destination file is located in “~/Desktop/filename.txt”. The command has been executed by the user “nms” on computer “”.
What if you need to do the reverse operation and copy a file from a remote server to your local machine? You would then switch the source and destination within the same command.

Here’s an example:

scp –P 40050 nms@ Desktop/filename.txt

I will have copied a file from the folder” ~/Desktop/” of the remote computer to the “Desktop” folder on my computer.
If you want to copy a whole directory you will have to use the -r flag, in lowercase. The command would then look like this:

scp -r –P 40050 nms@ Desktop/filename.txt

You can actually “combine” flags. Instead of using:

scp –P –r …

You can use:

scp –Pr …

SSH Without Passwords

Secure copy is great as you can put it in scripts and let it perform backups to remote computers. However, you won’t always be around to provide the password. Being asked to enter a password every time you run the script can get tiresome.Thankfully, you can use key files to get around this problem. You can generate two key files; a private one for your computer and a public one for the remote computer. You’ll then be able to use these instead of a password

First use the following command on your computer:

ssh-keygen –t rsa

The command will generate two keys which should be kept in:


with the name “id_rsa.pub” for the public key and the name “id_rsa” for the private key.
You’ll be asked about where to save the keys. If you want to use the defaults, just hit Enter and you will also be asked to type a passphrase. You can hit the Enter key again to leave it blank.
You should then copy the file with the public key to the remote computer. Now the “scp” command can be used to put the keys in place, like this:

scp -r –P 40050 .ssh/id_rsa.pub nms@

The destination of the key on the remote server will be located in:


And you’re done!
You’ve learned how to use the scp command by itself, as well as generating key files, and using scp with key key files to copy data without using a password. Secure copy over SSH is very flexible. You can use the command for small operations or in conjunction with server control panels for security and flexibility in bulk operations.

February 24 2016

Add or review comments

Please leave your comment

Existing comments

Comments 18

David Pickett
I always liked something more like: $ find ... -type f | cpio ... | gzip -9 | ssh user@system 'gunzip | cpio ...' It allows you to select your own favorite compression and level, distributes the load over many cores/CPUs, relieves ssh of secondary tasks so it just does d/encryption. If directory creation is not an issue, it can be parallelized by tools like GNU parallel. Even then, you can do directory creation first, as it is not CPU or net bandwidth sensitive/intensive. Fun for all those cores! Options for cpio can be set for less compatible hosts, update only if older.
David Pickett
PS: When bandwidth is low, slower but more intense compressors like bzip2 may be worthwhile to minimize that hit. The slower speed can be compensated by more parallelism. (Leave some bw for others!) At very least, consider scp with high compression, possibly in n parallel sessions, to speed things and spare some bw for others. Each scp could be give m file names, for instance. This spares the cost of SSH session setup.
I presonally like the rsync option over ssh more... since it can continue where it left off when the pipe breaks or the network stalls. Especially useful for large collections of files and directories preserving rights... Works almost the same as scp but can also handle updates. <code> rsync -rvah --progress [localDir[ [user]@[remote host]:[remote path] </code>
When the number of files to transfer is small, scp directly is a good option. However, when there are many files or big size of them, or the connection can be lost in progress (wireless) rsync has advantages as it can restart easily.
Бажаєте фіксувати рухи лісових тварин для більш ефективного полювання? Тоді [url=https://intervision.ua/videosposterejennya]відеоспостереження[/url] – це саме те, що Вам потрібно! З її допомогою Ви можете робити якісні та чіткі фотографії лісових мешканців без власної присутності. Наш Інтернет-магазин пропонує Вам широкий вибір фотопасток від надійних світових виробників.
Современная предприятие TVP больше 6 лет имеет технологическое оборудование для ремонтных работ,а так же возведения очистных сооружений для комбикормового завода. Такая продукция сертифицирована. Любой человек в процессе своей жизнеспособности для разных собственных надобностей использует воду. Для ее прямого предназначения она загрязняется, видоизменяется ее состав и физические свойства. Для этой цели и производятся очистные сооружения. Очистные сооружения – предварительная очистка поступающих на очистные сооружения сточных вод с целью подготовки их к биологической очистке. Допускается также их рецикл и повторнаяиспользование в промышленных делах всевозможных заводов. В следствииочищения стоков производств в местных постройках наибольшая накопление загрязняющих материалов убавляется, а присутствующие в них необходимые компоненты извлекаются. В последующейтребование воды отправляются на доочистку в общепроизводственных сооружениях. TVP - это фирма, которая устанавливает, проектирует, а также занимается возведеньем очистительных построек для консервного завода. Принимаем заказы на установку, исправление,работу по проектированию,в любом мегаполисе Нашего государства. Услуги выполняются быстро и в назначенный срок. санитарно защитная зона очистных сооружений - [url=https://tvpolimer.ru/]воздуходувка для очистных сооружений[/url]
Do you like something super new? Open and look at this site. Only here the choice of young girls for every desire and completely free! They are obedient slaves, they will implement anything you order ! http://gov.shortcm.li/kings#N65
If you like something super new? Take a look at this page. Only there the choice of girls for every unique guy and completely free! They are responsible slaves, they will and want do anything you say ! http://gov.shortcm.li/kings#G23
Do you need something new? Open and look at this offer. Only there the choice of young girls for every taste and completely free! They are obedient slaves, they will and want do anything you order ! http://gov.shortcm.li/kings1#Z59
Здравствуйте! Нашел познавательную информацию на этом сайте: http://hellbro.ru : http://hellbro.ru/foto-prikoly-interesnoe/4551-netipichnye-oteli.html [b] Нетипичные отели [/b] [url=http://hellbro.ru/foto-prikoly-interesnoe/9384-seksualnye-devushki-v-bikini-i-bele.html] Сексуальные девушки в бикини и белье [/url] http://hellbro.ru/foto-prikoly-interesnoe/4167-7-samyh-romantichnyh-domikov-na-dereve.html
Всем привет! Класный у вас сайт! Что думаете по этим новостям?: http://electek.ru/information-technology-it/21964-smi-kompaniya-google-otkazhetsya-ot-brenda-nexus.html [b] СМИ: Компания Google «откажется» от бренда Nexus [/b] [url=http://electek.ru/news/12782-deputaty-predlagayut-nakazyvat-za-krazhu-velosipedov-kak-za-ugon-avtomobilya.html] Депутаты предлагают наказывать за кражу велосипедов как за угон автомобиля [/url] http://electek.ru/news/10831-specnaz-gru-dnr-smertonosnyy-i-besposchadnyy.html Ещё много всего по теме нашел тут: [b] события в днр сегодня [url=http://electek.ru/]http://electek.ru/[/url]
Visitors to room can find many questionnaires massage specialist of any age and nationality performing body work massage in the city New York. Masseuses are able not only to give pleasure in this way, but also to the strong semi-gentlemen. Specialists perform japanese a massage that will produce a Strong gender a vivid impression. Prices for japanese massage depends on qualification Women and the skills that she possesses. Before making a choice, carefully study the prices for services and customer feedback about the work of one or another masseur specialist. We are sure that the search for a real professional masseur will be crowned with success and you will be satisfied with the quality of our services. Women are skilled workers in their field and they will help you relax after a hard day. Our showroom works in NY. - [url=https://body2body.massage-nyc.com/]body to body massage[/url]
Do you want something new? Look at this site. Only here the choice of young girls for every desire and completely free! They are responsible slaves, they will and want perform anything you command ! http://gov.shortcm.li/kings1#W59
Приветствую всех! Нашел удивительную информацию на этом сайте: http://limonos.ru : http://limonos.ru/design/3794-pervyy-reklamnyy-multik-dlya-dior-rose-des-vents.html [b] Первый рекламный мультик для Dior Rose des Vents [/b] [url=http://limonos.ru/foto-prikoly-interesnoe/6954-chto-islandcu-horosho-to-russkomu-ne-ponyat.html] Что исландцу хорошо, то русскому не понять [/url] http://limonos.ru/foto-prikoly-interesnoe/4119-kak-ya-letal-na-spasatelnom-vertolete.html
As you prefer something super new? Open and look at this page. Only there the choice of women for every will and completely free! They are obedient slaves, they will and want do everything you say ! https://rebrand.ly/governy#N16
Comprar Viagra En Espana Sin Receta [url=http://buygenericvia.com]viagra[/url] Como Comprar Viagra En Espana En La Farmacia Propecia Depression Reversible Prix Du Xenical En Pharmacie France Acheter Cialis Ligne Canada Online Lasix Generic [url=http://genericviabuy.com]viagra[/url] Amoxicillin 500 Tv Viagra Price [url=http://demalan.com]viagra[/url] Cheap Plavix Canada Pharmacy Levitra Prezzo In Vendita [url=http://realviaonline.com]generic cialis[/url] Purchase Amoxicillin Without Prescription Cephalexin Side Effects In Dogs Viagra Fa Dimagrire Viagra Para Hombres Amoxicillin Pediatric Tab [url=http://catabs.com]priligy sin receta andorra[/url] Achat Tadalis Sx Sans Risque Buy Fluoxetine Online
Привет всем! Нашел приколы за день на этом сайте: http://watafak.ru : [url=http://watafak.ru/prikoli_umor/]приколы смех до слез[/url] юмор года новое интересное видео http://watafak.ru/interesnoe-video/ http://watafak.ru/foto-prikoly-interesnoe/7809-podborka-prikolnyh-foto-111-foto.html [b] Подборка прикольных фото (111 фото) [/b] [url=http://watafak.ru/foto-prikoly-interesnoe/1408-samyy-neobychnyy-dizaynov-stolov.html] Самый необычный дизайнов столов [/url] Самый необычный дизайнов столов http://watafak.ru/foto-prikoly-interesnoe/8871-molodezh-razvlekaetsya.html
This is may depend from implementation front-rank equipment park,technology,equipment,algorithm,cleaning,methods,equipment,components,mechanisms and industrial equipment, specialized detergents and cleaning funds and also beautiful organization work cleaning service. In our world use support Cleaning firms made necessarily authoritative and relevant. Some enterprises and organizations Partnership long for a time enjoy help with cleaning companies, but not conclude personal frames swabber for such types of services as Cleaning a private house and Bathroom cleaning in TriBeca . Long-term practice General Partnership in Chinatown & Little Italy owner specialized company is STEPHEN WILLIAMS, revealed that hired trained staff cleaning firms produce cleaning well faster, neater, scrupulous and cleaner, than for example own regular cleaners. You will be spared from wasting time on training and recruitment frames , on check his work, you it will not be necessary to allocate room for cleaners and organize storage inventory. We Limited liability Limited Partnership is that is on the street Douglaston invite you personally work with uson profitable conditions. Any Economist Proves You contain Multiple workman at a loss in collation with employ foreign cleaning service. elite cleaning services : [url=https://cleaningsnyc.club]my home cleaning services[/url]
Приветствую! Нашел приколы за день на этом сайте: http://okaybro.ru : [url=http://okaybro.ru/prikoli_umor/]новые приколы[/url] приколы на ютубе до слез анимация скачать бесплатно http://okaybro.ru/gifki-gif-animacii/ http://okaybro.ru/6164-novaya-shkola-v-stolice-danii.html [b] Новая школа в столице Дании [/b] [url=http://okaybro.ru/2894-keti-perri-v-billboard-magazine.html] Кэти Перри в Billboard Magazine [/url] [b] Кэти Перри в Billboard Magazine [/b] http://okaybro.ru/179-katmandu-zhivoy-gorod.html

Get notified about new publications and product updates.
Please note we do not share information to anyone.