- Ethical hacking and penetration testing
- InfoSec, IT, Kali Linux, BlackArch
- How to install and use Ruby on Windows
- Why install Ruby
- How to install Ruby on Windows
- How to update Ruby on Windows
- How to install and use gem on Windows
- How to install bundler
- How to install the Ruby program on Windows. How to run a Ruby program on Windows
- Recovering sites from the Internet Archive in Windows
- How to Install WhatWeb on Windows
- How to install WPScan on Windows
- What is MSYS2. How to use MSYS2
- How to configure Ruby as an Apache module on Windows
- HackWare.ru
- Этичный хакинг и тестирование на проникновение, информационная безопасность
- Как установить и использовать Ruby в Windows
- Для чего устанавливать Ruby
- Как установить Ruby на Windows
- Как обновить Ruby на Windows
- Как установить и использовать gem в Windows
- Как установить bundler
- Как установить программу Ruby в Windows. Как запустить программу Ruby в Windows
- Восстановление сайтов из Интернет Архива в Windows
- Как установить WhatWeb в Windows
- Установка WPScan в Windows
- Что такое MSYS2. Как пользоваться MSYS2
Ethical hacking and penetration testing
InfoSec, IT, Kali Linux, BlackArch
How to install and use Ruby on Windows
Why install Ruby
Ruby is a scripting language, that is, pre-compilation is not required to run programs. In this sense, Ruby is an analogue of PHP, Python, PERL and others.
Ruby is a fairly popular language and many interesting programs are written on it; in scope of InfoSec, the well-known WPScan, WhatWeb, Wayback Machine Downloader and others can be cited as examples.
By installing Ruby on Windows, you can run programs written in this language, as well as learn this programming language and write your own scripts.
By the way, Ruby, like PHP, Python and PERL, can be a web server module, and scripts written in this language can be used as backend of a website or service.
How to install Ruby on Windows
There you will see many installer options that differ not only in versions, but also in the composition of the downloaded files. Executable files are self-contained installers for Windows that include the Ruby language, runtime, important documentation, and more. If you do not know which version to install in order to get started with Ruby, the Ruby+Devkit * (x64) is recommended. It provides the largest number of compatible gem (Ruby packages) and installs MSYS2-Devkit along with Ruby, so gem with C-extensions can be compiled immediately after installation.
Run the downloaded file. In this window we can select the settings:
The installation folder can be left unchanged.
Add Ruby executables to your PATH – means adding a directory with Ruby executables to the system variable. This is recommended to do for in future to avoid specifying the full path to the script interpreter each time the Ruby script is run.
Associate .rb and .rbw files with Ruby installation. Thanks to this, Ruby files can be launched by double-clicking or by typing the name of the script on the command line.
Use UTF-8 as default external encoding.
I selected all three checkmarks and entered C:\Ruby26 as the installation folder:
As you can see on the next page, the Ruby package itself takes up a bit of space, but the MSYS2 development toolkit offered for installation takes up a lot of space. I highly recommend installing MSYS2 because, in addition to the ability to compile packages for Ruby mentioned above, MSYS2 provides a console environment with Linux features (something like Cygwin does, but with additional features).
Leave a checkmark on the last window to configure the MSYS2 developer tools and click Finish.
Further we are offered:
Just press ENTER to complete all three actions:
Everything is completed, to exit, press ENTER:
By the way, if you carefully watched what was happening on the screen, you might notice pacman. There really is a pacman package manager in this console environment. We will return to other functions of MSYS2 a bit later.
How to update Ruby on Windows
To upgrade to the latest patch (that is, the minor version, for example from 2.5.1 to 2.5.4), it is enough to launch a new version of the installer. Installed gem (packages from the Ruby repository) are not overwritten and will work with the new version without reinstalling. To upgrade the installation, just use RubyInstaller without Devkit. You can update Devkit separately by running the following command at the Windows command prompt:
When a new major version is released, it cannot be updated by installing it in the same directory as the previous one. For example, if the previous version of the installation is RubyInstaller-2.5.x, and the new version is RubyInstaller-2.6.x, then you need to install it either in a new directory or delete the old version and install a new one instead, since gem (programs) with C extensions are not compatible between ruby-2.5 and 2.6.
How to install and use gem on Windows
RubyGems is a package manager for Ruby. Using it, you can install various programs and their dependencies, installation can be done both from the source code on the local system, and from remote application sources.
The Ruby installation shown above also installs gem:
You should see gem help.
To display all available gem commands, run:
To install the package, run a command of the form:
More examples of installing packages will follow.
To show help about the installation command:
For example, to install the ‘rake’ program from a local directory or a remote server:
Installing the ‘rake’ package only from a remote server:
Installing ‘rake’, but only version 0.3.1, even if there are unsatisfied dependencies, do the installation in the user directory:
List gem (packages) whose name begins with ‘D’:
List local and remote gem whose name contains ‘log’:
The previous command is used to search for packages by name.
List only remote (non-local) gem whose name contains ‘log’:
View information about RubyGems:
Update all gem programs in the system:
Update local version of RubyGems:
How to install bundler
bundler is a Ruby dependency manager. This manager is useful when installing other programs written in Ruby.
To install bundler on Windows, run:
To upgrade bundle, run the command:
If you install the program from the source code and there is a Gemfile file, then go to the folder with this program and run the command in it:
This command will install all the dependencies listed in the Gemfile.
To see where gem packages are installed using bundle, use the command:
How to install the Ruby program on Windows. How to run a Ruby program on Windows
The following are a few examples of installing and using Ruby programs on Windows.
Recovering sites from the Internet Archive in Windows
Let’s start with the Wayback Machine Downloader program, which completely restores sites from the web archive.
To install Wayback Machine Downloader, just do:
To check the operability of the program, run site restoration from the Internet Archive:
The program successfully completed the work:
How to Install WhatWeb on Windows
WhatWeb identifies websites. The purpose of this program is to answer the question “What is this website?”. WhatWeb recognizes web technologies, including a content management system (CMS), blogging platforms, statistics/analytics packages, JavaScript libraries, a web server and embedded devices. WhatWeb has over 1700 plugins, each of which is for recognizing one or the other. WhatWeb also identifies version numbers, email addresses, account IDs, web platform modules, SQL errors and more.
Let’s start by searching WhatWeb in the Ruby package repository:
Only simple_whatweb found (0.4.1).
Even if it’s WhatWeb, the version is very old. Therefore, on Windows, install WhatWeb from the source code.
Unzip this folder. Open a command prompt and navigate to this folder:
Run the command:
The following command will show the help for the program:
Run the site check:
How to install WPScan on Windows
To install and run WPScan on Windows is tricky a bit, so the tutorial was divided in separate article “How to Install and Run WPScan on Windows”.
What is MSYS2. How to use MSYS2
We have already installed MSYS2 in order to gain access to compilation tools, thanks to which we can install any Ruby package. In fact, MSYS2 is based on Cygwin and contains a large number of Linux utilities.
MSYS2 provides a shell for bash, Autotools, make, gcc, pacman, sh, and many other packages. Of particular note is the pacman package manager.
To activate the MSYS2 working environment, open a command prompt or powershell console and run there:
As a result, many Linux utilities will immediately become available for work, as well as the Pacman package manager, with which you can install new packages or update existing ones. When installing packages, Pacman monitors the dependencies and installs them.
To update all packages:
To search for a package:
To list all available packages:
How to configure Ruby as an Apache module on Windows
Ruby scripts can be run in an Apache environment similar to running PHP scripts. To do this, you need to make a little configuration.
I installed the web server according to this tutorial, if you installed according to another manual, then edit the paths to fit your environment.
Open the httpd.conf file for editing, I have it located on the path C:\Server\bin\Apache24\conf\httpd.conf.
Find the line there
and add ExecCGI to it. You should get the following line (ATTENTION: you may have different the set of options):
HackWare.ru
Этичный хакинг и тестирование на проникновение, информационная безопасность
Как установить и использовать Ruby в Windows
Для чего устанавливать Ruby
Ruby — это скриптовый язык, то есть для запуска программ не требуется предварительная компиляция. В этом смысле Ruby является аналогом PHP, Python, PERL и других.
Ruby достаточно популярный язык и на нём написано много интересных программ; если говорить применительно к InfoSec, то в качестве примеров можно привести знаменитые WPScan, WhatWeb, Wayback Machine Downloader и другие.
Установив Ruby на Windows вы сможете запускать программы, написанные на этом языке, а также изучать это язык программирования и писать свои собственные скрипты.
Кстати, Ruby, наравне как и PHP, Python и PERL, может быть модулем веб-сервера и скрипты, написанные на этом языке, можно использовать в качестве программной основы веб-сайта или сервиса.
Как установить Ruby на Windows
Там вы увидите много вариантов установщика, которые различаются не только версиями, но и составом скаченных файлов. Исполнимые файлы являются самодостаточными установщиками для Windows, которые включают язык Ruby, окружение выполнения, важную документацию и прочее. Если вы не знаете, какую версию установить, чтобы начать знакомство с Ruby, то рекомендуется установщик Ruby+Devkit * (x64). Он предоставляет самое большое число совместимых gem (пакеты Ruby) и устанавливает MSYS2-Devkit вместе с Ruby, благодаря чему gem с C-расширениями могут быть скомпилированы сразу после завершения установки.
Запустите скаченный файл. В этом окне мы можем выбрать настройки:
Папку установки можно оставить без изменения.
Add Ruby executables to your PATH – означает добавить каталог с исполнимыми файлами Ruby в системную переменную. Это рекомендуется сделать, чтобы не указывать при каждом запуске скрипта Ruby полный путь до интерпретатора скриптов.
Associate .rb and .rbw files with Ruby installation — означает связать файлы с расширениями .rb и .rbw с установленным Ruby. Благодаря этому файлы Ruby можно будет запускать двойным кликом или набрав имя скрипта в командной строке.
Use UTF-8 as default external encoding – означает использовать кодировку UTF-8 в качестве внешней кодировки по умолчанию.
Я выбрал все три галочки и в качестве папку установки ввёл C:\Ruby26:
Как видно на следующей странице, сам пакет Ruby занимает немного места, но много места занимается предлагаемая к установке набор инструментов разработчика MSYS2. Я настоятельно рекомендую установить MSYS2, поскольку кроме упомянутой выше возможности компилировать пакеты для Ruby, MSYS2 обеспечивает консольное окружение с функциями Linux (примерно как это делает Cygwin, но с дополнительными возможностями).
Оставьте галочку на последнем окне для настройки инструментов разработчика MSYS2 и нажмите Finish.
Далее нам предлагается:
Просто нажимаем ENTER для выполнения всех трёх действий:
Всё завершено, для выхода нажмите ENTER:
Кстати, если вы внимательно смотрели за происходящем на экране, то могли заметить pacman. В этом консольном окружении действительно есть менеджер пакетов pacman. К другим функциями MSYS2 вернёмся чуть позже.
Подробнее о Pacman смотрите в статьях:
Как обновить Ruby на Windows
Для обновления до последнего патча (то есть минорной версии, к примеру с 2.5.1 до 2.5.4), достаточно запустить новую версию установщика. Установленные gem (пакеты из репозитория Ruby), не перезаписываются и будут работать с новой версией без переустановки. Для обновления установки достаточно использовать RubyInstaller без Devkit. Обновить Devkit можно отдельно запустив в командной строке Windows следующую команду:
При выходе новой мажорной версии её нельзя обновить установкой в ту же директорию, что и предыдущая. К примеру, если предыдущая версия установки RubyInstaller-2.5.x, а новая версия RubyInstaller-2.6.x, то её нужно установить либо в новую директорию, либо удалить старую версию и вместо неё установить новую, поскольку gem (программы) с C расширениями не совместимы между ruby-2.5 и 2.6.
Как установить и использовать gem в Windows
RubyGems — это менеджер пакетов для Ruby. С помощью него можно установить различные программы и их зависимости, установку можно делать как из исходного кода на локальной системе, так и с удалённых источников приложений.
Показанная выше установка Ruby также устанавливает и gem, чтобы в этом убедиться выполните команду:
Вы должны увидеть справку по использованию gem.
Чтобы вывести все доступные команды gem, выполните:
Чтобы установить пакет запустите команду вида:
Больше примеров по установке пакетов будет далее.
Чтобы показать справку о команде установки:
К примеру, для установки программы ‘rake’ из локальной директории или удалённого сервера:
Установка пакета ‘rake’ только с удалённого сервера:
Установка ‘rake’, но только версии 0.3.1, даже если имеются неудовлетворённые зависимости, установку сделать в пользовательскую директорию:
Вывести список gem (пакетов), чьё имя начинается на ‘D’:
Вывести список локальный и удалённых gem, чьё имя содержит ‘log’:
gem search log —both
Предыдущая команда используется для поиска пакетов по имени.
Вывести список только удалённых (не локальных) gem, чьё имя содержит ‘log’:
Просмотреть информацию о RubyGems:
Обновить все программы gem в системе:
Обновить локальную версию RubyGems:
Как установить bundler
bundler — это менеджер зависимостей Ruby. Данный менеджер пригодится при установке других программ, написанных на Ruby.
Для установки bundler в Windows выполните:
Для обновления bundle выполните команду:
Если вы устанавливаете программу из исходного кода и там присутствует файл Gemfile, то перейдите в папку с этой программой и выполните в ней команду:
Эта команда установит все перечисленные в файле Gemfile зависимости.
Чтобы увидеть, где установленные с помощью bundle пакеты gem, используйте команду:
Как установить программу Ruby в Windows. Как запустить программу Ruby в Windows
Далее рассмотрим несколько примеров установки и использования программ на Ruby в Windows.
Восстановление сайтов из Интернет Архива в Windows
Начнём с программы Wayback Machine Downloader, которая полностью восстанавливает сайты из веб архива.
Для установки Wayback Machine Downloader достаточно выполнить:
Запустим для проверки работоспособности программы восстановление сайта из Архива Интернета:
Программа успешно завершила работу:
Как установить WhatWeb в Windows
WhatWeb идентифицирует веб-сайты. Цель этой программы ответить на вопрос «Чем является этот веб-сайт?». WhatWeb распознает веб-технологии, в том числе систему управления контентом (CMS), платформы для ведения блогов, пакеты статистики/аналитики, библиоотеки JavaScript, веб-сервера и встроенные устройства. WhatWeb имеет более 1700 плагинов, каждый из которых для распознавания чего-то одного. WhatWeb также идентифицирует номера версий, email адреса, ID аккаунтов, модули веб-платформ, SQL ошибки и прочее.
Начнём с поиска WhatWeb в репозитории пакетов Ruby:
Найдено только simple_whatweb (0.4.1).
Даже если это WhatWeb, то версия очень старая. Поэтому на Windows установим WhatWeb из исходного кода.
Распакуйте эту папку. Откройте командную строку и перейдите в эту папку:
Следующая команда покажет справку по программе:
Запустим проверку сайтов:
Установка WPScan в Windows
Что такое MSYS2. Как пользоваться MSYS2
Мы установили уже MSYS2 для того, чтобы получить доступ к инструментам компиляции, благодаря которым мы сможем установить любой пакет Ruby. На самом деле MSYS2 основывается на Cygwin и содержит большое количество утилит Linux.
MSYS2 предоставляет оболочку bash, Autotools, make, gcc, pacman, sh и многие другие пакеты. Особенно следует отметить менеджер пакетов pacman.
Для активации рабочего окружения MSYS2 откройте командную строку или консоль powershell и выполните там:
В результате сразу станут доступны для работы многие утилиты Linux, а также менеджер пакетов Pacman, с помощью которого можно установить новые пакеты или обновить имеющиеся. При установке пакетов Pacman следит за зависимостями и устанавливает их.