Pscp exe как пользоваться windows

Как копировать и передавать файлы по 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

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

Протокол 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-тренды, делятся полезными инструкциями и даже приглашают к себе работать. 

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

  • 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.

pscp / scp is the keyword when wanting to copy files from Windows to Linux and vice versa.

How to use

example

Linux to Windows
scp /home/ubuntu/myfile.txt username@IP_of_windows_machine:/C:/Users/Admin/Desktop

Windows to Linux

scp C:\Users\Admin\Desktop\myfile.txt username@IP_of_linux_machine:/home/ubuntu

Instead of ip the hostname can be used as well

PSCP

PSCP usually comes with the popular ssh client Putty and is used to copy files via the command line interface from one machine to another.

Quick example

Windows to Linux

pscp C:\Users\Name\Downloads\myfile.txt username_linux_machine@ip_of_linux_machine:/home/ubuntu

Linux to Windows

pscp username_linux_machine@ip_of_linux_machine:/home/ubuntu/myfile.txt C:\Users\Name\Downloads

Set up

1. Download pscp.exe [1]

Pscp-download

2. copy pscp.exe executable to system32 folder

copy the pscp.exe executable to the system32 directory of your windows machine. This folder normally exists in C:\Windows\System32 path.

Pscp exe system32

3. Verify with PowerShell

Open Windows PowerShell and use the following command to verify if pscp is accessible from the path.

You should see the following output.

Pscp-powershell-verification

4. Copy file

From Windows to Linux

Use the following format to copy the single file from Windows to the Linux box.

pscp -pw password C:\Users\Admin\Desktop\test.txt  \user@192.168.33.10:/home/JohnDoe
From Linux to Windows
pscp -pw password user@192.168.33.10:/path/to/file \C:\Users\Admin\Desktop\
Explanation of the command:
  1. -pw for the password.
  2. Replace password with the Linux user password.
  3. C:\Users\Admin\Desktop\test.txt represents the path of the file that has to be copied to the Linux system.
  4. 192.168.33.10 is the IP of the Linux server.
  5. /home/vagrant is the user-accessible path in the Linux system to copy the file.
Copy all files of a folder:

If you want to copy all the files in a directory to Linux, you need to add a star (*) to the folder. eg. folder\*

pscp -pw password C:\Users\Admin\Desktop\folder\*  \user@192.168.33.10:/home/JohnDoe

Иногда все мы сталкиваемся с ситуацией передачи файлов с сервера, на сервер. Легко, удобно и безопасно это делать через SSH.

Для Linux используется утилита scp (secure copy) входящая в состав OpenSSH, а для Windows аналогичная утилита pscp которая входит в состав пакета инструментов PuTTY.

Пример использования SCP на Linux

Общий синтаксис scp выглядит так:

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

Скачать файл с удаленного сервера на локальный:

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

Пример:

scp root@192.168.1.10:/root/file.tar.gz /opt

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

Скачать папку со всеми файлами и подпапками:

scp -r [источник] [получатель]

Пример:

scp –r /var/www root@192.168.1.10:/root

Загрузить файл на удаленный сервер:

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

Пример:

scp file.tar.gz root@192.168.1.10:/root

Пример использования PSCP на Windows

В общем и целом, синтаксис pscp не отличается от scp, но все равно рассмотрим как выполнить аналогичные операции с использованием pscp.

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

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

Пример:

pscp.exe root@192.168.1.10:/home/user/file.tar.gz .

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

Загрузить файл на удаленный сервер:

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

Пример:

pscp.exe file.tar.gz root@192.168.1.10:/root

 

ПОНРАВИЛАСЬ ИЛИ ОКАЗАЛАСЬ ПОЛЕЗНОЙ СТАТЬЯ, ПОДДЕРЖИ АВТОРА ДОНАТОМ

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Можно ли обновить windows 8 до windows 10 на ноутбуке
  • Windows 10 google chrome не устанавливается на windows
  • Календарь на рабочий стол для windows 10 pro
  • Ovg windows 10 ltsc
  • В каких случаях нужно переустанавливать windows