Перейти к содержимому

Как через путти передать файл

  • автор:

6.2.10 The put command: send a file to the server

To upload a file to the server from your local PC, you use the put command.

In its simplest form, you just use this with a file name:

If you want to store the file remotely under a different name, specify the remote file name after the local one:

This will send the local file called myfile.dat , but will store it on the server under the name newname.dat .

To send an entire directory recursively, you can use the -r option:

(If you want to send a file whose name starts with a hyphen, you may have to use the — special argument, which stops put from interpreting anything as a switch after it. For example, ‘ put — -silly-name- ’.)

Глава 5: Using PSCP to transfer files securely

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 chapter 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:

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:

(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:

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:

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

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:

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

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:

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:

. 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.8.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:

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:

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 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:

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.23.8). 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.8.3.18 for more information.

Thirdly, PSCP will attempt to authenticate using Pageant if Pageant is running (see chapter 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 chapter 8.

Transfer files to/from session I'm logged in with PuTTY

What is the command to transfer files from my local machine to the machine I’m logged into on PuTTY?

blue-sky's user avatar

13 Answers 13

This is probably not a direct answer to what you’re asking, but when I need to transfer files over a SSH session I use WinSCP, which is an excellent file transfer program over SCP or SFTP. Of course this assumes you’re on Windows.

  • Click on start menu.
  • Click run
  • In the open box, type cmd then click ok
  • At the command prompt, enter:

  • When promted, enter your password for server.

S.L. Barth is on codidact.com's user avatar

PuTTY usually comes with a client called psftp which you can leverage for this purpose. I don’t believe you can do it through the standard PuTTY client (although I may be proven wrong on that).

PuTTY only gives you access to manipulate the remote machine. It doesn’t provide a direct link between the two file systems any more than sitting down at the remote machine does.

Peter Mortensen's user avatar

corsiKa's user avatar

You can also download psftp.exe from:

When you run it you type:

(Type help to get a full list of commands.)

You can also type get <file name> to download files from a remote machine to the local machine.

Peter Mortensen's user avatar

There’s no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (the pscp or psftp ), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY button.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.

(I’m the author of WinSCP)

Since you asked about to/from, here’s a trick that works for the ‘from’ part. Open the ‘Change settings. ‘ screen, Terminal, and under ‘Printer to send ANSI printer output to:’ select ‘Generic / Text Only’

Now on the remote system, run this on one line:

Putty will inform you that the file was saved. What this is doing is putting the terminal into printer mode (tput mc5), printing the file to the screen (cat), and then turning off printer mode (tput mc4). If you don’t put all the commands on one line, the screen will appear frozen because Putty is saving all terminal output to a file in the background.

If you’re on a more limited system that doesn’t have the tput command (e.g. a qnap), you can try printf «\x1b[5i» instead of tput mc5, and printf «\x1b[4i» instead of tput mc4.

The command in the middle is just anything that prints to the screen. So use tail -n 10000 blah.log to download the last 10k lines of the log file, or use a base64 encoder to map a binary file to something you can print (and then decode on your local system):

If it is only one file, you can use following procedure (in putty):

  1. vifilename.extension (opens new file name in active folder on server),
  2. copy + mouse right click while over putty (copy and paste),
  3. edit and save. =>vi editor commands

Edit file permission with next command: chmod u+x filename.extension

If you have to do private key validation; at Command Prompt(cmd), run

Also, if you need extra options look at the following link. https://the.earth.li/

ÖMER TAŞCI's user avatar

It recommends using pscp.exe from PuTTY, which can be found here: https://www.chiark.greenend.org.uk/

A direct transfer like FTP is not possible, because all commands during your session are send to the server.

Инструкция по программе Putty и PSCP

Для удаленной работы с серверами Linux, FreeBSD, *BSD удобно пользоватся программой Putty.

Putty — это бесплатная программа — клиент для подключения к серверу в основном по SSH протоколу, но также можно использовать и telnet протокол, который не желательно использовать из-за его небезопасности, так как все по telnet протоколу передается в незашифрованном виде.

Через протокол SSH вы узнаете как пробросить порт на роутер, модем либо другое оборудование за сервером с установленным сервером SSH, узнаете как можно скачать либо закачать файл на сервер либо с сервера. Вообщем Putty очень полезная и удобная маленькая программа с большими возможностями.

Программу Putty также можно использовать и для подключения к устройствам используя последовательный порт, например настроить 3G модем Huawei через Putty.
Скачиваем программу Putty и PSCP на странице: <![CDATA[ ]]> скачать Putty и PSCP с официального сайта <![CDATA[ ]]>

При открытии выше приведенной ссылки в браузере, Вам откроется окно:

Открываем официальный сайт и скачиваем программы Putty и Pscp

На скриншоте выше обведено две ссылки которые нужно скачать на диск С:\ в папку putty, которую необходимо предварительно создать. Туда скачиваем две программы putty.exe и pscp.exe. На приведенном ниже скриншоте Вы можете видеть скачанные на моем компьютере программы в папке putty на диске C:\

Скачиваем программы Putty и Pscp на диск С в папку putty

Запускаем файл программы putty.exe нажав дважды на файле мышкой, откроется окно, в котором я добавляю сервер Linux который находится в моей сети и имеет айпи адрес 192.168.2.1 со стандартным портом SSH — 22, итого:

  • Host Name: 192.168.2.1
  • Port: 22
  • Saved Session: 192.168.2.1 (тут можно написать любое имя, например сервер Васи Пупкина)

Окно программы Putty - добавляем server Linux

Далее обязательно переходим во вкладку Window — Translation и в выпадающем списке выбираем кодировку UTF-8(либо выбираем ту кодировку с которой настроен Ваш удаленный сервер, в большинстве случаев это UTF-8), если этого не сделать, тогда у Вас после подключения к серверу используя Putty все руские слова будут отображатся нечитаемыми символами:

Изменяем кодировку текущего сервера на UTF-8

После изменения кодировки переходим в главное окно Session и проверив, что у Вас заполнено поле Saved Session нажимаем кнопку Save. Теперь у Вас в главном окне появилась новая запись 192.168.2.1 (либо сервер Васи Пупкина). После закрытия программы Putty у Вас добавленная запись останется и для подключения к удаленному серверу по SSH Вам достаточно нажать дважды на сохраненную запись 192.168.2.1:

Сохраняем добавленный сервер в Putty

При первом подключении к серверу по SSH протоколу, Вам будет предложено согласится на запись ключа удаленного сервер в кеш программы Putty, Вы соглашаетесь на это нажав кнопку Да и Вам откроется окно ввода логина и пароля:

Подключаемся и соглашаемся на вопрос программы при добавлении ключа сервера

В открывшемся окне вводим имя пользователя например root и нажимаем Enter, Вам будет предложено ввести пароль пользователя root, сам вводимый пароль не будет виден, просто когда введете пароль нажмите Enter и если Вы правильно ввели логин:пароль Вы окажетесь на удаленно Linux сервере:

Подключаемся к удаленному серверу Linux по SSH используя программу Putty

Ниже приведен скриншот в котором я вошел на сервер Linux по SSH bcgjmpez программу удаленного доступа Putty:

Подключились к удаленному серверу Linux по SSH используя программу Putty

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

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

  • IP Удаленного сервера — 192.168.2.1
  • IP роутера либо модема — 192.168.1.1
  • Пробрасываемый порт — 82

Нам необходимо в браузере открыть настройки роутера либо модема, внести изменения и сохранить. Пробрасывать будем 82 порт, так как он при стандартных настройках как сервера так и декстопа не задействован.

Так как мы будем пробрасывать 82 порт на роутер на том же сервере к которому мы ранее уже подключались, на необходимо во вкладке Session выделить мышкой добавленный ранее сервер с именем 192.168.2.1 и нажать кнопку Load, после этого заполнятся поля Host Name, Port, Saved Session:

Добавляем туннель для проброса 82 порта на роутер, модем за сервером

Нам необходимо перейти во вкладку Connection — SSH — Tunnels и заполнить поля:

где порт 82 — это порт который откроется на Вашем компьютере (декстопе), а 192.168.1.1:80 это айпи роутера и порт на который нам необходимо пробросить порт. Все что открывается по ссылке http — это 80 порт, https — это 443 порт. Аналогично можно пробросить и 21 порт это FTP, почту, SSH, Radmin, RDP и так далее. После заполнения полей нажимаем кнопку Add для добавления тунеля в текущие настройки:

Добавляем туннель для проброса 82 порта на роутер, модем за сервером

В окне ниже мы добавили туннель на роутер с 82 порта на айпи роутера 192.168.1.1 и WEB порт 80:

Добавили туннель для проброса 82 порта на роутер, модем за сервером

После добавления тунеля нам необходимо сохранить данные настройки под другим именем, для этого переходим во вкладку Session и в поле Saved Session написать имя соединения с настроенным тунелем: 192.168.2.1_82-to-192.168.1.1 и нажимаем кнопку Save, в окне ниже появится новое имя 192.168.2.1_82-to-192.168.1.1 дважды нажав на которое мышкой, мы получим приглашение ввести логин:пароль, введя которые мы зайдем на удаленный сервер.

Сохраняем настройки с туннелем на роутер, модем под отдельным именем

После того как мы зашли на удаленный сервер с профиля 192.168.2.1_82-to-192.168.1.1, в котором у нас настроен проброс порта 82 на 80 порт роутера по айпи 192.168.1.1, нам для подключения к роутеру либо модему необходимо в браузере прописать адрес http://localhost:82 и у Вас откроется окно ввода логина и пароля от роутера:

Заходим на роутер, модем через 82 проброшенный порт в Putty

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

Как настроить проброс порта через Putty Вы узнали, потому переходим к третьему разделу копирования файлов по SSH.

Копирование файлов через SSH используя программу для удаленного доступа Putty.

Для копирования файла на удаленный сервер, я в папке pytty на диске C:\ заархивировал программу putty.exe, и в заархивированном виде файл имеет имя putty.zip скриншот:

Заархивированный файл putty.zip, который мы скопируем на удаленный сервер по SSH

Для копирования файла putty.zip нам необбходимо открыть командную строку Windows, для этого нажимаем кнопку Пуск — Выполнить и в появившемся окне вводим команду cmd и нажать Ok:

Запускаем командную строку в Windows

После запуска командной строки выполнив команду cmd нам откроется окно:

Открыта командная строка Windows

После открытия командной строки, нам необходимо перейти в папку, где находится программа pscp.exe и копируемый файл putty.zip, для этого нам необходимо выполнить в командной строке команду:

После входа в папку putty на диске C:\ мы можем проверить содержимое папки выполнив команду:

На скриншоте ниже это все видно:

Переходим в папку Putty на диске C:\

И теперь нам для того, чтобы закачать файл putty.exe на удаленный сервер под пользователем root в папку /root нам необходимо выполнить команду:

Если у Вас SSH сервер висит на стандартном 22 порту, выполняете команду:

Если же у Вас SSH сервер висит на нестандартном порту, например 222, тогда выполняете команду:

Копируем файл по ssh на удаленный сервер

В команде выше мы сказали программе pscp.exe закачать файл putty.zip находящийся в текущей директории на удаленный сервер под пользователем root с IP адресом 192.168.2.1 в папку /root. После выполненной команды, Вам будет предложено ввести пароль пользователя root

Для того, чтобы скопировать файл putty.zip с удаленного сервера в текущую папку, SSH сервер на стандартном 22 порту, нам необходимо выполнить команду:

Для того, чтобы скопировать файл putty.zip с удаленного сервера в текущую папку, SSH сервер на нестандартном 222 порту, нам необходимо выполнить команду:

Копируем файл по ssh с удаленного сервера в текущую папку

В команде выше мы сказали программе pscp.exe cкачать файл putty.zip находящийся в директории /root на удаленном сервере под пользователем root с IP адресом 192.168.2.1 в текущую папку (в папку в которой мы находимся)

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

С Вами был Лазаренко Сергей, буду очень рад если данная инструкция будет Вам полезна.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *