Linux copy files over ssh

10 Examples: Copying Files over SSH

SCP (Secure CoPy) – is a remote file copy program, that copies files between hosts on a network.

It uses SSH for data transfer, and uses the same authentication and provides the same security as SSH.

When copying a source file to a target file which already exists, SCP will replace the contents of the target file. If the target file does not yet exist, an empty file with the target file name is created, then filled with the source file contents.

Example 1: Copy the file “file.txt” from a remote host to the local host.

Example 2: Copy the file “file.txt” from the local host to a remote host.

Example 3: Copy the directory “dir1” from the local host to a remote host’s directory “dir2”.

Example 4: Copy the file “file.txt” from remote host “remote.host1” to remote host “remote.host2”.

Example 5: Copy the files “file1.txt” and “file2.txt” from the local host to your home directory on the remote host.

Example 6: Copy the file “file.txt” from the local host to a remote host using port 2222.

Example 7: Copy the file “file.txt” from the local host to a remote host’s home directory. Preserve the modification and access times, as well as the permissions of the source-file in the destination-file.

Example 8: Copy the file “file.txt” from the local host to a remote host’s home directory. Increase SCP speed by changing the cipher from the default AES-128 to Blowfish.

Example 9: Copy the file “file.txt” from the local host to a remote host’s home directory. limit the bandwidth used by SCP command to 100 Kbit/s.

Example 10: Copy multiple files from the remote host to your current directory on the local host.

Источник

How to copy file remotely via SSH

SSH or Secure Shell is a protocol that allows secure access to remote computers. SSH implementation also comes with scp utility for remote file transfer that uses SSH protocol. Other applications such as sftp and rsync also utilize SSH for file transfer to secure their network transaction.

These applications allow us to copy our files from local to remote servers and copy files from remote servers to our local machine. Below are examples of how to use these applications for files transfers based on this setup:

Make sure you have access right to the remote server and correct permission to the remote files and folders

Methods for remote file transfer using SSH:

Transfer file using scp

The easiest of these are scp or secure copy. While cp is for copying local files, scp is for remote file transfer where both use almost the same syntax. The main difference is that with scp, you’ll have to specify the remote host’s DNS name or IP address and provide a login credential for the command to work. You can both scp files from local to remote and local to remote.

If the target folder (/remote/folder/) is not specified, it will copy the file to the remote user’s home directory.

Читайте также:  Сброс пароля администратора домена windows server 2016

Using . as the copy target (replacing localfile.txt will copy the remote file to the current working directory using the same filename (remotefile.txt)

remoteuser need to exist and have write permission to /remote/folder/ in the remote system.

GUI programs such WinSCP can also be used to transfer files between local and remote host using scp methods.

Transfer file using sftp

Related: WinSCP can also be used to for file transfer usiing SFTP. The other popular tool is FileZilla.

Transfer file using rsync

You can also use ssh to secure your rsync session. To do this, use —rsh=ssh or -e “ssh” with your normal rsync commands. The following 2 commands will work exactly the same;

If these options are not specified, rsync will first try to connect to rsyncd but will automatically fallback to SSH if rsyncd is not running in the remote system.

Mount remote filesystem locally

Remote filesystems could be mounted to the local host and accessed as a local filesystem. Mounting remote filesystem requires SSH access to the remote host and with the use of sshfs.

Comment anonymously. Login not required.

Источник

4 Ways to Transfer Files Between Remote and Local Systems Over SSH

Sooner or later, you’ll find yourself in a situation where you have to upload the file to the remote server over SSH or copy a file from it.

There are various ways you can transfer files over SSH. I am going to discuss the following methods here:

  1. scp: Legacy command which is being deprecated
  2. rsync: Popular command for file synchronization
  3. sshfs: Mounting remote directory over SSH
  4. sftp clients: GUI tool for accessing file over SFTP

For a successful file transfer over SSH, you need to

  • to have SSH access between the two machines
  • to know the username and password on the remote machine
  • IP address or hostname (on the same subnet) of the remote machine

With that aside, let’s see the methods for copying files between remote systems via SSH.

Method 1: Use scp command to copy files over SSH

I have read that scp is going to be deprecated. Still, it is my favorite tool for transferring files between systems over SSH. Why? Because its syntax is similar to the cp command.

Let’s see how to use the scp command.

Copy files from the remote machine to your local machine

Here’s the scenario. You want to copy files from the remote Linux system to the currently logged in system.

Here’s a generic syntax that copies the file from the home directory of the user on the remote system to the current directory of your locally logged in system.

Do you see the similarity with the cp command? It’s almost the same except that you have to specify username and ip address with colon (:).

Now, let me show you a real-world example of this command.

In the example above, I copied the file remote.txt from the /home/abhishek/my_file directory on the remote system to the current directory of the local machine.

This should give you a hint that you should know the exact location of the file on the remote system. The tab completion does not work on remote systems.

Copy files from your local machine to the remote machine

The scenario is slightly changed here. In this one, you are sending a local file to the remote system over SSH using scp.

This is a generic syntax which will copy the filename to the home directory of username on the remote system.

In the above example, I copied local.txt file from the current directory to the home directory of the user abhishek on the remote system.

Then I logged into the remote system to show that the file has actually been copied.

You can copy directories too

Remember I told you I like scp because of its similarity with the cp command?

Like cp command, you can also use scp to copy directory over SSH. The syntax is similar to the cp command too. You just have to use the -r option.

Читайте также:  Создать загрузочную флешку с linux диска

You can do a lot more with it. Read some more examples of scp command in this tutorial:

Method 2: Use rsync to copy files and directories over SSH

Since scp is being deprecated, rsync is the next best tool for copying files between remote system over SSH. Actually, it is better than scp in many terms.

The command syntax is the same as scp. Older versions of rsync had to use rsync -e ssh but that’s not the case anymore.

Copy files from the remote machine to your local machine

Let’s say you want to copy a file from the home directory of the user on the remote system to the current directory of your locally logged in system.

Let’s take the same example you saw with scp. I am copying the file remote.txt from the /home/abhishek/my_file directory on the remote system to the current directory of the local machine.

Copy files from your local machine to the remote machine

Here is a generic syntax which will copy the file to the home directory of username on the remote system.

Time to see the real world example. I am copying local.txt file from the current directory to the home directory of the user abhishek on the remote system.

How about copying directories with rsync?

It’s the same. Just use -r option with rsync to copy entire directory over SSH between remote systems.

Take a look at this example. I copy the entire my_file directory from the remote system to the local system.

rsync is a versatile tool. It is essentially a tool for ‘recursively syncing’ the contents between two directories and quite popular for making automated backups.

Method 3: Using SSHFS to access files from remote system over SSH

There is also SSHFS (SSH Filesystem) that can be used to access remote files and directories. However, this is not very convenient just for copying files.

In this method, you mount the remote directory on your local system. Once mounted, you can copy files between the mounted directory and the local system.

You may need to install sshfs on your local system first using your distribution’s package manager.

On Debian and Ubuntu, you may use the following command:

Once you have sshfs installed on your system, you can use it to mount the remote directory. It would be better to create a dedicated directory for the mount point.

Now mount the desired directory on the remote machine in this fashion:

Once it is mounted, you can copy files into this directory or from this directory as if it is on your local machine itself.

Remember that you have mounted this file. Once your work is done, you should also unmount it:

Here’s an example where I mounted the my_file directory from the remote system to the remote_dir directory on the local system. I copied the remote.txt file to the local system and then unmounted the directory.

Method 4: Use a GUI-based SFTP client for transferring files between remote systems

As the last resort, you can use an FTP client for transferring files between remote and local systems.

FileZilla is one of the most popular cross-platform FTP client. You can easily install on your local system.

Once installed, go to File->Site Manager and add the remote system details like IP address, SSH port number, username and password.

Once you connect, you can see a split window view that shows the local filesystem on the left and the remote filesystem on the right.

To transfer the file, drag and drop files from left to right or right to left. A progress bar appears at the bottom.

Which method do you prefer?

Alright! I showed various command line and GUI methods that can be used for copying files over SSH.

Now it is up to you to decide which method to use here. Do comment your preferred method for transferring files over SSH.

Читайте также:  Образы для службу развертывания windows

Источник

Копирование файлов и запуск команд через SSH

Подключение к серверу посредством SSH – один из основных методов управления *nix серверами. Довольно часто возникает необходимость загрузить файл на удаленный сервер, либо выгрузить, и других средств кроме SSH-подключения нет. К счастью, копирование файлов через защищенное соединение – одна из штатных функций этого протокола и реализуется с помощь отдельной команды scp в Linux-системах, либо с помощью pscp.exe, входящей в состав SSH-клиента Putty для операционной системы Windows.

Работаем на ОС семейства Linux

Используем следующий формат команд:

scp [модификатор] [источник] [место_назначения]

Если в качестве источника или места назначения указывается удаленный сервер, то формат параметра такой:

После запуска команды потребуется ввести пароль от указанной учетной записи удаленного сервера.

Если собрать все вместе, то скопировать локальный файл /home/user/file.tgz в домашний каталог пользователя root удаленного сервера 123.123.123.123 можно командой:

scp /home/user/file.tgz root@123.123.123.123:/root

Чтобы скачать этот же файл с удаленного сервера:

scp root@123.123.123.123:/root/file.tgz /home/user

За одну операцию можно скопировать несколько файлов, для этого необходимо указать их в качестве источника, разделив пробелом – местом назначения будет считаться последний указанный параметр. Например, загрузить файлы file1.tgz и file2.tgz из локального каталога на удаленный сервер позволит команда:

scp file1.tgz file2.tgz root@123.123.123.123:/root

Для копирования каталога потребуется задействовать модификатор команды r. Копируем локальный каталог /home/user/dir на удаленный сервер:

scp –r /home/user/dir root@123.123.123.123:/root

В тех случаях, когда SSH-сервер работает на нестандартном порту, поможет опция P. Если нужно подключиться через порт 10022:

scp –P 10022 /home/user/file.tgz root@123.123.123.123:/root

Чтобы узнать какие еще модификаторы поддерживает команда, можно просто запустить scp без параметров и прочитать краткую справку.

Работаем на ОС семейства Windows

При использовании операционной системы Windows и Putty в качестве клиента, формат команды остается тот же, меняется только название исполняемого файл и используется синтаксис указания путей к файлам и каталогам Windows при указании источника или места назначения. Запускаем командную строку (cmd.exe) или PowerShell, переходим в каталог, где расположен файл pscp.exe вводим команду:

pscp.exe C:Tempfile.tgz root@123.123.123.123:/root

В случае запуска из какой-либо другой папки понадобится указать полный путь к pscp.exe. Если в каком-либо из путей присутствуют пробелы, используются двойные кавычки — “Путь к файлу”:

“C:Program FilesPuttypscp.exe” C:Tempfile.tgz root@123.123.123.123:/root

Как и в случае с scp, запустив pscp.exe без параметров, можно увидеть краткую справку по синтаксису команды и перечень поддерживаемых модификаторов.

Запуск команд на удаленном сервере через SSH-подключение

Протокол SSH, помимо работы в интерактивном режиме, поддерживает также разовый запуск команд или скриптов на удаленном сервере.

Работаем на ОС семейства Linux

ssh [пользователь]@[сервер] ‘[команда]’

При запросе вводим пароль указанного пользователя и в консоли получаем вывод команды, если таковой имеется.

Например, получим информацию об установленной на удаленном сервере операционной системе:

ssh root@123.123.123.123 ‘uname -a’

Чтобы запустить несколько команд за одно подключение, можно использовать символ “;” в качестве разделителя. Проверим сетевые настройки и активные сетевые подключения на удаленном сервере:

ssh root@123.123.123.123 ‘ifconfig; netstat -anp tcp’

В случае, если потребуется запустить на удаленном сервере локальный файла сценария, потребуется в SSH-подключении вызвать командный интерпретатор в режиме исполнения сценария (например, bash с ключом -s), и на стандартный ввод передать ему файл сценария. Выглядеть эта конструкция будет так:

ssh root@123.123.123.123 ‘bash -s’

В результате локальный файл /home/user/myscript.sh исполнится на удаленном сервере.

Запуск команды SSH без параметров позволит ознакомиться с краткой справкой по синтаксису и списком дополнительных модификаторов, которые позволяют расширить функциональность команды.

Работаем на ОС семейства Windows

Если мы подключаемся к удаленному серверу с компьютера, работающего на операционной системе Windows, то нам снова потребуется обратиться к терминальному клиенту Putty, в состав которого входит исполняемый файл plink.exe. Работать с этим файлом необходимо из командной строки (cmd.exe) или из PowerShell.

Для запуска команды на удаленном сервере используется следующий синтаксис:

plink.exe [сервер] -ssh -l [пользователь] “[команда]”

Проверим конфигурацию сетевых интерфейсов:

plink.exe 123.123.123.123 -ssh -l root “ifconfig”

Как и при работе с командой SSH в Linux, plink.exe позволяет использовать “;” в качестве разделителя для запуска нескольких команд:

plink.exe 123.123.123.123 -ssh -l root “ifconfig; netstat -anp tcp”

А запуск команд из локального файла можно реализовать с помощью дополнительного ключа m:

Источник

Оцените статью