Asterisk — это сервер телефонии с открытым исходным кодом. Многие считают его ТОП-1 бесплатных АТС, распространяемых как self-hosted решение.
FreePBX — GUI с открытым исходным кодом разработанный для управления сервером Asterisk.
Помимо прочего FreeBPX в последних релизах — не только дает возможность базового управления Asterisk, но и расширяет его функционал.
В статье я опишу процесс установки Asterisk и FreePBX на сервер Ubuntu 20.04
- Choose a different version or distribution
- Introduction
- Prerequisites
- Step 1 – Disable SELinux
- Step 2 – Download Asterisk
- Step 3 – Install Asterisk Dependencies
- Step 4 – Install Asterisk
- Step 5 – Creating Asterisk User
- Step 6 – Start Asterisk
- Step 7 – Adjust the Firewall
- Is it possible to run Asterisk without special hardware?
- How do I dial from the CLI?
- Conclusion
- Перейдем к установке
Choose a different version or distribution
Introduction
Before we begin talking about how to install Asterisk on CentOS 7, let’s briefly understand – What Asterisk is?
Asterisk is a very famous and open-source PBX platform that powers IP PBX systems, conference servers, and VoIP gateways. It is being used worldwide by small businesses to huge enterprises.
It has many useful features like music on hold, call queuing, interactive voice response, conference calling, and voicemail.
In this tutorial, you will install Asterisk 20 on CentOS 7. We will also address some FAQs related to the Flask installation.
Here are some benefits of using Asterisk:
- Cost-effective: Asterisk is open-source, which means it’s free to use and can be modified to fit specific needs. This can make it an affordable alternative to commercial communication solutions.
- Flexibility: Asterisk can be integrated with a variety of technologies and programming languages, including PHP, Python, and Perl. This means developers can build a wide range of communication applications tailored to their specific needs.
- Customizability: Asterisk is highly customizable and can be configured to work with almost any type of telephony hardware or software. This makes it easy to integrate existing systems with new applications.
Prerequisites
- You have to be logged in as a user with sudo privileges.
- You also have to update CentOS 7 and install the development tools as they will be helpful in compiling the Asterisk source code:
sudo yum update
sudo yum groupinstall core base "Development Tools"Step 1 – Disable SELinux
Asterisk doesn’t function properly if SELinux is set to the enforcing mode.
In order to make Asterisk work, you’ll have to open /etc/selinux/config file and set SELINUX=disabled
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
# targeted - Targeted processes are protected,
# mls - Multi Level Security protection.
SELINUXTYPE=targetedSave the above file and reboot the system.
sudo shutdown -r nowOn completion of the reboot, make sure getenforce command returns Disabled:
getenforceOutput
DisabledStep 2 – Download Asterisk
1) We’ll start by downloading Asterisk in the /usr/src directory, which is a common place to keep source files.
cd /usr/src/sudo wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-20-current.tar.gzsudo tar zxf asterisk-20-current.tar.gz5) Before continuing, change the Asterisk source directory with the help of the commands given below:
cd asterisk-20.*/Step 3 – Install Asterisk Dependencies
1) Now, you’ve to download the Mp3 sources, required to build the Mp3 module and use the Mp3 files on Asterisk:
sudo contrib/scripts/get_mp3_source.sh2) After that, you need to install all the missing dependencies with the help of install_prereq script;
sudo contrib/scripts/install_prereq installOutput
#############################################
## install completed successfully
#############################################Step 4 – Install Asterisk
sudo ./configure --libdir=/usr/lib64 --with-jansson-bundled
2) Now you’ve to select the modules you want to compile and install.
sudo make menuselectSince all Mp3 files have already been downloaded, you need to instruct Asterisk to build the Mp3 module by selecting format_mp3:

4) Now hit F12 to save and exit, or simply switch to the Save and Exit button then press Enter.
5) Use the make command to commence the compilation process:
sudo make -j2The build might take some time to finish, based on your system, you can modify the -j flag as per the number of your processor cores.

sudo make install8) When the installation is complete, you’ll see a similar output as below:

9) Now that Asterisk has been installed, you need to install the sample configuration files.
sudo make samples11) Alternatively, you can use the basic PBX configuration files:
sudo make basic-pbxsudo make configsudo ldconfigStep 5 – Creating Asterisk User
sudo adduser --system --user-group --home-dir /var/lib/asterisk --no-create-home asteriskAST_USER="asterisk"
AST_GROUP="asterisk"sudo usermod -a -G dialout,audio asterisksudo chown -R asterisk: /var/{lib,log,run,spool}/asterisk /usr/lib64/asterisk /etc/asterisk
sudo chmod -R 750 /var/{lib,log,run,spool}/asterisk /usr/lib64/asterisk /etc/asteriskStep 6 – Start Asterisk
sudo systemctl start asterisk2) Connect to Asterisk Command Line Interface (CLI) in order to check for its proper functioning
sudo asterisk -vvvr3) This is how the Asterisk CLI prompt will look like:

sudo systemctl enable asteriskStep 7 – Adjust the Firewall
Once Asterisk is installed successfully, configure the firewall to allow the traffic on specific ports.
Note: If the firewall is disabled on your system, you may skip this section.
<?xml version="1.0" encoding="utf-8"?>
<service version="1.0"> <short>asterisk</short> <description>Asterisk is a software implementation of a telephone private branch exchange (PBX).</description> <port protocol="udp" port="10000-10100"/> <port protocol="udp" port="4569"/> <port protocol="udp" port="2727"/> <port protocol="udp" port="5060-5061"/>
</service>3) With the next set of commands, Save and Apply the firewall rules:
sudo firewall-cmd --add-service=asterisk --permanent
sudo firewall-cmd --reload3) Next, check whether the new firewall settings have been saved properly:
sudo firewall-cmd --list-allOutput
public (active) target: default icmp-block-inversion: no interfaces: eth0 sources: services: ssh dhcpv6-client asterisk ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:Is it possible to run Asterisk without special hardware?
Yes, PSTN hardware like Digium cards or ISDN adapters is not a requirement. For some applications, like the conferencing application, you need hardware to get timer support, but that’s possible in many ways. Asterisk works well as a VOIP and voicemail server with SIP, MGCP, IAX, and H.323 support both with and without PSTN connectivity.
How do I dial from the CLI?
You’ll need chan_oss for that. chan_oss provides a “dial” command from the CLI that connects the soundcard (via chan_oss) to the outgoing line. By including the module chan_oss, you’ll find a new “dial” command on the CLI.
Conclusion
If you have any queries, please leave a comment below, and we’ll be happy to respond to them for sure.
Перейдем к установке
По непонятной мне причине, Asterisk по прежнему необходимо компилировать из исходников скачанных с сайта. Хотя в репозиториях Canonical появился пакет с asterisk с возможностью установить через пакетный менеджер, но либо я не разобрался в теме, либо он относительно урезанный. В любом случае установка из исходников примерно одинаково отработает на любой системе.
Для начала устанавливаем зависимости для компилятора:
apt-get install unzip git gnupg2 curl libnewt-dev libssl-dev libncurses5-dev subversion libsqlite3-dev build-essential libjansson-dev libxml2-dev uuid-dev subversion -yСкачиваем самый последний релиз астериска (на момент написания статьи — самым свежим был 19)
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-19-current.tar.gzПо завершению загрузки — распаковываем
tar zxf asterisk-19-current.tar.gzПереходим в распакованный каталог и устанавливаем требуемые зависимости с помощью команд:
cd asterisk-19.2.0/
contrib/scripts/get_mp3_source.sh
contrib/scripts/install_prereq installДалее запускаем конфигурацию астериска:
Выбираем нужные нам модули Asterisk:
Навигация с помощью стрелок и tab, выбор с помощью Enter
Не забываем выбрать русские звуки:

Экстра саундов на русском нет, потому придется довольствоваться английским:
Клацаем «save & exit» в нижнем правом углу.
Как только конфигурация завершена — собираем астериск командой:
И устанавливаем Asterisk:
Устанавливаем конфиги, примеры и модули с помощью следующих команд:
make samples
make config
ldconfigПереходим к настройке.
По умолчанию Asterisk запускается от пользователя root, но это не круто, потому сначала исправляем это упущение, создав пользователя и группу пользователя asterisk:
groupadd asterisk
useradd -r -d /var/lib/asterisk -g asterisk asteriskДобавляем нужные права для группы астериск:
usermod -aG audio,dialout asteriskИ выдаем права на нужные каталоги:
chown -R asterisk.asterisk /etc/asterisk
chown -R asterisk.asterisk /var/{lib,log,spool}/asterisk
chown -R asterisk.asterisk /usr/lib/asteriskРедактируем конфигурацию, созданную по умолчанию, устанавливаем пользователем по умолчанию — asterisk, открываем для редактирования файл конфигурации:
nano /etc/default/asteriskНаходим и раскоменчиваем строки:
AST_USER="asterisk"
AST_GROUP="asterisk"Cохраняем и открываем следующий файл:
nano /etc/asterisk/asterisk.confrunuser = asterisk ; The user to run as.
rungroup = asterisk ; The group to run as.В самом низу файла раскоменчиваем и приводим вот к такому виду:
[files]
astctlpermissions = 0660
astctlowner = asterisk
astctlgroup = asterisk
astctl = asterisk.ctlСохраняем, закрываем, перезапускаем астериск и добавляем его в автозагрузку:
systemctl restart asterisk
systemctl enable asteriskПроверяем статус службы:
systemctl status asteriskВ некоторых случаях в статусе можно получить ошибку:
radcli: rc_read_config: rc_read_config: can't open /etc/radiusclient-ng/radiusclient.conf: No such file or directoryНе беда, пофиксить можно вот так:
sed -i 's";\[radius\]"\[radius\]"g' /etc/asterisk/cdr.conf
sed -i 's";radiuscfg => /usr/local/etc/radiusclient-ng/radiusclient.conf"radiuscfg => /etc/radcli/radiusclient.conf"g' /etc/asterisk/cdr.conf
sed -i 's";radiuscfg => /usr/local/etc/radiusclient-ng/radiusclient.conf"radiuscfg => /etc/radcli/radiusclient.conf"g' /etc/asterisk/cel.confСнова перезапускаем asterisk и проверяем статус, всё должно быть хорошо:

Проверяем что всё удачно запустилось — перейдя в консоль:
Если вы видите такое сообщение — то установка выполнена успешно:

Для выхода из консоли набираем:
Для установки FreePBX нужен Apache Webserver, MySQL (MariaDB) и PHP 7.2.
По умолчанию в Ubuntu 20.04 устанавливается PHP версии 7.4, потому сначала добавляем нужные репозитории:
apt-get install software-properties-common -y
add-apt-repository ppa:ondrej/php -yТеперь устанавливаем сами пакеты:
apt-get install apache2 mariadb-server libapache2-mod-php7.2 php7.2 php-pear php7.2-cgi php7.2-common php7.2-curl php7.2-mbstring php7.2-gd php7.2-mysql php7.2-bcmath php7.2-zip php7.2-xml php7.2-imap php7.2-json php7.2-snmp -yСкачиваем дистрибутив FreePBX (на момент написания статьи был 15)
wget http://mirror.freepbx.org/modules/packages/freepbx/freepbx-15.0-latest.tgztar -xvzf freepbx-15.0-latest.tgzПереходим в каталог и устанавливаем пакеты Node.js:
cd freepbx
apt-get install nodejs -yУстанавливаем нужные зависимости:
В результате вы должны получить сообщение об успешной установке:

Далее меняем пользователя в Apache на asterisk и разрешаем allowoverride:
sed -i 's/^\(User\|Group\).*/\1 asterisk/' /etc/apache2/apache2.conf
sed -i 's/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.confУвеличиваем upload_max_filesize в php.ini с помощью команд:
sed -i 's/\(^upload_max_filesize = \).*/\120M/' /etc/php/7.2/apache2/php.ini
sed -i 's/\(^upload_max_filesize = \).*/\120M/' /etc/php/7.2/cli/php.iniВключаем Apache rewrite и перезапускаем сервис:
a2enmod rewrite
systemctl restart apache2
На этом настройка закончена.







