- Копирование файлов через SSH
- Копирование файлов по SSH на Linux
- Как скопировать файл по SSH с локальной машины на удалённый сервер
- Как скопировать файлы с удалённого сервера на локальный компьютер
- Как скопировать файл по SSH с одного удалённого сервера на другой
- Как скачать папку со всеми файлами и подпапками
- Как подключиться к серверу по нестандартному порту
- Как передать и скачать файлы по SSH на Windows
- How to transfer files remotely using SSH
- Transfer file using scp
- Transfer file using sftp
- Transfer file using rsync
- Mount remote filesystem locally
- Secure Copy Protocol (SCP) in Linux: A Guide to File Transfer from Local to Remote Server
- Understanding SSH and SCP: The Basis for Secure File Transfers
- Introducing the SCP Command on Linux
- Using Linux SCP via SSH: A Guide on How to Copy Files
- Linux SCP from Local to Remote: How to Copy a Single File
- Linux SCP from Remote to Local: Copying a Single File
- Copying Several Files Using SCP
- Recursively Copy Files and Folders from Local to Remote using SCP
- Copy files using SCP with PEM or CER credential
- Final considerations
Копирование файлов через SSH
В статье мы расскажем, как копировать файлы в Windows и Linux-системах, и покажем основные команды, с помощью которых происходит передача файлов по SSH.
Для копирования файлов по SSH в Linux-системах и Windows используют разные инструменты:
- scp (Secure CoPy) — утилита для безопасного копирования данных между Linux-системами по протоколу SSH. Она входит в состав OpenSSH, поэтому для работы с утилитой не нужно устанавливать дополнительное ПО;
- pscp.exe — утилита для загрузки файлов по SSH в ОС Windows. Она обладает теми же возможностями, что и scp. Утилита входит в состав программы Putty — SSH-клиента для Windows. Скачать программу можно по ссылке.
Если файл, который вы хотите скопировать, уже существует на целевом хосте, при копировании он будет перезаписан.
Копирование файлов по SSH на Linux
Для Linux копирование файлов по SSH происходит с использованием команды scp. С её помощью можно копировать файлы:
- с локального компьютера на удалённый сервер,
- с удалённого сервера на локальный компьютер,
- с одного удалённого сервера на другой.
scp [опция] [источник] [получатель]
Как скопировать файл по SSH с локальной машины на удалённый сервер
Как загрузить файл на сервер по SSH? Для этого используйте команду вида:
scp [путь к файлу] [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу]
scp /home/test.txt root@123.123.123.123:/directory
Файл test.txt будет скопирован на хост 123.123.123.123 в директорию «/directory».
Как скопировать файлы с удалённого сервера на локальный компьютер
При подключённом SSH скачать файл на локальный компьютер с удалённого сервера можно с помощью команды:
scp [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу] [путь к файлу]
scp root@123.123.123.123:/home/test.txt /directory
Файл test.txt будет загружен с сервера 123.123.123.123 на локальный компьютер в папку «/directory».
Как скопировать файл по SSH с одного удалённого сервера на другой
Подключитесь по SSH к серверу, на котором расположен файл. Затем выполните команду:
scp [путь к файлу] [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу]
scp /home/test.txt root@123.123.123.123:/directory
Файл test.txt будет скопирован на хост 123.123.123.123 в директорию «/directory».
Как скачать папку со всеми файлами и подпапками
Если вы хотите скачать папку со всеми файлами и подпапками, используйте ключ -r:
scp -r [источник] [получатель]
Как подключиться к серверу по нестандартному порту
Бывает, что для подключения по SSH нужно указать нестандартный порт. Без указания порта команда подключается к серверу по стандартному 22 порту. Чтобы указать нестандартный порт, введите команду с ключом -P:
scp -P [источник] [получатель]
scp -P 12345 /home/test.txt root@123.123.123.123:/directory
Эта команда подключается по порту 12345 к серверу 123.123.123.123 и копирует на него файл «test.txt» с локального компьютера в директорию «/directory».
Как передать и скачать файлы по SSH на Windows
Скопировать файл по SSH на сервер можно командой:
pscp [путь к файлу] [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу]
Скачать файл по SSH с сервера командой:
pscp [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу] [путь к файлу]
Увидеть список папок и файлов на сервере можно через pscp.exe. Для этого введите:
pscp -ls [имя пользователя]@[имя сервера/ip-адрес]:[путь]
Если в пути или в названии файла есть пробелы, используйте кавычки:
pscp “C:\files or docs\file name” root@123.123.123.123:/home
How to transfer files remotely using SSH
Secure Shell (SSH) is a versatile protocol that enables secure access to remote computers. With its scp utility, you can transfer files between remote systems efficiently, using a syntax similar to the cp command.
Additionally, SSH can be utilized by other file transfer applications like sftp and rsync to ensure secure transfers.
Examples for the following file transfer methods are based on the above setup.
Make sure you have SSH access to the remote server with adequate permission to the remote files and folders.
Methods for remote file transfer using SSH:
Transfer file using scp
scp (secure copy) is the simplest method for transferring files remotely. It requires SSH access to the remote server and operates like the cp command but for remote transfers. When using scp, you must specify the remote host’s DNS name or IP address and provide login credentials. You can use scp for local-to-remote and remote-to-local transfers.
$ scp myfile.txt remoteuser@remoteserver:/remote/folder/
If the target folder (/remote/folder/) is not specified, it will copy the file to the remote user’s home directory.
$ scp remoteuser@remoteserver:/remote/folder/remotefile.txt localfile.txt
Using . as the copy target (replacing localfile.txt will copy the remote file to the current working directory using the same filename (remotefile.txt)
$ scp myfile.txt myfile2.txt remoteuser@remoteserver:/remote/folder/
$ scp * remoteuser@remoteserver:/remote/folder/
$ scp -r * remoteuser@remoteserver:/remote/folder/
GUI programs such WinSCP can also be used to transfer files between local and remote host using scp methods.
Transfer file using sftp
Secure FTP (sftp) functions similarly to FTP , but with a secure connection. Most commands are interchangeable between the two. The following sftp examples demonstrate the similarities to standard FTP commands:
$ sftp user@192.168.1.10 Connected to 192.168.1.10. sftp> dir file1 file2 file3 sftp> pwd Remote working directory: /home/user sftp> get file2 Fetching /home/user/file2 to file2 /home/user/file2 100% 3740KB 747.9KB/s 00:05 sftp> bye $
WinSCP can also be used for file transfer using SFTP protocol, but with graphical interface. The other popular tool is FileZilla.
Transfer file using rsync
To secure your rsync sessions with SSH, use —rsh=ssh or -e ssh alongside your usual rsync commands. The two commands below produce the same results:
$ rsync -av --delete --rsh=ssh /path/to/source remoteuser@192.168.1.10:/remote/folder/ $ rsync -av --delete -e "ssh" /path/to/source remoteuser@192.168.1.10:/remote/folder/
If these options aren’t specified, rsync will first attempt to connect to rsyncd. If rsyncd isn’t running on the remote system, it will automatically revert to SSH.
Mount remote filesystem locally
You can mount remote filesystems on your local host and access them as if they were local. To do this, you’ll need SSH access to the remote host and the sshfs utility.
Secure Copy Protocol (SCP) in Linux: A Guide to File Transfer from Local to Remote Server
We often need to move files from a local machine to a remote server or vice versa, especially when managing or deploying code on servers. One efficient way to do this is through Secure Copy Protocol (SCP), a tool that’s built into the SSH (Secure Shell) protocol. This guide will walk you through how to use SCP on Linux platforms like Ubuntu, Linux Mint, and Debian, among others.
SSH, or Secure Shell, is a protocol that allows secure access to remote computers.
Understanding SSH and SCP: The Basis for Secure File Transfers
SSH , an acronym for Secure Shell, is a protocol used to access remote computers securely. Built into this SSH ecosystem is the Secure Copy Protocol ( SCP ), an effective tool for transferring files between local and remote computers. Its syntax closely resembles the ‘cp’ (copy) command, but it’s geared towards remote file transfer.
Other file transfer applications, such as SFTP and rsync , also harness the power of SSH to secure their file transfers. These applications open up the possibility of securely copying files from local to remote servers, and vice versa.
Introducing the SCP Command on Linux
The SCP command in Linux is a utility for transferring files between remote computers. It’s included by default in most Linux and Unix distributions, including Linux Ubuntu, Linux Mint, Linux Debian, Arch Linux, etc., and is part of the OpenSSH packages.
SCP is your secure solution for transferring files between a remote location and a host, or from your local computer to a remote server, or even between two remote locations.
Using Linux SCP via SSH: A Guide on How to Copy Files
The difference between the cp command and the scp command is that the latter requires you to specify the remote host’s DNS name or IP address and provide username credentials. Here’s how to use SCP for copying files from your local machine to a remote server, and from a remote server to your local machine.
Linux SCP from Local to Remote: How to Copy a Single File
Copying a single file from your local computer to a remote computer using SCP involves the following syntax:
# From current folder you don't need to specify the file path scp myfile.txt [email protected]:/remote/folder/ # From any folder from your local computer, write the full local path to the file scp /full/path/to/myfile.txt [email protected]:/remote/folder/
Let’s break down these two examples:
In this first example, we’re using SCP to transfer a file called myfile.txt from the current working directory on our local machine to a folder on the remote server.
- myfile.txt is the name of the file we want to transfer.
- username is the username for your account on the remote server.
- remoteserver is the DNS name or IP address of the remote server.
- /remote/folder/ is the path of the directory on the remote server where you want to transfer the file.
By running this command, myfile.txt will be securely copied from your local machine to the specified folder on the remote server.
In the second example, we’re doing the same thing but the file we want to transfer isn’t in our current directory. Instead, it’s located elsewhere on our local machine, and we need to specify its full path.
- /full/path/to/myfile.txt is the absolute path to the file on your local machine. It provides complete information about the file’s location starting from the root directory.
So, when you run this command, again, myfile.txt will be securely transferred from the specified path on your local machine to the designated folder on the remote server.
Both of these SCP commands offer a simple yet powerful way to perform secure file transfer from a local machine to a remote server using SSH, irrespective of where your file is stored locally.
If the target folder on remote host ( /remote/folder/ ) is not specified, it will copy the file to the remote user’s home directory.
The user specified with username need to exist and have write permission to /remote/folder / in the remote system.
Linux SCP from Remote to Local: Copying a Single File
You can also copy a file from a remote server to your local computer using SCP. The syntax is similar, only that you invert the order of the local and remote information:
# From remote to current local folder scp use[email protected]:/remote/folder/remotefile.txt localfile.txt # From remote to local but specifying the local folder target to save the file scp [email protected]:/remote/folder/remotefile.txt /path/to/local/folder/localfile.txt
Using a . (dot) as the copy target (in our example replacing localfile.txt to . ), will copy the remote file to the current working directory using the original filename, in this case: remotefile.txt
Copying Several Files Using SCP
You can copy multiple files from your local machine to a remote server, or vice versa. You can either specify each file as a parameter, or use wildcards:
# Specify each file scp myfile.txt /local/folder/myfile2.txt [email protected]:/remote/folder/ # Use a wildcard to copy several files from remote scp [email protected]:/remote/folder/* .
Recursively Copy Files and Folders from Local to Remote using SCP
To copy recursively files and folders from local to a remote server, you need to use the option -r .
This is particularly useful when setting up a project structure on a remote server:
Copy files using SCP with PEM or CER credential
If you don’t want to type the remote user password when are copying files, you can use a .pem ou .cer file to inform you secure credential to scp ssh connection.
Note that you still need to write the username on the command:
Final considerations
The SCP command in Linux is one of the most efficient and secure methods for transferring files between local and remote computers connected over a network. Whether you need to SCP from local to remote or perform SSH file copy operations, this guide has you covered.
Always remember to verify your SCP operations to ensure the correct files have been transferred.