Меню Рубрики

Cygwin ssh server windows

Установка SSH-демона на Windows

Недавно я уже писал о том, как поднять SSH-туннелирование между двумя компьютерами, один из которых работает на Windows (клиент), другой — на Debian (сервер).

Теперь возникла задача создать туннель между компьютерами с установленной ОС Windows. Эта задача чуть сложнее, т.к. в Windows нет встроенного SSH-сервера, чтобы принимать подключения от клиента. Таким образом на компьютер-сервер, который, кстати, у меня работает под управлением Windows Server 2012 Standart, пришлось поднимать SSH-демон. Для решения этой задачи, как и ранее, я использовал Cygwin. Для работы с SSH нужно установить два дополнительных пакета — openssh и openssl.

Далее идет инструкция, как поднять SSH-демон на Windows:

1. Необходимо отредактировать файл Cygwin.bat, добавив в него следующую строку:

set CYGWIN=binmode ntsec

Таким образом батник должен иметь следующий вид:

2. Теперь необходимо убедиться, что Cygwin (cygrunsrv) установлен должным образом. Для этого нужно запустить Cygwin.bat и в открывшемся окне консоли ввести команду:

Если будет показана справка, то все установленно корректно и можно продолжать дальше. В противном случае нужно будет переустановить Cygwin.

3. Для установки SSH-демона (демон в Windows принято называть службой) нужно выполнить следующую команду:

На появляющиеся вопросы следует отвечать следующим образом:

Если конфигурация прошла успешно, то должно быть выведено следующее сообщение:

4. Далее нужно выполнить команды:

/bin/mkpasswd -l –u root >> /etc/passwd
mkdir -p /home/root (for example, mkdir -p /home/pjohn)
chown /home/root

5. В файле C:\cygwin\etc\passwd нужно удалить подобную строку (если есть), которая запрещает пользователю root использовать интерпретатор bash:

6. Выполните следующую команду для запуска SSH-демона (службу можно запустить также из оснастки «Services»):

7. Убедитесь, что 22 порт открыт для прослушивания (в этом поможет команда netstat -na). Если нет, то необходимо создать соответствующее правило в Windows Firewall.

Теперь можно проверить подключение с клиента:

Если все настроенно правильно, то будет выведено приглашение на подключение и ввода пароля.

Источник

Как установить Cygwin на Windows 7

Задача : Разобрать, как установить OpenSSH сервис на Windows 7 с применением Cygwin.

Для справки: В данном примере используется Windows 7 с архитектурой x 64

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

  • Как установить в систему Windows пакет Cygwin
  • Как установить OpenSSH пакет
  • Как настроить аутентификацию по ключу против по паролю

Устанавливаю в систему пакет Cygwin , скачав необходимый по следующей ссылке: http://cygwin.com/setup-x86_64.exe

если используется архитектура x 86, то ссылка на скачиваемый пакет:

http://cygwin.com/setup-x86.exe

На заметку: для установки в системе должны быть права Администратора, и у меня UAC Отключён.

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

W7X86 – 192.168.1.59

W7X64 – 192.168.1.40

Запускаю установщик (версия 2.852 (64 bit )ДалееInstall from Internet , Далее – каталог установки оставляю по умолчанию: C :\ cygwin 64 и тип установки для всех пользователей: All Users ( RECOMMENDED ), Далее – следующим шагом оставляем путь предложенный установщиком где будет располагаться локальные пакеты: C :\ Users \ ekzorchik \ Downloads , Далее – предопределяем тип используемого соединений, Direct Connection (в моем случае, соединение прямой, прокси сервер не используется), Далее – на следующем шаге выбираем сервер загрузки из множества (любой), к примеру: http :// mirrors — ru . go — parts . com , Далее – на следующем шаге выбираем пакет(ы) которые нужны в системе нам, в моем случаем мне нужен пакет:

В текущем примере моей заметки — это пакет для организации безопасного подключения к системе посредством SSH, т. е. Пакет OpenSSH, как серверная так и клиентская часть.

, Далее – в процессе установки мастер определит, какие зависимости сперва нужно до установить, соглашаемся, Далее – и начнется процесс скачивания зависимостей и самого приложений, просто ожидаем – после того, как установка пройдет успешно останется только проконтролировать, чтобы были поставлены галочки для создания ярлыков быстрого доступа к Cygwin :

  • Create icon on Desktop
  • Add icon to Start Menu

И нажать Готово.

На заметку: Если понадобится установить в эмулятор консоли еще какие либо утилиты, то данные шаги повторяются, запуск исполняемого файла, указания сайта с которого будем производить скачивание и установку утилит.

Далее запускаю терминал Cygwin :

Пуск – Все программы – Cygwin — Cydwin 64 Terminal , окно консоли примет вид:

Copying skeleton files.

These files are for the users to personalise their cygwin experience.

They will never be overwritten nor automatically updated.

ekzorchik @srv-w7x64

В консоли после приглашения курсора $ набираем ssh-host-config –y этим мы генерируем ключи доступа к данной машине по ssh и создаем нового пользователя cyg _ server где в качестве его пароля нужно указать текущий пароль от пользователя (в моем случае пользователь ekzorchik с дефолтный паролем 712 mbddr @) под которым происходит инсталляция пакета cygwin и дополнительных пакетов в систему:

$ ssh-host-config -y

Часть информации выводимая в консоли отвечающая за создание нового пользователя cyg _ server от имени которого будет происходит запуск инсталлированной службы « CYDWIN sshd »

*** Query: Please enter the password:712mbddr@

*** Query: Reenter: 712mbddr@

Как видно, созданный пользователь инсталлирует службу в систему запуск которой будет осуществляться от имени данного пользователя ( cyg _ server ), по умолчанию она становится не запущенной, запускаю:

Win + R -> cmd.exe

C:\Users\ekzorchik>sc config sshd start= auto

SC] ChangeServiceConfig: успех

C:\Users\ekzorchik>net start sshd

Служба «CYGWIN sshd» запускается.

Служба « CYGWIN sshd » успешно запущена.

Либо через запущенную терминальную консоль Cygwin Terminal :

  • -S, —start Starts a service named .
  • -E, —stop Stops a service named .

$ cygrunsrv.exe -E sshd

$ cygrunsrv.exe -S sshd

Также важно открыть доступ к системе по порту 22 (порт по дефолту). Для этого нужно добавить правило в брандмауэр для всех профилей системы:

netsh avdfirewall firewall add rull name=”SSH Server” dir=in protocol=tcp localport=22 action=allow

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

C:\Users\ekzorchik>netstat -an | findstr :22

TCP 0.0.0.0:22 0.0.0.0:0 LISTENING

TCP [::]:22 [::]:0 LISTENING

Из вывода ясно, что порт открыт.

По такому же принципу шагов описанных выше устанавливаю и на другую систему с осью Windows 7 но применительно к архитектуре x86, хотя разницы в шагах вообщем-то никакой. Просто мне нужно для тестирования и показа, как это работает в дальнейшем.

Следующим шагом перехожу к тестированию подключения к системе посредством SSH соединения, в роли клиента на подключение к системе может использоваться, как консольный вариант — это через Cygwin Terminal, так и отдельным приложением ,к примеру утилита — Putty. Я же буду использовать Cygwin Terminal.

$ hostname

$ ssh -l ekzorchik 192.168.1.40 -p 22

The authenticity of host ‘192.168.1.40 (192.168.1.40)’ can’t be established.

ECDSA key fingerprint is 57:8b:b2:35:43:f5:18:22:c0:e7:61:9b:44:d4:56:fe.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added ‘192.168.1.40’ (ECDSA) to the list of known hosts.

ekzorchik@192.168.1.40’s password:712 mbddr@

— подключение по SSH прошло успешно в другую систему.

Отлично, работает, теперь же надо сделать, чтобы авторизация шла только по ключам доступа.

Ниже практические шаги, как это сделать:

Генерирую публичный и приватный ключ системы:

$ ssh-keygen -t dsa

Generating public/private dsa key pair.

Enter file in which to save the key (/home/ekzorchik/.ssh/id_dsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/ekzorchik/.ssh/id_dsa.

Your public key has been saved in /home/ekzorchik/.ssh/id_dsa.pub.

The key fingerprint is:

The key’s randomart image is:

Далее копируем публичный(открытый ключ) на вторую систему:

/.ssh/id_dsa.pub | ssh -p 22 ekzorchik@192.168.1.59 ‘umask 077;test -d .ssh | cat >>

ekzorchik@192.168.1.59’s password:712 mbddr@

Точно такие же шаги проделываем на второй системе по отношения к первой, но не забываем указать соответствующий IP адрес системы, в моем случае — это 192.168.1.40

/.ssh/id_dsa.pub | ssh -p 22 ekzorchik@192.168.1.40 ‘umask 077;test -d .ssh | mkdir .ssh ; cat >> .ssh/authorized_keys’

mkdir: cannot create directory ‘.ssh’: File exists

/.ssh/id_dsa.pub | ssh -p 22 ekzorchik@192.168.1.40 ‘umask 077;test -d .ssh | cat >> .ssh/authorized_keys’

$ ssh -l ekzorchik 192.168.1.40 -p 22 Last login: Thu Nov 27 18:36:23 2014 from 192.168.1.59

Но пока авторизация по ключам не заработает, в системах по умолчанию отключены все параметры настроек службы OpenSSH. Поэтому сперва произведу кое-какую настройку, в качестве редактора посредством которого буду изменять конфигурационные файлы выступит установленный по умолчанию — редактор vi: (советую познакомиться с его работой подробно, к примеру по моей заметке или по книгам посвященным Linux), но для быстро по первой настройке доустановлю пакет простого текстового редактора nano. Для этого снова запускаем setup-x86_64.exe – шаги до установки пакета точно такие же которые я проделывал выше когда устанавливал OpenSSH. Ниже скриншот поиска и установки необходимого бинарного пакета, исходники пакета не требуются поэтому их и не отмечаю.

Далее переходим к редактированию настроек сервиса SSHD:

$ nano /etc/sshd_config

Сохраняем внесенные ( Ctrl + O, Ctrl + X) изменения и перезапускаю службу для применения настроек.

$ cygrunsrv.exe -E sshd

$ cygrunsrv.exe -S sshd

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

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

Работает с 192.168.1.40 на 192.168.1.59

ssh ekzorchik@192.168.1.59 -p 22

Last login: Thu Nov 27 17:58:06 2014 from w7x64

Работает с 192.168.1.59 на 192.168.1.40

$ ssh -l ekzorchik 192.168.1.40 -p 22

Last login: Thu Nov 27 18:40:21 2014 from 192.168.1.59

Отлично, все заработало, шаги один в один, как и на Ubuntu 12.04.5 Server/Desktop. Если же у Вас не заработает, то при подключении включите режим логирования, параметр v, либо проверьте что содержимое authorized_keys удаленной системы содержит id_dsa.pub ключ первой , возможно в этом проблема, вообщем вот так сразу сложно сказать в чем может быть проблема, если работает по паролю, а не работает по ключу, скорое всего не добавлен ключ на удаленную систему. Будьте внимательнее, но раз столкнувшись с проблемами и решив их Вы будете более подкованными в дальнейшем . Свой опыт лучше, чем подсказка более опытных, хотя и знаешь что сэкономишь время, но это как в школе, мало того что можно списать решение из книги содержащей пошаговое решение, пока сам не повторишь и не разберешь ни будешь знать в общем-то ничего . Вот так. На этом задачу считаю выполненной и смею прощаться. До встречи в следующих реальных заметках — с уважением автор блога — ekzorchik.

Используйте прокси ((заблокировано роскомнадзором, используйте vpn или proxy)) при использовании Telegram клиента:

Поблагодари автора и новые статьи

будут появляться чаще 🙂

Карта МКБ: 4432-7300-2472-8059
Yandex-деньги: 41001520055047

Большое спасибо тем кто благодарит автора за практические заметки небольшими пожертвованиями. С уважением, Олло Александр aka ekzorchik.

Источник

5 Installing Cygwin and Starting the SSH Daemon

This chapter explains how to install Cygwin and start the SSH daemon on Microsoft Windows hosts. This chapter is applicable only when you want to install a Management Agent on a Microsoft Windows host, using the Add Host Targets Wizard or EM CLI. In particular, this chapter covers the following:

If you do not want to install Cygwin to deploy Management Agents on Microsoft Windows hosts using the Add Host Targets Wizard or EM CLI, you can choose to deploy Management Agents on these hosts using the PsExec process utility. For information on how to deploy Management Agents on Microsoft Windows hosts using PsExec, see Appendix F.

5.1 About the Cygwin Requirement for Installing Management Agents

The Add Host Targets Wizard is an application built into the Enterprise Manager Cloud Control console. It offers GUI-rich, interactive screens that enable you to install Oracle Management Agents (Management Agents) on unmanaged hosts and convert them to managed hosts, so that they can be monitored and managed in Enterprise Manager Cloud Control.

When you use the Add Host Targets Wizard or EM CLI to install a Management Agent on a host running on Microsoft Windows, as a prerequisite, you must install Cygwin and start the SSH Daemon on the host. To do so, follow the steps listed in Section 5.3.

Cygwin is essentially a utility that offers a Linux-like environment on a Microsoft Windows host. Technically, it is a DLL ( cygwin1.dll ) that acts as a Linux API layer providing substantial Linux API functionality. Once you install Cygwin, you can configure the SSH Daemon on the host. The Add Host Targets Wizard is certified and supported with Cygwin 1.7.

The SSH Daemon enables the Add Host Targets Wizard to establish SSH connectivity between the OMS host and the host on which you want to install a Management Agent. Using this connectivity, the wizard transfers the Management Agent software binaries to the destination host over SSH protocol, installs the Management Agent, and configures it.

5.2 Be fore You Begin Installing Cygwin

Before starting with the SSHD setup, ensure you are not using OpenSSH and MKSNT when using the Add Host Targets Wizard. To do so, perform the following checks:

Ensure OpenSSH\bin and mksnt are not in your PATH environment variable. If they are, remove them by doing the following:

Right-click on My Computer and go to Properties .

In the System Properties window, click Advanced.

In this tab, click Environment Variables.

Here, search for the PATH system variable, select it, and if the OpenSSH\bin and mksnt are present in PATH, click Edit.

In the Edit System Variable dialog box, delete these two values from PATH, then click OK.

Stop the SSH Daemon if it is running from OpenSSH , MKS or any other vendor. If the SSH Daemon is running, stop it by doing the following:

Right-click on My Computer , and select Manage.

In the Computer Management window, in the left pane, expand Services and Applications , and select Services .

In the right pane, click the SSH Daemon/MKS Secure Shell service, then click the Stop button.


The navigational steps described in this section may vary for different Microsoft Windows operating systems.

5.3 Installing Cygwin

To install Cygwin on a Microsoft Windows host, follow these steps:

Access the following URL, then click Install Cygwin:

Download the 32-bit version (if you are running a 32-bit version of Microsoft Windows) or the 64-bit version (if you are running a 64-bit version of Microsoft Windows) of the Cygwin setup executable.

Run the setup executable, then click Next to proceed.

On the Choose Installation Type screen, select Install from Internet, then click Next.

On the Choose Installation Directory screen, enter C:\cygwin as the Root Directory, then click Next.

If you choose to install Cygwin in a different directory, then ensure that you update the SSH_PATH, SCP_PATH, MKDIR_PATH, SH_PATH, CHMOD_PATH , and TRUE properties present in the $ \oui\prov\resources\ssPaths_msplats.properties file to their proper Cygwin binary values, after installing the Enterprise Manager system.

For example, if you choose to install Cygwin in the D:\software\cygwin directory, then update the specified properties in the following manner:

On the Select Local Package Directory screen, select a directory on your local machine where you want to store the downloaded installation files, then click Next.

On the Select Connection Type screen, select appropriate settings to connect to the internet, then click Next.

On the Choose Download Site(s) screen, select any site from the available list, then click Next.

On the select pac kages screen, ensure that you select the following packages, then click Next :

From the Archive category, select unzip and zip as follows:

From the Net category, select openssh and openssl as follows:

After selecting the packages and clicking Next, the Resolving Dependencies screen is displayed. Click Next to proceed.

On the Installation Status and Create Icons screen, do not make any changes. Click Finish to complete the installation process.


5.4 Confi guring SSH

This section describes how to configure SSH and test your Cygwin setup after installing Cygwin on a host.

While configuring SSH, you may need to run the cygwin.bat script. While running cygwin.bat in Microsoft Windows Server 2008 and Microsoft Windows Vista, ensure that you invoke it in administrator mode. To do this, right-click the cygwin.bat file and select Run as administrator.

To configure SSH and test your Cygwin setup, follow these steps:

After you install Cygwin, navigate to the C:\cygwin directory, open the Cygwin.bat file in edit mode using any editor, and add the following line before invoking the bash shell.

set CYGWIN=binmode ntsec

For example, here are the contents for the Cygwin.bat file after adding the above line:

To verify if Cygwin ( cygrunsrv) is installed properly, run C:\cygwin\Cygwin.bat , and execute the following command:

If Cygwin is installed properly, then all the Cygwin help options are displayed on the screen. However, if this command returns an error message, then you may have to reinstall Cygwin.

To configure the SSHD service, run C:\cygwin\Cygwin.bat , and execute the following command:

After running the command, you are prompted the following questions:

At this point, if you want to use the same name, that is cyg_server, enter no. You are then prompted the following questions:

However, if you want to use a different name, enter yes. You are then prompted the following questions:

If the configuration is successful, you will see the following message:

Backup the c:\cygwin\etc\passwd file and then use any editor to open the file in edit mode. Remove only those entries of the user that you will use to connect to the host on which you want to install a Management Agent. Ask the user to make a backup of the c:\cygwin\etc\passwd file before editing.

If the user that you are employing to connect to the host on which you want to install the Management Agent is a local user, run C:\cygwin\Cygwin.bat and execute the following:

If the user you are employing to connect to the host on which you want to install the Management Agent running is a domain user, run C:\cygwin\Cygwin.bat and execute the following:

(Only if the Cygwin software you have installed is of version 1.7.32 or higher) Open C:\cygwin\etc\sshd_config in a text editor and add the following line to the end of the file:

(For a domain user only) If the user you are employing to connect to the host on which you want to install the Management Agent is a domain user, do the following to start the SSH daemon:

Right-click on My Computer , and select Manage .

In the Computer Management dialog box that appears, go to Services and Applications, and select CYGWIN sshd .

Right-click CYGWIN sshd and select Properties .

In the Properties dialog box, go to the Log On tab.

Here, specify the domain/user name and password. Click Apply.

Run C:\cygwin\Cygwin.bat , and execute the following:

If /var/log/sshd.log does not exist, you do not have to execute the following commands:

Perform one of the following steps to start the SSH daemon:

Run C:\cygwin\Cygwin.bat and execute the following command:

Run C:\cygwin\Cygwin.bat and execute the following command:

Perform these steps:

Right-click on My Computer , and select Manage .

In the Computer Management dialog box that appears, go to Services and Applications, and select CYGWIN sshd .

Click CYGWIN sshd, then click the Start button.

If the SSH daemon does not start up, view the c:\cygwin\var\log\sshd.log file for information on why the start up failed.

You can now test your Cygwin setup.

To do this, go to a different machine (that has the ssh client running), and execute the following command:

This command will prompt you to specify the password. When you specify the correct password, the command should return the accurate date.

If you experience a process fork failure, memory leak error, or a file access error after configuring SSH, view the following website for a workaround:

If you are unable to find a workaround for your problem, report your problem to the Cygwin community using the following website:

5.5 After Inst alling Cygwin and Configuring SSH

After installing Cygwin (as described in Section 5.3) and configuring SSH (as described in Section 5.4), follow these steps:

If the OMS host runs on a Microsoft Windows platform, perform the following on the OMS host:

Right click My Computer, then select Properties. In the window that appears, select Advanced system settings, then select Environment Variables. In the System Variables section, create the CYGWIN variable, and specify its value as nodosfilewarning

You do not need to restart the host after performing this step.

Navigate to the Cygwin install directory (that is, C:\cygwin if you chose to install Cygwin in the default location), open the Cygwin.bat file in edit mode using any editor, then edit the following line:

For example, these are the contents of the Cygwin.bat file after editing the above line:

From the Start menu, select Run. For Open, enter services.msc, then click OK. Search for the Cygwin SSHD service and stop it.

Navigate to the Cygwin install directory (that is, C:\cygwin if you chose to install Cygwin in the default location), then run Cygwin.bat. Run the following command to start the SSHD service:

Running this command may return an error mentioning that /var/empty must be owned by the root user. If you encounter this error, run the following from the Cygwin terminal:

After running this command, retry the $ /usr/sbin/sshd command.

Perform the tasks mentioned in Step 1 on all the Microsoft Windows target hosts (on which you want to install Management Agents using the Add Host Targets Wizard or EM CLI).

Источник

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

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

  • Cydia impactor windows ошибка
  • Cydia impactor windows как пользоваться
  • Cyborg evo force драйвера для windows 7
  • Cyberlink youcam windows 7 32 bit
  • Cyberlink powerdvd for windows xp