Как передать файлы с windows на linux через putty

Как копировать и передавать файлы по SSH

В статье мы расскажем, как передать файлы через SSH на разных операционных системах — Windows и Linux.

  1. Что нужно для подключения
  2. Как скопировать файл через SSH на Linux
    • Как отправить файл по SSH с локального компьютера на сервер
    • Как скачать файлы с удаленного сервера на компьютер
  3. Как скопировать файлы по SSH на Windows
    • Как загрузить файл с компьютера на сервер
    • Как скачать файл через SSH на локальный компьютер

Для подключения к серверу вам потребуются:

  • IP-адрес или имя сервера,
  • логин пользователя (в том числе root),
  • пароль пользователя,
  • порт.

Чаще всего копирование файлов через SSH делают с помощью двух мини-программ:

  1. scp (Secure Copy) — утилита для Linux. Она позволяет безопасно передать или скачать файл по протоколу SSH. Программа scp входит в комплект OpenSSH и не требует установки.
  2. pscp.exe — это утилита для Windows. Она используется по тому же назначению, что и scp: подключение к серверу по SSH и работа с файлами. Эта мини-программа входит в состав PuTTY: ее можно скачать на официальном сайте. Процедура настройки SSH-клиента описана в нашей статье.

Важно: если загружаемый файл существует на целевом хосте, он перезапишется.

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

Как скопировать файл через SSH на Linux

Копирование файлов по SSH на Linux можно сделать с помощью scp. Эта утилита позволяет:

  • передать файл с локального компьютера на удаленный сервер,
  • скачать файл с удаленного сервера на локальный компьютер.

Команда scp имеет следующий синтаксис:

scp опция источник получатель

Как отправить файл по SSH с локального компьютера на сервер

Чтобы загрузить файл:

  1. Подключитесь к серверу по SSH.
  2. Выполните команду:

scp /home/test.doc username@servername:/directory

Где:

  • /home/test.doc — путь к файлу на локальном компьютере;
  • username — имя SSH-пользователя;
  • servername — имя сервера или его IP-адрес;
  • directory — директория на сервере, в которую нужно загрузить файл.

Готово, вы загрузили файл на сервер.

Как скачать файлы с удаленного сервера на компьютер

Чтобы загрузить файл:

  1. Подключитесь к серверу по SSH.
  2. Выполните команду:

scp username@servername:/directory/test.doc /home

Где:

  • /directory/test.doc — путь к файлу на сервере;
  • username — имя SSH-пользователя;
  • servername — имя сервера или его IP-адрес;
  • home — папка на компьютере, в которую нужно загрузить файл.

Готово, вы скачали файл на компьютер.

Как скопировать файлы по SSH на Windows

Копирование через SSH на ОС Windows выполняется с помощью утилиты pscp.exe из набора PuTTY.

Как загрузить файл с компьютера на сервер

Чтобы загрузить файл:

  1. Подключитесь к серверу по SSH.
  2. Выполните команду:

pscp C:/documents/test.doc username@servername:/directory

Где:

  • /documents/test.doc — путь к файлу на локальном компьютере;
  • username — имя SSH-пользователя;
  • servername — имя сервера или его IP-адрес;
  • directory — директория на сервере, в которую нужно загрузить файл.

Если название файла или путь содержит пробелы, заключите его в кавычки:

pscp “C:/documents/test 1.doc” username@servername:/directory

Готово, вы загрузили файл на сервер.

Как скачать файл через SSH на локальный компьютер

Чтобы загрузить файл:

  1. Подключитесь к серверу по SSH.
  2. Выполните команду:

pscp username@servername:/directory/test.doc C:/documents

Где:

  • username — имя SSH-пользователя;
  • servername — имя сервера или его IP-адрес;
  • directory/test.doc — путь к файлу на сервере;
  • /documents — директория на локальном компьютере, в которую нужно загрузить файл.

Если название файла или путь содержит пробелы, заключите его в кавычки:

pscp username@servername:”/directory/test 1.doc” C:/documents

Готово, вы скачали файл на компьютер.

В операционных системах семейства Linux для удаленного доступа между машинами широко используется протокол SSH. Его популярность обусловлена простотой, надежностью и безопасностью соединения. Подключившись по SSH к удаленному компьютеру, вы получаете возможность выполнять на нем любые команды терминала, как будто вы работате на своем компьютере, работает даже автодополение и другие вспомогательные возможности.

Иногда возникает необходимость подключиться к удаленному компьютеру Linux из Windows, но по умолчанию, там нет утилиты предназначенной для этого. Есть сторонняя программа, она называется PuTTY и вы можете установить ее отдельно. В этой статье мы рассмотрим как пользоваться PuTTY для подключения к Linux системам, а также поговорим как выполняется настройка PuTTY для удобного использования.

Содержание статьи

  • Установка PuTTY
  • Как пользоваться PuTTY

  • Выводы

Сначала нужно скачать установщик программы. Для этого откройте официальный сайт и нажмите «You can download PuTTY here»:

Затем выберите установщик для вашей архитектуры, x86 или x64 и загрузите его.

На первом шаге нажмите «Next»:

Папку для установки можно оставить по умолчанию:

Компоненты тоже:

Дождитесь завершения установки:

Снимите галочку с «View README» и нажмите «Finish»:

Теперь перейдем к тому как выполняется работа в PuTTY.

Как пользоваться PuTTY

1. Интерфейс программы

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

Рассмотрим за что отвечают те или иные вкладки программы, чтобы вы ориентировались что и где искать. У нас есть четыре вкладки:

  • Session — отвечает за подключение удаленному серверу, тут мы вводим параметры подключения, порт, адрес, а также можем сохранить все настройки putty, чтобы не настраивать каждый раз заново.
  • Terminal — позволяет включать или отключать возможности терминала;
  • Window — настройка внешнего вида окна, цвет, шрифт, кодировка;
  • Connection — настройка параметров подключения, алгоритма шифрования, сжатия, ключей аутентификации, X11 и других параметров.

Каждая вкладка имеет несколько подразделов, но мы не будем сейчас их трогать, а перейдем сразу к практике и посмотрим как подключиться putty к удаленному узлу.

2. Подключение к удаленному компьютеру PuTTY

Чтобы подключиться к удаленному компьютеру по SSH перейдите на вкладку «Session», здесь, в поле «Host Name» необходимо прописать ip адрес или имя хоста, компьютера, к которому вы хотите подключиться, в поле порт — нужно указать порт, на котором запущен SSH сервер, по умолчанию используется порт 22:

Далее, нажмите кнопку «Open». После этого появится запрос на добавление ключа сервера в список доверенных ключей, нажмите «Да»:

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

Теперь авторизация прошла успешно, и вы можете выполнять нужные действия на сервере:

3. Сохранение сессии PuTTY

Чтобы не вводить каждый раз ip и порт можно сохранить эти данные в виде сессии, для этого пропишите новое имя в поле «Saved Sessions», а затем нажмите кнопку «Save»:

Теперь вы сможете загрузить сохраненную сессию, нажав кнопку «Load».

После того как будет завершена настройка putty и все параметры будут выставлены правильно вы можете сохранить настройки и не вводить их несколько раз.

4. Имя пользователя по умолчанию

Вы можете не вводить имя пользователя каждый раз, для этого перейдите на влкадку «Connection», затем «Data» и в поле «Auto-login Username» пропишите имя пользователя, например, root:

Теперь подключение putty будет выполняться от имени этого пользователя.

5. Авторизация по ключу ssh в PuTTY

Чтобы не вводить каждый раз пароль можно настроить авторизацию по ключу. В Linux такая возможность используется очень широко потому что это удобно. Первым делом необходимо создать ключ. Для этого запустите утилиту PuTTYgen и установите переключатель в положение «SSH-2 RSA» нажмите «Generate»:

Обязательно ключ должен быть SSH-2 RSA, если в главном окне нет, выберите в меню «Key». Подвигайте мышкой, чтобы создать достаточное количество энтропии:

Ключ готов, затем, с помощью кнопок «Save Public Key» и «Save Private Key» сохраните оба ключа.

Далее, откройте PuTTY, перейдите на вкладку «Connection», затем «SSH», затем «Auth»:

Здесь необходимо нажать кнопку «Browse» и добавить недавно сохраненный приватный ключ:

Далее, возвращаемся на вкладку «Session», выбираем наше сохранение и нажимаем «Save» чтобы сохранить настройки. Осталось только отправить наш открытый ключ на сервер. Для этого авторизуйтесь на нем с помощью пароля и открытый ключ вставьте ключ в конец файла /root/.ssh/authorized_keys.

Ключ можно брать прямо из окна PuTTYgen «Public key for pasting» или из файла открытого ключа:

Все, теперь можно выходить и авторизоваться снова. На этот раз подключение по ssh putty будет выполняться с помощью нашего ключа. Не забывайте сохранять настройки сессии, чтобы не выбирать ключ каждый раз. Теперь вы знаете как пользоваться программой putty, рассмотрим еще передачу файлов.

5. Передача файлов через scp в PuTTY

Не все знают, но PuTTY позволяет передавать файлы через ssh также как это делает linux с помощью утилиты scp. Нажмите Win+R, затем пропишите cmd, чтобы запустить командную строку.

Синтаксис утилиты pcsp выглядит следующим образом:

pscp опции путь_файлу имя_пользователя@хост:/путь/к/файлу/на/удаленном/хосте

Например, мы можем отправить файл из текущей папки в папку пользователя /root/:

pscp test.txt root@185.22.173.108:/root/

С помощью опции -P можно задать удаленный порт:

pscp -P 2250 test.txt root@185.22.173.108:/root/

А опция load позволяет загрузить сохраенные настройки сессии PuTTY:

pscp -load losst-2 test.txt root@185.22.173.108:/root/

Теперь вы знаете как использовать putty для передачи файлов.

Выводы

В этой статье мы рассмотрели как пользоваться PuTTY для решения задач администрирования Linux в Windows. Иногда случаются ситуации, что без ssh в windows никуда, тогда эта утилита будет просто незаменимой.

During my daily working, I do the development on Windows OS; besides, we have a
Debian server for running different jobs automatically, file storage, etc.
Sometimes, we also need to transfer files from Windows OS to Linux OS, or
reverse; in this case, we use Putty to realize the transfering. Today, I will
talk about how to use Putty for transfer files with the following points:

  • What is Putty ?
  • Requirements
  • Transfering files from Windows to Linux
  • Transfering files from Linux to Windows

What is Putty ?

PuTTY is a free and open-source terminal emulator, serial console and
network file transfer application. It supports several network protocols,
including SCP, SSH, Telnet, rlogin, and raw socket connection. It can also
connect to a serial port. The name “PuTTY” has no official meaning.

Requirements

  • Windows OS
  • Linux OS
  • Putty installed: download Putty here
  • Putty PSCP installed: download Putty PSCP here

Transfering files from Windows to Linux

To transfer files from Windows OS to Linux OS, we will apply PSCP. Before we
start, let’s have a general understanding of it. PSCP means “PuTTy Secure
Copy Protocol (PSCP)”, is a tool for transferring files securely between
computers using an SSH connection. To use this utility, we should be
comfortable working in the Windows Command Prompt.

Now, let’s start to transfer files to Linux:

  • Open Windows Command Prompt.
  • Type pscp source_path user_name@host:target_path at the prompt
pscp weekly_report.xlsx xxx@123.456.789.0:reporting

Wins to Linux 1

Here, ./weekly_report.xlsx specifies the path of source file, xxx is user’s
account for accessing the Linux server, 123.456.789.0 is the host address,
/reporting presents target path.

  • After the bash script above, we also need to type the password for accessing
    the Linux server.

Wins to Linux 2

Transfering files from Linux to Windows

Transfering files from Linux OS to Windows OS is similar to the steps above:

  • Open Windows Command Prompt.
  • Type pscp user_name@host:source_path target_path at the prompt
pscp xxx@123.456.789.0:reporting/weekly_report.xlsx ./

Linux to Wins 1

  • Same as above, after the bash script above, we also need to type the password
    for accessing the Linux server.

Linux to Wins 2

Conclusion

In this blog, I introduced how to use Putty to transfer files from Windows OS
to Linux OS and reverse. Hope it’s useful for you.

Reference

  • “PuTTY”, wikipedia. [Online]. Available: https://en.wikipedia.org/wiki/PuTTY
  • “Transfer Files Using PuTTY”, it.cornell.edu. [Online]. Available: https://it.cornell.edu/managed-servers/transfer-files-using-putty
  • Comfreak, “traffic information superhighway”, pixabay.com. [Online]. Available: https://pixabay.com/photos/traffic-information-superhighway-3524185/

предыдущая глава | содержание | следующая глава

  • 5.1 Starting PSCP
  • 5.2 PSCP Usage
    • 5.2.1 The basics
    • 5.2.2 Options
    • 5.2.3 Return value
    • 5.2.4 Using public key authentication with PSCP

PSCP, the PuTTY Secure Copy client, is a tool for transferring files securely between computers using an SSH connection.

If you have an SSH-2 server, you might prefer PSFTP (see глава 6) for interactive use. PSFTP does not in general work with SSH-1 servers, however.

5.1 Starting PSCP

PSCP is a command line application. This means that you cannot just double-click on its icon to run it and instead you have to bring up a console window. With Windows 95, 98, and ME, this is called an «MS-DOS Prompt» and with Windows NT, 2000, and XP, it is called a «Command Prompt». It should be available from the Programs section of your Start Menu.

To start PSCP it will need either to be on your PATH or in your current directory. To add the directory containing PSCP to your PATH environment variable, type into the console window:

set PATH=C:\path\to\putty\directory;%PATH%

This will only work for the lifetime of that particular console window. To set your PATH more permanently on Windows NT, 2000, and XP, use the Environment tab of the System Control Panel. On Windows 95, 98, and ME, you will need to edit your AUTOEXEC.BAT to include a set command like the one above.

5.2 PSCP Usage

Once you’ve got a console window to type into, you can just type pscp on its own to bring up a usage message. This tells you the version of PSCP you’re using, and gives you a brief summary of how to use PSCP:

C:\>pscp
PuTTY Secure Copy client
Release 0.82
Usage: pscp [options] [user@]host:source target
       pscp [options] source [source...] [user@]host:target
       pscp [options] -ls [user@]host:filespec
Options:
  -V        print version information and exit
  -pgpfp    print PGP key fingerprints and exit
  -p        preserve file attributes
  -q        quiet, don't show statistics
  -r        copy directories recursively
  -v        show verbose messages
  -load sessname  Load settings from saved session
  -P port   connect to specified port
  -l user   connect with specified username
  -pwfile file   login with password read from specified file
  -1 -2     force use of particular SSH protocol version
  -ssh -ssh-connection
            force use of particular SSH protocol variant
  -4 -6     force use of IPv4 or IPv6
  -C        enable compression
  -i key    private key file for user authentication
  -noagent  disable use of Pageant
  -agent    enable use of Pageant
  -no-trivial-auth
            disconnect if SSH authentication succeeds trivially
  -hostkey keyid
            manually specify a host key (may be repeated)
  -batch    disable all interactive prompts
  -no-sanitise-stderr  don't strip control chars from standard error
  -proxycmd command
            use 'command' as local proxy
  -unsafe   allow server-side wildcards (DANGEROUS)
  -sftp     force use of SFTP protocol
  -scp      force use of SCP protocol
  -sshlog file
  -sshrawlog file
            log protocol details to a file
  -logoverwrite
  -logappend
            control what happens when a log file already exists

(PSCP’s interface is much like the Unix scp command, if you’re familiar with that.)

5.2.1 The basics

To receive (a) file(s) from a remote server:

pscp [options] [user@]host:source target

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp fred@example.com:/etc/hosts c:\temp\example-hosts.txt

To send (a) file(s) to a remote server:

pscp [options] source [source...] [user@]host:target

So to copy the local file c:\documents\foo.txt to the server example.com as user fred to the file /tmp/foo you would type:

pscp c:\documents\foo.txt fred@example.com:/tmp/foo

You can use wildcards to transfer multiple files in either direction, like this:

pscp c:\documents\*.doc fred@example.com:docfiles
pscp fred@example.com:source/*.c c:\source

However, in the second case (using a wildcard for multiple remote files) you may see a warning saying something like «warning: remote host tried to write to a file called «terminal.c» when we requested a file called «*.c». If this is a wildcard, consider upgrading to SSH-2 or using the «-unsafe» option. Renaming of this file has been disallowed».

This is due to a fundamental insecurity in the old-style SCP protocol: the client sends the wildcard string (*.c) to the server, and the server sends back a sequence of file names that match the wildcard pattern. However, there is nothing to stop the server sending back a different pattern and writing over one of your other files: if you request *.c, the server might send back the file name AUTOEXEC.BAT and install a virus for you. Since the wildcard matching rules are decided by the server, the client cannot reliably verify that the filenames sent back match the pattern.

PSCP will attempt to use the newer SFTP protocol (part of SSH-2) where possible, which does not suffer from this security flaw. If you are talking to an SSH-2 server which supports SFTP, you will never see this warning. (You can force use of the SFTP protocol, if available, with -sftp — see section 5.2.2.6.)

If you really need to use a server-side wildcard with an SSH-1 server, you can use the -unsafe command line option with PSCP:

pscp -unsafe fred@example.com:source/*.c c:\source

This will suppress the warning message and the file transfer will happen. However, you should be aware that by using this option you are giving the server the ability to write to any file in the target directory, so you should only use this option if you trust the server administrator not to be malicious (and not to let the server machine be cracked by malicious people). Alternatively, do any such download in a newly created empty directory. (Even in «unsafe» mode, PSCP will still protect you against the server trying to get out of that directory using pathnames including «..».)

5.2.1.1 user

The login name on the remote server. If this is omitted, and host is a PuTTY saved session, PSCP will use any username specified by that saved session. Otherwise, PSCP will attempt to use the local Windows username.

5.2.1.2 host

The name of the remote server, or the name of an existing PuTTY saved session. In the latter case, the session’s settings for hostname, port number, cipher type and username will be used.

5.2.1.3 source

One or more source files. Wildcards are allowed. The syntax of wildcards depends on the system to which they apply, so if you are copying from a Windows system to a UNIX system, you should use Windows wildcard syntax (e.g. *.*), but if you are copying from a UNIX system to a Windows system, you would use the wildcard syntax allowed by your UNIX shell (e.g. *).

If the source is a remote server and you do not specify a full pathname (in UNIX, a pathname beginning with a / (slash) character), what you specify as a source will be interpreted relative to your home directory on the remote server.

5.2.1.4 target

The filename or directory to put the file(s). When copying from a remote server to a local host, you may wish simply to place the file(s) in the current directory. To do this, you should specify a target of .. For example:

pscp fred@example.com:/home/tom/.emacs .

…would copy /home/tom/.emacs on the remote server to the current directory.

As with the source parameter, if the target is on a remote server and is not a full path name, it is interpreted relative to your home directory on the remote server.

5.2.2 Options

PSCP accepts all the general command line options supported by the PuTTY tools, except the ones which make no sense in a file transfer utility. See section 3.11.3 for a description of these options. (The ones not supported by PSCP are clearly marked.)

PSCP also supports some of its own options. The following sections describe PSCP’s specific command-line options.

5.2.2.1 -ls list remote files

If the -ls option is given, no files are transferred; instead, remote files are listed. Only a hostname specification and optional remote file specification need be given. For example:

pscp -ls fred@example.com:dir1

The SCP protocol does not contain within itself a means of listing files. If SCP is in use, this option therefore assumes that the server responds appropriately to the command ls -la; this may not work with all servers.

If SFTP is in use, this option should work with all servers.

5.2.2.2 -p preserve file attributes

By default, files copied with PSCP are timestamped with the date and time they were copied. The -p option preserves the original timestamp on copied files.

5.2.2.3 -q quiet, don’t show statistics

By default, PSCP displays a meter displaying the progress of the current transfer:

mibs.tar          |   168 kB |  84.0 kB/s | ETA: 00:00:13 |  13%

The fields in this display are (from left to right), filename, size (in kilobytes) of file transferred so far, estimate of how fast the file is being transferred (in kilobytes per second), estimated time that the transfer will be complete, and percentage of the file so far transferred. The -q option to PSCP suppresses the printing of these statistics.

5.2.2.4 -r copies directories recursively

By default, PSCP will only copy files. Any directories you specify to copy will be skipped, as will their contents. The -r option tells PSCP to descend into any directories you specify, and to copy them and their contents. This allows you to use PSCP to transfer whole directory structures between machines.

5.2.2.5 -batch avoid interactive prompts

If you use the -batch option, PSCP will never give an interactive prompt while establishing the connection. If the server’s host key is invalid, for example (see section 2.2), then the connection will simply be abandoned instead of asking you what to do next.

This may help PSCP’s behaviour when it is used in automated scripts: using -batch, if something goes wrong at connection time, the batch job will fail rather than hang.

5.2.2.6 -sftp, -scp force use of particular file transfer protocol

As mentioned in section 5.2.1, there are two different file transfer protocols in use with SSH. Despite its name, PSCP (like many other ostensible scp clients) can use either of these protocols.

The older SCP protocol does not have a written specification and leaves a lot of detail to the server platform. Wildcards are expanded on the server. The simple design means that any wildcard specification supported by the server platform (such as brace expansion) can be used, but also leads to interoperability issues such as with filename quoting (for instance, where filenames contain spaces), and also the security issue described in section 5.2.1.

The newer SFTP protocol, which is usually associated with SSH-2 servers, is specified in a more platform independent way, and leaves issues such as wildcard syntax up to the client. (PuTTY’s SFTP wildcard syntax is described in section 6.2.2.) This makes it more consistent across platforms, more suitable for scripting and automation, and avoids security issues with wildcard matching.

Normally PSCP will attempt to use the SFTP protocol, and only fall back to the SCP protocol if SFTP is not available on the server.

The -scp option forces PSCP to use the SCP protocol or quit.

The -sftp option forces PSCP to use the SFTP protocol or quit. When this option is specified, PSCP looks harder for an SFTP server, which may allow use of SFTP with SSH-1 depending on server setup.

5.2.2.7 -no-sanitise-stderr: control error message sanitisation

The -no-sanitise-stderr option will cause PSCP to pass through the server’s standard-error stream literally, without stripping control characters from it first. This might be useful if the server were sending coloured error messages, but it also gives the server the ability to have unexpected effects on your terminal display. For more discussion, see section 7.2.3.5.

5.2.3 Return value

PSCP returns an ERRORLEVEL of zero (success) only if the files were correctly transferred. You can test for this in a batch file, using code such as this:

pscp file*.* user@hostname:
if errorlevel 1 echo There was an error

5.2.4 Using public key authentication with PSCP

Like PuTTY, PSCP can authenticate using a public key instead of a password. There are three ways you can do this.

Firstly, PSCP can use PuTTY saved sessions in place of hostnames (see section 5.2.1.2). So you would do this:

  • Run PuTTY, and create a PuTTY saved session (see section 4.1.2) which specifies your private key file (see section 4.22.1). You will probably also want to specify a username to log in as (see section 4.15.1).
  • In PSCP, you can now use the name of the session instead of a hostname: type pscp sessionname:file localfile, where sessionname is replaced by the name of your saved session.

Secondly, you can supply the name of a private key file on the command line, with the -i option. See section 3.11.3.18 for more information.

Thirdly, PSCP will attempt to authenticate using Pageant if Pageant is running (see глава 9). So you would do this:

  • Ensure Pageant is running, and has your private key stored in it.
  • Specify a user and host name to PSCP as normal. PSCP will automatically detect Pageant and try to use the keys within it.

For more general information on public-key authentication, see глава 8.

Протокол SSH (Secure Shell) — это сетевой протокол для удаленного управления операционной системой через командную строку, который можно назвать стандартом для удаленного доступа к *nix-машинам. Позволяет производить защищенный вход на сервер, удаленно выполнять команды, управлять файлами (создавать, удалять, копировать и т.д.) и многое другое. Большинство облачных и хостинг-провайдеров требуют наличие SSH для доступа к своим сервисам. В этой статье рассмотрим копирование файлов по SSH в Windows и Linux-системах.

Копирование Файлов По Ssh (1)

SSH способен передавать любые данные (звук, видео, данные прикладных протоколов) через безопасный канал связи. В отличие от устаревших и небезопасных протоколов telnet и rlogin, в SSH обеспечивается конфиденциальность передаваемых данных и подлинность взаимодействующих сторон — необходимые условия для сетевого взаимодействия в Интернете.

Рассмотрим алгоритм установки зашифрованного соединения между клиентом и сервером:

  1. Установка TCP-соединения. По умолчанию сервер слушает 22-й порт. В работе протокола используется набор алгоритмов (сжатие, шифрование, обмен ключами), поэтому стороны обмениваются списком поддерживаемых алгоритмов и договариваются, какие из них будут использовать.
  2. Чтобы третья сторона не смогла выдать себя за сервер или клиент, стороны должны удостоверится в подлинности друг друга (аутентификация). Для этого используются асимметричные алгоритмы шифрования и пара открытый-закрытый ключ. Вначале проверяется аутентичность сервера. Если соединение происходит впервые, пользователь увидит предупреждение и информацию о сервере. Список доверенных серверов и их ключей записывается в файл по адресу /home/<username>/.ssh/known_hosts.
  3. Как только клиент убедился в достоверности сервера, стороны генерируют симметричный ключ, с помощью которого происходит шифрования всех обмениваемых данных. Таким образом при перехвате данных, никто, кроме сторон не сможет узнать содержимое сообщений.
  4. Далее происходит аутентификация пользовательского сеанса. Для этого используется либо пароль, либо присланный клиентом публичный ключ, сохраняемый в файле /home/<username>/.ssh/authorized_keys на сервере.

Самая популярная реализация на Линукс, OpenSSH, предустанавливается практически на всех дистрибутивах: Ubuntu, Debian, RHEL-based и других. На Windows в качестве клиентов можно использовать программы PuTTY, MobaXterm. Начиная с WIndows 10 и Windows Server 2019 инструменты OpenSSH доступны и на Windows.

Подробнее об SSH и работе с ним мы писали в статье «Как пользоваться SSH».

VDS

Копирование файлов

Копирование файлов в Linux по SSH осуществляется с помощью двух основных программ: scp и sftp. Обе утилиты поставляются вместе с пакетом OpenSSH. Суще­ствуют две основные версии протокола SSH: 1 и 2. Оболочка OpenSSH поддержи­вает обе версии, однако первая применяется редко.

Настройка автодополнений

При работе с scp крайне удобно использовать tab для автодополнения путей на удаленной машине. Для этого нужно настроить аутентификацию пользователя по публичному ключу.

Для начала сгенерируем открытый и закрытый ключ:

ssh-keygen

Вывод:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Created directory '/home/user/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:wJQ/XBZq69qXGHxseTuccUEpzWYHhsVVHcDXE3MrTHQ user@host

В конце вывода будет графическое представление ключа (key’s randomart image), которое легче запомнить, чем хэш ключа.

По умолчанию ключи (id_rsa.pub — открытый, id_rsa — закрытый) сохранятся в домашнем каталоге пользователя в директории .ssh. Также во время генерации программа попросит ввести пароль, которым будут защищены ключи. Если не хотите дополнительной защиты, нажмите два раза Enter.

Теперь копируем публичный ключ на удаленную машину:

ssh-copy-id [имя пользователя]@[ip-адрес]

Здесь [имя пользователя] — учетная запись пользователя, под которой будем логиниться на удаленной машине, [ip-адрес] — адрес удаленной машины (можно использовать доменное имя, если они локально резолвится). Далее вводим пароль пользователя. Если все прошло корректно, то в выводе будет команда для удаленного подключения:

Number of key(s) added: 1
Now try logging into the machine, with:   "ssh '<имя пользователя>@<ip-адрес>'"
and check to make sure that only the key(s) you wanted were added.

Secure copy (SCP)

Для копирования небольших объемов информации (например, конфиги сервисов) лучше всего подойдет утилита scp. 

Синтаксис команды для копирования с локальной машины на удаленный сервер:

scp [путь к файлу] [путь к файлу] [имя пользователя]@[ip-адрес]:[путь к файлу]

Попробуем скопировать файл на сервер:

scp test.txt user@192.168.1.29:/home/user/

Вывод:

test.txt                              100%   12   20.6KB/s   00:00

Можно передать несколько файлов за раз. Для этого указываем пути, разделенные пробелами:

scp test1.txt test2.txt user@192.168.1.29:/home/user/

Для копирования с удаленного сервера на локальную машину нужно поменять источник и место назначения местами:

scp user@192.168.1.29:/home/user/test.txt ~/

Для передачи директории используйте ключ -r:

scp -r testdir user@192.168.1.29:/home/user/

Также имеется возможность передачи с одного удаленного сервера на другой:

scp gendo@192.168.1.25:/home/gendo/test.txt user@192.168.1.29:/home/user/

Secure FTP (SFTP)

Еще одной утилитой для передачи файлов, поставляемых в OpenSSH, является sftp. C релизом OpenSSH 9.0 утилита scp переведена по умолчанию на использование SFTP вместо устаревшего протокола SCP/RCP. Sftp работает практически также, как и классический ftp, за исключением того, что в sftp данные передаются не в виде обычного текста, а по зашифрованному туннелю (туннелирование — это процесс упаковки и передачи одного сетевого подключения с помощью другого). Также для работы sftp не нужен отдельный FTP-сервер.

Пример простого скачивания через sftp:

gendo@melhior:~$ sftp misato@192.168.1.29
Connected to 192.168.1.29.
sftp> ls
file.txt   file1.txt  file2.txt  test.txt  
sftp> lcd testdir/
sftp> get test.txt
Fetching /home/misato/test.txt to test.txt
test.txt                              100%  12  4.8KB/s  00:00    
sftp> bye

Сам по себе sftp применяется редко: вместо этого его используют файловые менеджеры, например Midnight Commander и Nautilus:

Image1

Использование sftp в файловом менеджере Nautilus. Удаленная машина отображается в виде папки с именем пользователя и IP-адресом.

Копирование файлов по SSH в Windows

Скачать файл с сервера или на сервер в Windows можно с помощью консольной программы pscp, поставляемой вместе с PuTTY. Синтаксис очень похож на обычный scp:

pscp [путь к файлу] [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу]

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

pscp C:\server\test.txt misato@192.168.1.29:/home/misato/

Скачивание файла с сервера на компьютер:

pscp misato@192.168.1.29:/home/misato/test.txt C:\file.txt

Увидеть список файлов на сервере можно при помощи опции -ls:

pscp -ls [имя пользователя]@[ip-адрес]:[путь]

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

pscp "C:\dir\bad file name" misato@192.168.1.29:/home/misato

Для получения помощи по команде введите pscp без аргументов.

Заключение

Мы рассмотрели, как копировать файлы на сервер и с сервера с помощью безопасного сетевого протокола SSH. Если вы используете облачные серверы, важно уметь работать с SSH, так как он является стандартом для удаленного доступа к *nix-машинам и будет необходим вам в повседневной работе. 

Кстати, в официальном канале Timeweb Cloud собрали комьюнити из специалистов, которые говорят про IT-тренды, делятся полезными инструкциями и даже приглашают к себе работать. 

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Hp deskjet d1663 драйвер windows 10
  • Что будет если удалить onedrive в windows 11
  • Лучшие программы для работы с pdf файлами для windows 10
  • Как редактировать системные файлы windows 10
  • Передача изображения с компьютера на телевизор по wifi windows 10