Winscp ssh подключение по ключу
Привет, йуные программисты. Сегодня расскажу о такой вещи, как SSH авторизация по ключу. С данной технологией я познакомился год назад на одном из проектов компании, был впечатлен и теперь активно сам использую. Зачастую, правда, сталкиваюсь с непониманием со стороны других разработчиков, мол «Зачем это нужно?!» .
Скажу сразу: я глубоко не админ, поэтому буду излагать так, как понимаю сам. Привычная всем нам авторизация состоит из связки «логин – пароль». Авторизация по ключу подразумевает связку «логин – ключ» , передаваемую серверу. Тысяча чертей, я кэп-очевидность!
Syntax
Command-line parameters that include space(s) must be surrounded by double-quotes:
To use the double-quote as a literal, use two double-quotes sequentially. For example, the /command expects that each script command is surrounded by double quotes, so that it is passed as a single command-line argument. In addition, any script command argument that includes spaces is expected to be surrounded by double-quotes within the command (see doubling double-quotes):
When executing such command from PowerShell, you additionally have to escape the doubled inner double-quotes with ` (backtick) to prevent PowerShell from interpreting them on its own:4
To debug the quoting, enable session logging on level Debug 1 ( /loglevel=1 ). The log will show how WinSCP understands your command-line.
An argument that begins with a slash is considered a switch. To pass a parameter that itself starts with the slash in its syntax (i.e. a remote path like /root ), use the special switch // (two slashes) before the argument. The switch // denotes that all following arguments are not switches. Example:
Private key conversion and modification
Use the /keygen switch to convert private keys from other formats to a PuTTY .ppk format or to change their passphrase or comment.
When converting the key from other format, you need to specify an output key path using the /output switch. When modifying a PuTTY key, the existing file is overwritten, if /output is not specified.
Use /changepassphrase switch to change the key passphrase.
Use /comment switch to change the key comment.
For example, to convert key mykey.pem from OpenSSH format to mykey.ppk in PuTTY format and set its comment:
To change the passphrase of existing mykey.ppk :
For a compatibility with *nix puttygen , the -o , -P and -C switches are understood as aliases to /output , /changepassphrase and /comment respectively. So, for features supported by WinSCP, you can use the same arguments as for puttygen , just prefixed with /keygen :
OpenSSH on Windows
-
from PuTTYgen, and copy that into the .ssh2 subdirectory of your account home directory.
- In the same subdirectory, edit (or create) a file called authorization . In this file you should put a line like Key mykey.pub , with mykey.pub replaced by the name of your key file.
Configure Server to Accept Public Key
Once logged in, configure your server to accept your public key. That varies with SSH server software being used. The most common SSH server is OpenSSH.
Operations
The following parameters can be used to create a shortcut that initiates operation in GUI mode. They are not intended for automation, for that see scripting.
Use /edit to open a remote file in WinSCP internal editor.
Use /browse to select the specified file in (both) file panel(s). The switch can also be used together with a file URL for the same effect, overriding the default download action.
With /synchronize or /keepuptodate parameter WinSCP performs Synchronize or Keep remote directory up to date commands respectively on the specified session and directories. A dialog to set options is displayed first.
With /upload parameter WinSCP uploads specified files to initial remote directory of session.3 A dialog to set options is displayed first.
Use /defaults parameter along with /upload , /synchronize or /keepuptodate to skip the settings dialog and start the operation straight away with default settings. Alternatively you can specify a number of seconds, to actually show the settings dialogs, but have them automatically submit after the specified time elapses.
Use the /refresh parameter to reload remote panel of all running instances of WinSCP. If a session is specified on command-line, only instances that have that session as active are refreshed. If a path is specified after the /refresh , only that directory is refreshed.
It is recommended to escape the arguments with // switch.
Authentication Options
OpenSSH
You can use Session > Install Public Key into Server command on the main window, or Tools > Install Public Key into Server command on SSH > Authentication page page on Advanced Site Settings dialog. The functionality of the command is similar to that of OpenSSH ssh-copy-id command.
Or you can configure the key manually:
- Navigate into a .ssh subdirectory of your account home directory. You may need to enable showing hidden files to see the directory. If the directory does not exists, you need to create it first.
- Once there, open a file authorized_keys for editing. Again you may have to create this file, if this is your first key.
- Switch to the PuTTYgen window, select all of the text in the Public key for pasting into OpenSSH authorized_keys file box, and copy it to the clipboard ( Ctrl+C ). Then, switch back to the editor and insert the data into the open file, making sure it ends up all on one line. Save the file. WinSCP can show you the public key too.
- Ensure that your account home directory, your .ssh directory and file authorized_keys are not group-writable or world-writable. Recommended permissions for .ssh directory are 700 . Recommended permissions for authorized_keys files are 600 . Read more about changing permissions.
Что такое SSH-ключ и как его создать
На самом деле речь идет о связке из двух ключей: один хранится у вас на рабочей машине, второй хранится на сервере, и они взаимно-однозначны. Первый ключ называется Private Key (приватный), второй – Public Key (публичный). Приватный ключ представляет собой текстовый файл с .ppk расширением и может быть использован на неограниченном количестве машин. Как правило, у каждого разработчика свой приватный ключ.
Для генерации подобной связки ключей нам потребуется программка PuTTYgen.exe (PuTTy Key Generator), которую вы должны были скачать, когда настраивали среду разработки. Запускаем программу, выбираем нужные опции и дрыгаем мышкой в конвульсиях для генерации случайного числа.
В самом верхнем отмеченном окне мы получаем Public key, который именно в таком виде и будем через несколько минут закидывать на сервер. Но перед этим сохраняем оба ключа себе на компьютер в укромное место, да так, чтобы не потерялись.
Logging
With /log parameter you may turn on session logging to file specified by local path. In the path you can use the same patterns as in the logging preferences.
Use parameter /loglevel to change logging level. The value can be in range -1 … 2 (for Reduced, Normal, Debug 1 and Debug 2 logging levels respectively). Append additional * to enable password logging (e.g. /loglevel=2* ).1
Use parameter /logsize to configure log file size limit and log file rotation. Specify maximum size in bytes, optionally with K , M or G units. Optionally you can limit number of archived log files using count* prefix. For example /logsize=5*10M will limit log file size to 10 MB and will allow up to 5 archived logs.
With /xmllog parameter you may turn on XML logging to file specified by local path.2 In the path you can use the same patterns as in the logging preferences.
Use parameter /xmlgroups along with /xmllog , to group all XML log elements belonging to the same command under parent group element.
Configuration
With /ini parameter you may specify local path to configuration INI file. It effectively disables using registry as configuration storage. If the file does not exist, default configuration will be used and the file will be created.
Use nul instead of path to force WinSCP start with its default configuration and not save the configuration on exit.
With /rawconfig parameter you can set any configuration settings using raw format as in an INI file. E.g. to configure an external IP address use /rawconfig Interface\ExternalIpAddress=198.51.100.10 . The parameter must come after a session URL (if any). The configuration set this way is preserved.
With /rawtransfersettings you can set any transfer settings using raw format as in an INI file. E.g. to enable preserving of directory timestamps, use /rawtransfersettings PreserveTimeDirs=1 . The configuration set this way is preserved. In scripting, it is better to use -rawtransfersettings switch of individual scripting commands, like get , put , etc.
Authentication Parameters
Private key file
Use the Private key file box to specify local path to your private key file if you are going to use public key authentication. The file must be in PuTTY format. If the private key is passphrase-protected, you will be prompted for passphrase once the authentication begins.
You can use Pageant so that you do not need to explicitly configure a key here.
If a private key file is specified here with Pageant running, WinSCP will first try asking Pageant to authenticate with that key, and ignore any other keys Pageant may have. If that fails, WinSCP will ask for a passphrase as normal. You can also specify a public key file in this case (in RFC 4716 or OpenSSH format), as that’s sufficient to identify the key to Pageant, but of course if Pageant isn’t present WinSCP can’t fall back to using this file itself.
The passphrase cannot be entered in advance in session settings and thus it cannot be saved to site. If you need to login to server automatically without prompt, generate a key without passphrase. Use this method carefully and only under special circumstances.
Private Key Tools
Use the button Display Public Key to display public key in a format suitable for pasting into OpenSSH authorized_keys file.
The command Tools > Generate New Key Pair with PuTTYgen starts PuTTYgen, in which you can generate a new private key pair. After you save your new key pair in PuTTYgen, WinSCP will detect it and automatically insert a path to the new key file into Private key file box.
Use the command Tools > Install Public Key into Server to install a public key into OpenSSH server. You will be prompted to select key pair to install. You will need to authenticate to the server to install the key. You can authenticate using a password or using another key (select it in Private key file box). After installing succeeds, the new private key will be inserted into the Private key file box.
Console/scripting mode
To run batch script either pass script file using /script parameter or specify the commands directly on command line using /command . In the latter case each following parameter is treated as single command. See syntax section and examples below for details how to deal with spaces and double-quotes.
If both /script and /command parameters are used, commands from script file are executed first. When the last command is not exit , regular non-batch mode follows.
Use parameter /parameter to specify list of arguments to be passed to script. It is recommended to escape the arguments with // switch.
With winscp.exe , if /console parameter is not used along with /script or /command , the script/command is executed without visual feedback (window).
Attempt Authentication Using Pageant
If this option is enabled, then WinSCP will look for Pageant and attempt to authenticate with any suitable public keys Pageant currently holds.
This behavior is almost always desirable, and is therefore enabled by default. In rare cases you might need to turn it off in order to force authentication by some non-public-key method such as passwords.1
Learn how to use the Pageant (PuTTY’s SSH authentication agent) application for public key authentication.
Running from Bash
When running WinSCP from a shell, where /switch is interpreted as a path, such as Git Bash, use a dash ( - ) instead of the slash ( / ) for switches. For example:
Public key authentication is an alternative means of identifying yourself to a login server, instead of typing a password. It is more secure and more flexible, but more difficult to set up.
In conventional password authentication, you prove you are who you claim to be by proving that you know the correct password. The only way to prove you know the password is to tell the server what you think the password is. This means that if the server has been hacked, or spoofed, an attacker can learn your password.
Public key authentication solves this problem. You generate a key pair, consisting of a public key (which everybody is allowed to know) and a private key (which you keep secret and do not give to anybody). The private key is able to generate signatures. A signature created using your private key cannot be forged by anybody who does not have that key; but anybody who has your public key can verify that a particular signature is genuine.
So you generate a key pair on your own computer, and you copy the public key to the server under a certain name. Then, when the server asks you to prove who you are, WinSCP can generate a signature using your private key. The server can verify that signature (since it has your public key) and allow you to log in. Now if the server is hacked or spoofed, the attacker does not gain your private key or password; they only gain one signature. And signatures cannot be re-used, so they have gained nothing.
There is a problem with this: if your private key is stored unprotected on your own computer, then anybody who gains access to that will be able to generate signatures as if they were you. So they will be able to log in to your server under your account. For this reason, your private key is usually encrypted when it is stored on your local machine, using a passphrase of your choice. In order to generate a signature, WinSCP must decrypt the key, so you have to type your passphrase.
This can make public-key authentication less convenient than password authentication: every time you log in to the server, instead of typing a short password, you have to type a longer passphrase. One solution to this is to use an authentication agent, a separate program which holds decrypted private keys and generates signatures on request. WinSCP can use PuTTY’s authentication agent, called Pageant. When you begin a Windows session, you start Pageant and load your private key into it (typing your passphrase once). For the rest of your session, you can start WinSCP any number of times and Pageant will automatically generate signatures without you having to do anything. When you close your Windows session, Pageant shuts down, without ever having stored your decrypted private key on disk. Many people feel this is a good compromise between security and convenience.
Allow agent forwarding
This option allows the SSH server to open forwarded connections back to your local copy of Pageant. If you are not running Pageant, this option will do nothing. Learn more about agent forwarding.
Mass-modification of sites
Use /batchsettings to mass-modify stored sites. The first argument is a mask to select sites to modify. Use a syntax of basic file masks. You can also use path mask to select sites based on their folders. The other arguments define new values for site settings. Use the same syntax as for /rawsettings .
For example to configure a proxy for all sites in a “clients” folder, use:
Private Keys
Other SSH Servers
For other SSH server software, you should refer to the manual for that server.
Настройка сервера
Я, надеюсь, у вас уже есть свой сервер или хостинг? Если нет, то, как друпалер до мозга и костей, я рекомендую IT-Patrol, который даже на минимальном тарифном плане предоставляет доступ по SSH. Для примера, я продолжу повествование на примере этого хостинга.
- Авторизируемся на сервере по предоставленной связке «логин – пароль» и переходим в предоставленную нам домашнюю директорию - /home/u1234 ;
- Создаем директорию .ssh c правами «700»;
- В директории .ssh создаем файл authorized_keys с правами «600»;
- Закидываем все необходимые Public keys в authorized_keys по принципу: одна строка – один ключ.
Для любителей все делать через консоль:
- cd ~ && ls - la | grep . ssh (проверяем наличие папки SSH конфигов домашнем каталоге);
- cd ~ && mkdir . ssh (в случае отсутствия папки);
- cd ~ && chmod 700 . ssh ;
- ssh - keygen - i - f ~ / public . pub >> ~ /. ssh / authorized_keys (импортируем закаченный ранее файл публичного ключа в authorized_keys файл;
- ~ && chmod 600 . ssh / authorized_keys .
Public Key Authentication in Clouds
Cloud providers have typically their own mechanism to setup a public key authentication to virtual servers running in the cloud.
The Authentication page on the Advanced Site Settings dialog allows you to configure authentication options of SSH protocol.
To reveal this page you need to select SCP or SFTP file protocol on Login dialog.
Refer to documentation of page sections:
Generating Keys
To generate a key pair, use the PuTTYgen application.
You can start PuTTYgen directly from Authentication page of Advanced Site Settings dialog. If you start PuTTYgen this way, WinSCP will automatically pick up the generated key.
Allow GSSAPI credential delegation
GSSAPI credential delegation is a mechanism for passing on your Kerberos (or other) identity to the session on the SSH server. If you enable this option, then not only will WinSCP be able to log in automatically to a server that accepts your Kerberos credentials, but also you will be able to connect out from that server to other Kerberos-supporting services and use the same credentials just as automatically.
This option is the Kerberos analogue of SSH agent forwarding.
Note that, like SSH agent forwarding, there is a security implication in the use of this option: the administrator of the server you connect to, or anyone else who has cracked the administrator account on that server, could fake your identity when connecting to further Kerberos-supporting services. However, Kerberos sites are typically run by a central authority, so the administrator of one server is likely to already have access to the other services too; so this would typically be less of a risk than SSH agent forwarding.1
The first syntax opens the site. To open site, stored in folder, use path syntax “folder/site”. You can also open workspace or all sites in site folder.
The second creates the session specified by session URL and optionally by initial remote path. If the remote path is not ended by slash ( / ), it is treated as path to file (or even directory) that should be downloaded.
The parameter /sessionname specifies a custom name of the session to be used instead of the automatically generated name in a format username@hostname or to override the name of the saved site.
If there’s already idle WinSCP instance running, the session(s) opens in the existing instance. To force session open in new instance of WinSCP, use /newinstance parameter.
The parameter /privatekey specifies a local path to an SSH private key file. If the key file is encrypted, use the /passphrase to specify its passphrase.
You can use the parameters /username and /password as an alternative way to specify the credentials. The credentials are normally part of the session URL. Using these switches has the advantage of not needing to URL-encode special characters.
The parameter /clientcert specifies a local path to FTPS or WebDAVS TLS/SSL client certificate. If the certificate is encrypted, use the /passphrase to specify its passphrase.
When a FTPS or WebDAVS server TLS/SSL certificate is not trusted (typically a self-signed certificate), use the parameter /certificate to specify the fingerprint of the untrusted certificate. It makes WinSCP trust the certificate. Several alternative fingerprints can be separated by a semicolon.
The parameter /passive enables a passive ( =on ) or an active ( =off ) transfer mode (FTP protocol only).
The parameters /implicit , and /explicit enable respective method of invoking FTPS.
The parameter /timeout specifies server response timeout.
The parameter /rawsettings allows configuring any site settings using raw format as in an INI file. E.g. to enable an SSH compression and an agent forwarding, use /rawsettings Compression=1 AgentFwd=1 . The parameter must come after the session URL (if any).
When using scripting, use the open command (and its switches) instead.
Executables
If you are going to run WinSCP from command-line often, you may wish to add WinSCP installation directory to search path.
Generate Key Pair
If you do not have a key pair yet, start with generating new key pair.
Attempt TIS or CryptoCard authentication
With this switch enabled, WinSCP will attempt these forms of authentication if the server is willing to try them. You will be presented with a challenge string (which may be different every time) and must supply the correct response in order to log in. If your server supports this, you should talk to your system administrator about precisely what form these challenges and responses take.1
You must select SSH-1 as a Preferred SSH protocol version to enable this option.
The SSH-1 support has been removed in the latest beta version.
Before Starting
Before starting you should:
Настройка клиента
В качестве клиента мы будем использовать программу WinSCP. Настроить соединение проще простого. Обратите внимание, что пароль отсутствует:
С этого момента авторизация на вашем сервере будет происходить по SSH-ключу. А теперь самое приятное – запуск консольного окна PuTTy без ввода пароля:
Теперь подведем итог, в чем же профит от того, что я здесь расписал:
- вам не надо запоминать какие-то пароли;
- быстрое и удобное предоставление доступа к серверу другим разработчикам;
- отсутствие необходимости вводить пароль в консоли PuTTy при авторизации.
Собственно на это все. Не заморачивайтесь с паролями, становитесь более продвинутыми!
This guide contains a description of setting up public key authentication for use with WinSCP. You may want to learn more about public key authentication or SSH keys instead.
Attempt keyboard-interactive authentication
‘Keyboard-interactive’ is a flexible authentication method using an arbitrary sequence of requests and responses; so it is not only useful for challenge/response mechanisms such as S/Key, but it can also be used for (for example) asking the user for a new password when the old one has expired.1
WinSCP leaves this option enabled by default, but supplies a switch to turn it off in case you should have trouble with it. If your server uses keyboard-interactive authentication to ask for your password only, and you wish to allow WinSCP to reply with password entered on Login dialog, tick Respond with password to the first prompt.
Auxiliary
When run with /update parameter, WinSCP only checks for its updates.
The parameter /info lists the supported SSH and TLS/SSL algorithms.
Parameter /help shows usage (overview similar to this).
Configure WinSCP Session
When configuring session, specify path to your private key on SSH > Authentication page of Advanced Site Settings dialog.
Alternatively, load the private key into Pageant.
Bypassing Authentication
In SSH, it is in principle possible to establish a connection without using SSH’s mechanisms to identify or prove who you are to the server. Some servers may simply require no authentication whatsoever.
By default, WinSCP assumes the server requires authentication (we’ve never heard of one that doesn’t), and thus must start this process with a username. If you find you are getting username prompts that you cannot answer, you could try enabling Bypass authentication entirely. However, most SSH servers will reject this.
This is not the option you want if you have a username and just want WinSCP to remember it; It’s also probably not what if you’re trying to set up passwordless login to a mainstream SSH server; depending on the server, you probably wanted public-key authentication or perhaps GSSAPI authentication. (These are still forms of authentication, even if you don’t have to interact with them.)1
GSSAPI
Attempt GSSAPI authentication
WinSCP supports two forms of GSSAPI-based authentication. In one of them, the SSH key exchange happens in the normal way, and GSSAPI is only involved in authenticating the user. The checkbox labelled Attempt GSSAPI authentication controls this form.
In the other method, GSSAPI-based authentication is combined with the SSH key exchange phase. If this succeeds, then the SSH authentication step has nothing left to do. See the Attempt GSSAPI key exchange checkbox on the Key exchange page.
If one or both of these controls is enabled, then GSSAPI authentication will be attempted in one form or the other, and (typically) if your client machine has valid Kerberos credentials loaded, then WinSCP should be able to authenticate automatically to servers that support Kerberos logins.
If both of those checkboxes are disabled, WinSCP will not try any form of GSSAPI at all, and the rest of the GSSAPI box is unused.
Читайте также: