Cd-m.ru

ПК Журнал СД-М
9 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Установка Asterisk на CentOS 7

Установка Asterisk 13.18 на CentOS 7

1. Установка CentOS на Hyper-V (VMware) сервер, настройка сети

Устанавливать Asterisk будем на CentOS 7. Для этого выбираем любое понравившееся зеркало с сайтаhttp://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1708.iso и скачиваем образ http://mirror.yandex.ru/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1708.iso (790 Мб). Подключаем образ к созданной ВМ (сама виртуальная машина должна иметь следующие параметры аппаратного обеспечения: процессор не ниже 2ГГц, память не менее 2 Гб, сетевой адаптер, дисковод компакт дисков) и выполняем загрузку с диска.

Процедура установки достаточно проста – выбираем языковые параметры и разбивку диска (используем значения по умолчанию), указываем пароль пользователя root, а также настраиваем сеть.

Небольшой нюанс при использовании старых виртуальных машин – желательно использовать при начальной установке системы legacy network adapter (в Hyper-V так и называется, в Vmware – E1000). После вышеописанных процедур по настройке сети потребуется установить Службы интеграции (Hyper-V), либо VMware tools. Для примера, рассмотрим установку VMware tools. В первую очередь установим необходимые пакеты для их развертывания:

Затем подключим виртуальный диск через ESXi с VMware tools (Guest – Install/upgrade VMware tools) и смонтируем его в нашей системе:

После выполнения последней команды выполняется скрипт, со всеми вопросами соглашаемся, нажимая Enter. После выполнения скрипта потребуется перезагрузка.

2. Установка последних обновлений ядра и окружения CentOS

После настройки сетевого интерфейса установим обновления операционной системы – ядра и его окружения с пакетами.

Затем отключим SELinux (его настройки безопасности будут мешать нашей работе и самому Астериску). Для этого: отредактируем файл /etc/selinux/config:

Заменим значение параметра SELINUX на disabled.

А также отключим брандмауэр:

Чтобы изменения вступили в силу, перезагрузим систему:

3. Загрузка исходного кода Asterisk, распаковка архивов

Для полноценной работы Астериск, помимо его исходных кодов нужны еще два основных пакета: DAHDI и LibPRI. Загрузим все три архива с исходными кодами сайта (по правилам хорошего тона, поместим исходники в папку /usr/src):

wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/libpri/libpri-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-13-current.tar.gz

Распакуем все три архива:

После распаковки возьмемся за установку необходимых пакетов. Астериск будем ставить после первых двух. Это важно (иначе не соберется).

4. Установка необходимых зависимостей для Asterisk

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

Установим также исходники нашего ядра:

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

5. Установка DAHDI и LibPRI

Начнем подготовку к установке Asterisk с установки DAHDI (Digium Asterisk Hardware Device Interface). По сути это набор драйвером к аппаратным картам фирмы Digium (разработчика Asterisk). Чаще всего используют платы потока Е1, реже – платы для оконечных устройств. Для начала установки переходим в каталог DAHDI и затем запускаем процесс компиляции и сборки:

Процесс занимает от одной до двух минут. Если в вашем сервере еще нет ни одной карты от Digium, то в конце компиляции вы получите текст следующего содержания:

List of detected DAHDI devices:

No hardware found

Необязательно вы получаете телефонию от своего оператора связи посредством канала Е1 (это может быть и sip), поэтому данному сообщению можно не придавать значения. В противном случае вы получили бы сообщение с названием вашей платы потока.
Переходим к сборке LibPRI:

Собирается практически мгновенно. На этом подготовительный процесс завершен. Переходим к установке Asterisk.

6. Запуск установки Asterisk

Вернемся в каталог с исходниками Астериска:

Если в процессе компиляции вы столкнетесь с ошибками, то придется перед повторной компиляцией очистить установочную директорию:

Если все прошло успешно, то мы увидим окно с настройками компиляции Asterisk:

Asterisk Module and Build Option Selection

Нас устроят значения по умолчанию. Нажимаем Save & Exit и ожидаем компиляции модулей по умолчанию. Этот процесс займет некоторое время (примерно 3-5 мин).
По окончании установки мы получим следующее сообщение:

Asterisk Installation Complete

Установим, как предлагается демонстрационные конфигурационные файлы:

Для обеспечения установки сценариев запуска Asterisk в /etc/init.d выполним следующую команду:

Настроим ротацию логов Астериска, чтобы не забивать место на диске:

Перейдем к запуску Астериск и проверки его работоспособности.

7. Запуск DAHDI. Запуск Asterisk, проверка работоспособности

В случае, если в нашем сервере установлены платы Digium, то предварительно нужно запустить DAHDI:

Ну и наконец, можем запустить сервис самого Астериск:

Чтобы подключиться к консоли Астериск введем команды:

В некоторой литературе вы можете видеть несколько букв v после ключа –r. Этот параметр отвечает за количество выводимой информации в консоль Астериск. Возможны уровни от 1 до 6. Например, команда

How to Install Asterisk on CentOS/RHEL 8/7

Asterisk is an open-source framework used for building communication applications. You can use it to turn a local computer or server to the communication server. It is used to power IP PBX systems, VoIP gateways, conference servers, and other solutions. It’s used by all kind of organizations worldwide and finally, but not last it is free and open source.

In this tutorial, we are going to show you how to install Asterisk on CentOS 8/7 (instructions also works on RHEL 8/7), but before we start, we will need to make some preparations so Asterisk can run smoothly after the installation.

Step 1: Disable SELinux on CentOS

To do this, SSH to your system and using your favorite command line text editor, open /etc/selinux/config and disable SELINUX.

Читать еще:  Скачать программу CloneDVD бесплатно

SELinux line should look like this:

Disable SELinux in CentOS

Now reboot your system. Once it comes back SSH again to that system.

Step 2: Install Required Packages

Asterisk has quite a few requirements that need to be installed. You can use the following yum command to install the required packages as shown.

Install Software Packages

Before we continue further, create a new user with sudo privileges called “asterisk“, we will use this user to setup asterisk on the system.

Next, install PJSIP, is a free open source multimedia communication library that implements standard based protocols such as SIP,SDP,RTP,STUN,TURN, and ICE. It is the Asterisk SIP channel driver that should improve the clarity of the calls.

To get the latest version, first let’s create a temporary directory where we will build the package from source.

Now go the PJSIP download page and grab the package or use the following wget command to download the package directly in the terminal.

Note that by the writing of this article the latest version is 2.8, this may change in future, thus make sure to use the latest version:

Once the download is complete, extract the file and change to that directory.

The next step is to prepare the package to be compiled. You can use the following command:

Configure PJSIP Source

You should not see any errors or warnings. Ensure that all dependencies are met:

Compile PJSIP Source

And now we can complete the install and link libraries with:

Install PJSIP Source

Finally, ensure that all libraries are installed and present:

You should get the following output:

Step 3: Install Asterisk on CentOS 8/7

We are now ready to initiate the installation of Asterisk. Navigate back to our

Go to the Asterisk download page and grab the latest version or you can use the following wget command to download the file in terminal.

By the writing of this tutorial, the latest Asterisk version is 16. Make sure that you are downloading the latest version of Asterisk, when you are following the steps.

Now extract the archive and navigate to the newly created directory:

This is the time to mention, that if you wish to enable mp3 support to play music while the client is on hold, you will need to install a few more dependencies. These steps are optional:

After the second step, you should get output similar to these:

Start by running the configure script to prepare the package for compiling:

If you get any missing dependencies to install them. In my case, I got the following error:

To go around this simply run:

And re-run the configure script. If all went perfectly without errors, you will see the following screenshot.

Configure Asterisk Source

Now, let’s start the build process:

After a few seconds, you should get a list of features to enable:

Asterisk Module Build

If you attempt to use music on hold feature, you will need to enable the “format_mp3” feature from “Add-ons” section. Save your list and run the following command:

Install Asterisk Source

To install the sample configuration files, use the command below:

Install Asterisk Samples

To start Asterisk on boot, use:

Update the ownership of the following directories and files:

Finally, let’s test our installation with:

You should see output similar to this one:

If you want to see a list of available commands type:

Asterisk Help

To exit the Asterisk prompt, simply type:

Asterisk will still be running in the background.

Conclusion

Now you have a running Asterisk server and you can start connecting phones and extensions and adjust your configuration per your needs. For more details how to achieve this, it is recommended to use the Asterisk Wiki page. If you have any questions or comments, please let us know in the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Related Posts

Install SVN in Linux

Secure Apache with Free Let’s Encrypt SSL Certificate on CentOS 8

SSH Server Security Practices

Install MS SQL Server on Linux

Install Google Chrome in CentOS

Install OnlyOffice Desktop in Linux

28 thoughts on “How to Install Asterisk on CentOS/RHEL 8/7”

Nice guide. It will be nice to give an example of a realtime asterisk. How to install it, create users, configure dialplan, conference,…

Beautifully written and well detailed.

In the section “will need to enable the “format_mp3” feature from the “Add-ons” section” you say to run using sudo. This results in root owning the mp3 folder and at one point the installation aborted as the asterisk user didn’t have write authority here.

Great tutorial. I am having an issue getting up and running. after the first yum install, I get: No match for argument libedit-devel, unable to find a match. This is what is really holding me up. Can you give me some feedback on this? I would sure appreciate it. Thank you in advance.

Читать еще:  Как посмотреть пароль от Инстаграмма на телефоне

Answering my own question, to get it to work, I had to issue the following command:

then when I issued: yum install libedit-devel everything worked as expected..

If you need to disable SELinux to use the app, then don’t use that. or, use another distro that not using SElinux by default.

I am still confused about why many GNU/Linux tutorial asks the reader to disable SElinux. it is bad security practice dude. just don’t use CentOS if you can’t handle SElinux.

I absolutely agree with LinuxSecSELinux should not be disabled.

It doesn’t help that Asterisk docs and Digium Support apparently suggest _disabling_ SELinux, not even changing it to permissive mode. Jeesh!

Research the contexts you need along with using permissive mode and set the contexts properly. There are situations where audit2allow can create policies with too much access, but there are policies for Asterisk PBX out there (haven’t used them myself).

How to configure file sip.conf and extendion.conf for sample test?

Can you help how to test it please, i am done in all steps , only testing & GUI for config

$ ./configure CFLAGS=»-DNDEBUG -DPJ_HAS_IPV6=1″ —prefix=/usr —libdir=/usr/lib64 —enable-shared —disable-video —disable-sound —disable-opencore-amr

I have error no such file or directory and i go with your guide step by step

Try admin/password.It should work just fine

ask me password of the asterisk

Me too did you find the solution

You must set password for asterisk user.

change to root mode and type:

and set your password.. thanks !

Can you please explain more what to do after it ask for the asterisk password?

Got something to say? Join the discussion. Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Установка Asterisk 13 из пакетов на CentOS 7 Minimal (+ настройка и защита)

1. Создаем нового пользователя и ограничиваем настройки входа по SSH

Для начала устанавливаем редактор nano:

Установили редактор nano

Добавляем пользователя и назначаем ему новый пароль:

Добавляем нового пользователя

Редактируем /etc/ssh/sshd_config. В целях безопасности, запрещаем логин из под root’а и разрешаем вход только нашему новому пользователю:

В конце файла добавляем:

Редактируем sshd_config

После чего перезагрузим службу SSH и заходим по SSH с новым пользователем:

2. Устанавливаем и настраиваем сетевой экран

По умолчанию, в Hetzner сервер предоставляется пользователю без сетевого экрана. Займемся его установкой. Нам понадобятся права суперпользователя:

Мы добавили службу сетевого экрана в автозапуск. Установили зону «public» для интерфейса eth0. Последняя команда добавляет сервисы Asterisk в исключения для того, чтобы мы могли подключаться к АТС снаружи. Вывод команды «firewall-cmd —zone=public —list-all«

Вывод firewalld

3. Подключим репозиторий EPEL и установим libcodec2

Для установки Asterisk нам понадобится пакет «codec2«, который мы можем установить из репозитория EPEL

Установка Codec2

4. Установка Asterisk

Для начала нам понадобится wget

Установку Asterisk будем производить из пакетов по инструкции https://tucny.com/telephony/asterisk-rpms

4.1 Подключаем репозиторий

Отредактируем файл /etc/yum.repos.d/tucny-asterisk.repo и установим строку «enabled=0» в разделах [asterisk-common] и [asterisk-13]. В нашем случае мы устанавливаем Asterisk версии 13. При необходимости, в этом конфигурационном файле можно отметить нужную версию:

Редактируем tucny-astreisk.repo

4.2 Установка Asterisk с репозитория

Установка Asterisk из пакетов

4.3 Добавляем Asterisk в автозапуск, запускаем и проверяем

Статус Asterisk

sip show peers

Astrerisk 13 установлен.

5. Настройка Asterisk

В нашей тестовой конфигурации мы создадим 5 внутренних номеров от 101 до 105. И настроим внутренние звонки между ними.

Для этого в файле /etc/asterisk/sip.conf добавляем наши внутренние номера в раздел [phones]:

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

В файле /etc/asterisk/extensions.conf определяем контекст «internal-calls«. Полное содержание файла:

6. Проверка Asterisk

Подключим 2 номера для проверки. Для этого отлично подойдет Zoiper for Windows. Для подключения используем IP-адрес сервера, внутренний номер и пароль. После подключения с помощью команды «sip show peers» увидим пиры:

Вывод команды sip show peers

Протестируем звонок с одного номера на другой:

zoiper_incoming_call.png

Базовая настройка выполнена.

7. Защищаем сервер Asterisk с помощью Fail2Ban

Сервер Asterisk, который находится в «открытом» интернете, постоянно подвергается попыткам примитивного взлома от «ботов«, которые пытаются подобрать пароль от SSH или подлючиться к АТС. Для борьбы с ними, необходимо:

  1. Использовать сложные пароли. Обязательно!
  2. Использовать Fail2Ban, который будет временно блокировать IP-адреса, с которых осуществляется попытка взлома.

7.1 Включаем security-log в Asterisk

Включим security-лог Asterisk и настроим чтобы он записывался в отдельный файл. Кроме этого, поменяем формат даты в логах. Для этого, раскоментируем в файле «/etc/asterisk/logger.conf» 2 строки:

Перезагрузим настройки логгера Asterisk:

7.2 Установка Fail2Ban

Для установки Fail2Ban в CentOS 7 должен быть подключен репозиторий EPEL. Мы это уже сделали в предыдущих пунктах. Установим Fail2Ban и активируем в качестве службы:

Читать еще:  Как сбросить ПИН код на Андроиде

7.3 Настройка Fail2Ban

Файл настроек лежит по адресу «/etc/fail2ban/jail.conf«. однако, разработчики рекомендуют использовать не его копию по адресу «/etc/fail2ban/jail.conf«, которая будет иметь приоритет. Итак:

В нашем примере на сервере используются 2 службы: SSH и Asterisk. Обе они поддерживают авторизацию и подвержены бруфорсу и требуют защиты. Найдем и отредактируем в файле «jail.local» 2 секции [sshd] и [asterisk]:

В параметр ignoreip можно вписать IP-адреса, которые блокировать не требуется (свои подсети и т. д.). Добавим в файл «jail.local«:

Сохраним файл и перезапустим службу fail2ban:

7.4 Проверка Fail2Ban

Для проверки работы можно использовать команду:

После некоторого времени, начинает появлятся первый «улов». На картинке снизу наблюдаем 3 заблокированных IP-адреса:

Installing Asterisk on CentOS 7

CloudwaferHQCloudwaferHQ — May 27, 2019

Asterisk is an open-source framework for building communications applications. Asterisk turns an ordinary computer into a communications server by powering IP PBX systems, VoIP gateways, conference servers and other custom solutions. Small businesses use it, large companies, call centres, carriers and government agencies, worldwide. Asterisk supports several standard voice-over IP protocols, including the Session Initiation Protocol (SIP), the Media Gateway Control Protocol (MGCP), and H.323.

In this guide, we will explain how to install Asterisk on a CentOS 7 server.

Deploying your cloud server
If you have not already registered with Cloudwafer, you should begin by getting signed up. Take a moment to create an account after which you can quickly deploy your cloud servers.

Once you have signed up, log into your Cloudwafer Client Area and deploy your Cloudwafer cloud server.

Updating System Packages
It is always recommended that you update the system to the latest packages before beginning any significant installations. This is done with the command below:

Step 1: Add SIP Ports to Config Server Firewall (CSF)
Ports 5060 and 5061 , both on TCP and UDP, are associated with the Session Initiation Protocol (SIP) by IANA. Hence, we will need to add these ports to our csf.conf file.

You can read our guide on configuring CSF on Ubuntu and CentOS for more information on CSF.

Reload CSF to enforce our changes with the command below:

Cloudwafer Asterisk CentOS 7 -1

Depending on your needs, you may want to add other related ports:

MGCP — For users that require Media Gateway Control Protocol in their configuration

RTP — Real-Time Transport Protocol. You can make further changes in the /etc/asterisk/rtp.conf file.

For users that want to use FreePBX (a web-based open-source GUI that controls and manages Asterisk:

For users that need IAX (Inter-Asterisk Exchange to allow multiple Asterisk servers to communicate with one another):

Ensure to reload CSF after making any changes.

Step 2: Install PJPROJECT
PJPROJECT is Asterisk’s SIP channel driver helping to improve call clarity and performance over older drivers. First, we need to install some build dependencies by issuing the command below:

Cloudwafer Asterisk CentOS 7 -2

Next, create a working directory for the build then navigate to that directory:

Next, using the wget tool, download the PJSIP driver source code:

Cloudwafer Asterisk CentOS 7 -4

Then proceed to extract it then navigate to the newly created directory:

Cloudwafer Asterisk CentOS 7 -5

Cloudwafer Asterisk CentOS 7 -6

Next step is to specify the compiling flags and options by issuing the command below:

Cloudwafer Asterisk CentOS 7 -7

Next, ensure that all dependencies are in place by issuing the command below:

If make dep completes successfully, then build the plugin and install the packages by issuing the command below:

You can verify that the libraries are now installed by issuing the command below:

Cloudwafer Asterisk CentOS 7 -8

Step 3: Install Asterisk
Navigate to the build directory that we created earlier then download the latest version of Asterisk 16 by issuing the commands below:

Cloudwafer Asterisk CentOS 7 -9

Next, extract the file before navigating to the new Asterisk directory, replacing 16.3.0 if needed:

Cloudwafer Asterisk CentOS 7 -10

Enable MP3 Support
To use MP3 files for Music on Hold, install Subversion and run the configuration script:

Cloudwafer Asterisk CentOS 7 -11

Cloudwafer Asterisk CentOS 7 -12

Step 4: Configure and Build Asterisk
From the build directory for Asterisk, run the configure script to prepare the Asterisk source code for compiling:

This will start the build process with a menu appearing shortly on screen, allowing you to configure the features you want to build.

To use the MP3 format with Music on Hold, you should select Add-Ons , navigating to format_mp3 and selecting it. Select additional core sound packages and Music on Hold packages in the left menu, and enable .wav format for your desired language. You can use F12 to save and exit.

Cloudwafer Asterisk CentOS 7 -13Cloudwafer Asterisk CentOS 7 -14

Next, compile Asterisk.

Cloudwafer Asterisk CentOS 7 -15

Lastly, we can now install Asterisk and install sample configuration files:

Cloudwafer Asterisk CentOS 7 -16

Configure Asterisk to start itself automatically on boot:

To test your Asterisk Connection, start Asterisk as shown below then proceed to connect to it:

To view a list of possible commands:

For more detailed instructions on configuring Asterisk, visit the Asterisk Project’s guide

0 0 голоса
Рейтинг статьи
Ссылка на основную публикацию
ВсеИнструменты