Обзор asterisk rest interface (ari)

Asterisk chan_pjsip configuration

Now, let’s configure Asterisk’s PJSIP channel driver to use TLS.

In the pjsip.conf configuration file, you’ll need to enable a TLS-capable transport.  An example of one would resemble:

Note the protocol, cert_file, priv_key_file, and method options.  Here, we’re using the TLS protocol, we’re specifying the keys that we generated earlier for cert_file and priv_key_file and we’re setting the method to SSLv23.

Next, you’ll need to configure a TLS-capable endpoint.  An example of one would resemble:

Note the media_encryption option for the endpoint.  In this case, we’ve configured an endpoint that will be using SDES encryption for RTP.

You might be tempted to add a transport=transport-tls to the endpoint but in pjproject versions at least as late as 2.4.5, this will cause issues like Connection refused in a few situations.  Let pjproject do the transport selection on its own.  If you still see issues, set rewrite_contact = yes in the endpoint configuration.

Платформа IT инфраструктуры

Обстановка в подавляющем большинстве компаний нашей с вами родины сложилась следующим образом: Везде Windows. На компьютерах Windows. На серверах Windows. Ноутбуки продаются с предустановленной Windows. Современные недорогие планшеты и те — на Windows. Все полезные и необходимые программы для бизнеса написаны для работы в Windows.

Хорошо это или плохо? Речь сейчас не об этом.

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

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

Заведение первых номеров

Для первой настройки достаточно завести 2 номера с возможностью подключения по SIP.

Создаем правило обработки вызова (контекст). Открываем следующий файл:

И добавляем в него следующее:

exten => _XXXX,1,Dial(SIP/$,,m)

* создаем контекст с именем outcaling для четырехзначных номеров (XXXX) с вызовом по SIP по внутреннему номеру.

Открываем следующие конфигурационный файл:

И добавляем в него два внутренних номера (extensions):

type=friend regexten=1001 secret=1234 context=outcaling host=dynamic caller disallow=all allow=alaw allow=ulaw language=ru callgroup=1 pickupgroup=1 qualify=yes canreinvite=yes call-limit=4 nat=no

type=friend regexten=1002 secret=1234 context=outcaling host=dynamic caller disallow=all allow=alaw allow=ulaw language=ru callgroup=1 pickupgroup=1 qualify=yes canreinvite=yes call-limit=4 nat=no

  • , — имена для обозначения номеров.
  • type — типы проверки номеров. Могут быть peer, user или friend. Peer — вызовы сопоставляются с IP-адресами и номерами портов. User — проверка username. Friend — включает возможности peer и user (проверка username и IP-адреса источника) и лучше всего подходит для телефонов и телефонных программ.
  • regexten — добавочный номер. Если не задан, используется имя.
  • secret — пароль для аутентификации.
  • context — контекст или группа правил.
  • host — IP-адрес или имя клиента. Для автоматической регистрации используем dynamic.
  • callerid — идентификатор пользователя при звонке.
  • disallow — запрещает кодеки (задается перед параметром allow).
  • allow — разрешает кодеки. alaw и ulaw — алгоритмы для кодеков g711.
  • language — код используемого языка.
  • callgroup — задает группу устройства (для возможности перехвата).
  • pickupgroup — задает перечень групп, которые можно перехватывать.
  • qualify — включает или отключает периодическую проверку подключенного клиента.
  • canreinvite — включает или отключает прохождение голосового RTP трафика через Asterisk. Устанавливать, только если клиент поддерживает функцию SIP re-invites.
  • call-limit — ограничение количества одновременных вызовов.
  • nat — устанавливается в yes, если клиент находиться за NAT.

systemctl restart asterisk

Звонки с/на Skype

Для запуска Skype в консольном Linux используем Xvfb (X Virtual Frame Buffer) и для настройки Skype с другой машины — x11vnc:

apt-get install xvfb x11vnc
dpkg -i skype.deb

Для работы SipToSis необходима Java версии не ниже 1.5.

sudo add-apt-repository ppa:webupd8team/java 
sudo apt-get update

Установим java:

sudo apt-get install oracle-java7-installer

Разархивируем в и проставим на исполняемый файл:

chmod +x /etc/siptosis/SipToSis_linux

man hier не согласится с этим

Теперь настроим asterisk.

В добавим:

username=Skype
type=friend
context=Skype
secret=
host=dynamic
nat=no
dtmfmode=auto
canreinvite=no
incominglimit=1
outgoinglimit=1
call-limit=1
busylevel=1

В добавим

exten => 1001,1,Dial(SIP/Skype/echo123)

И перезагрузим asterisk.

sudo /etc/init.d/asterisk restart

Теперь правим конфиг SipToSis:

sudo nano /etc/siptosis/siptosis.cfg

Закомментируем блок настроек, начинающийся с «#Sample AUTO config with NO registration»
Раскомментируем блок «#Sample Asterisk registration example», поправим:

host_port=5070
contact_url=sip:Skype@127.0.0.1:5070
from_url="Skype" <sip:Skype@127.0.0.1:5060>
username=Skype
realm=asterisk
passwd=
expires=300
do_register=yes
minregrenewtime=120
regfailretrytime=15

Запускаем:

sudo /usr/bin/Xvfb :101 -ac &
sudo DISPLAY=:101 /usr/bin/skype &
sudo x11vnc -display :101 &

Подключаемся с другой машины (в моем случае, с Windows XP через VNC Viewer), вводим в Skype логин-пароль, отключаем все лишнее.

Теперь запускаем :

DISPLAY=:101 /etc/siptosis/SipToSis_linux

Если все сделано правильно, SipToSis запустится и попытается подключиться к Skype. Skype выдаст вопрос — разрешить ли подключение. Разрешаем и ставим галку «запомнить».

Проверяем: набираем с подключенного к Asterisk клиента 1001 — мы должны услышать тестовый звонок Skype.

Чтобы принимать входящие звонки, в прописываем соответствующее правило. Например:

*,sip:user1@127.0.0.1:5060

-перенаправлять все входящие звонки Skype SIP-юзеру «user1».

Естественно, нужно создать в контекст «», в котором разрешить звонки на этот extension.

FreePBX

Создаем пользователя Asterisk и задаем права пользователя.

 useradd -m asterisk &&
 chown asterisk.asterisk /var/run/asterisk &&
 chown -R asterisk.asterisk /etc/asterisk &&
 chown -R asterisk.asterisk /var/{lib,log,spool}/asterisk &&
 chown -R asterisk.asterisk /usr/lib64/asterisk &&
 chown -R asterisk. /var/www/

Настроим httpd (Apache)

 cp /etc/php.ini /etc/php.ini_orig &&
 sed -ie 's/\;date\.timezone\ \=/date\.timezone\ \=\ "Europe\/Minsk"/g' /etc/php.ini &&
 sed -i 's/\(^upload_max_filesize = \).*/\120M/' /etc/php.ini &&
 cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf_orig &&
 sed -i 's/^\(User\|Group\).*/\1 asterisk/' /etc/httpd/conf/httpd.conf &&
 rm -rf /var/www/html

Подготовим MySQL

Подготовка базы данных Asterisk в MySQL.

Выполните по очереди следующие команды:

 service mysqld restart
 mysql -u root -e "CREATE DATABASE IF NOT EXISTS asterisk DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;"
 mysql -u root -e "CREATE DATABASE IF NOT EXISTS asteriskcdrdb DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;"

Зададим права на использование БД MySQL

Замените asteriskuser на имя пользователя, которое вам нравится. Например: YOURUSER@localhost. Можно оставить как есть.

 mysql -u root -e "GRANT ALL PRIVILEGES ON asterisk.* TO asteriskuser@localhost IDENTIFIED BY '123qweasdASD';"
 mysql -u root -e "GRANT ALL PRIVILEGES ON asteriskcdrdb.* TO asteriskuser@localhost IDENTIFIED BY '123qweasdASD';"
 mysql -u root -e "flush privileges;"
 mysqladmin password 123qweasdASD

Запустим Asterisk и установим FreePBX.

Если в предыдущем пункте вы задали собственное имя пользователя, замените asteriskuser на него. Например: –username=YOURUSER

 ./start_asterisk start
 cd /usr/src/freepbx
 ./install_amp --installdb --dbhost=localhost --username=asteriskuser --password=123qweasdASD
 amportal a ma reload
 amportal a ma refreshsignatures
 amportal chown
 echo "/usr/local/sbin/amportal start" >> /etc/rc.local
 ln -s /var/lib/asterisk/moh /var/lib/asterisk/mohmp3
 amportal restart

Installing Sangoma Driver (called ‘Wanpipe’)

The following instructions will guide you through the Installation of the Sangoma Wanpipe driver on your server that contains all required software pacakges already installed(i.e. Asterisk, DAHDI, Libpri).

  1. Download the latest official release of the Sangoma Wanpipe Driver
  2. Un-compress the download Wanpipe driver (.tgz file) located in /usr/src

    1. tar xvfz wanpipe-current.tgz
    2. cd wanpipe-<version>/
  3. Install the Sangoma Wanpipe driver by typing the following in the newly created wanpipe-<version> directory:-> ./Setup install

    You will be guided through a series of prompts through the rest of the installation process.You will notice the Wanpipe driver installation splash screen next. Press ‘y’ to continueYou will be presented with a dependency check with pass/fail results.  If there are any failures, you must exist and install missing dependency manually.Press to continuePress on the following screen for default kernel source location.  If there are any error messages that result, that means you are missing your Linux kernel development packages.This also means that during the ‘Preparing your Operating system for software packages’ step above has failed to download your kernel-devel packages. If this happens you must search online for the kernel-devel packages for your kernel, then download and install using (rpm -i…)

    Press to continue

    Next you will be presented with 7 different options on how to install the Wanpipe driver.Select option 2 to install the Wanpipe driver for AsteriskYou will be asked to provide the location of your DAHDI software package. If you have downloaded and installed DAHDI in /usr/src/, simply press the number pertaining to the location.In the example below, Press 1.In this example, the user has dahdi version 2.7.0 installed on their systemIf your DAHDI installation lives in another directory, press ‘m’ then manually enter the full pathIf you have multiple DAHDI versions on your system, select the correct one.(to find out which version of dahdi is installed on your system simply type dahdi_cfg -vvv command in another Linux window)The Wanpipe driver will now start to compile on your Linux operating system.Press ‘y’ to proceedPress to continue

    Press to continue he example above is for an a108 8 port E1/T1 cardcontinue to press as seen belowpress to continueYou should end up with the following screen. If you see error messages, then you are missing system dependencies.  continue to press when asked.Press ‘y’ to install Wanpipe start scriptsThe following screen indicates that the Wanpipe driver has completed installation on your server and is now ready to start Configuring your Sangoma hardware on your systemPress ‘y’ to configure all Sangoma hardware installed on server. If you have installed Wanpipe to upgrade from a previous version, you must exit installation now because if you continue you will overwrite all previous configuration If you have not installed your Sangoma hardware yet, you can exit the installation, install hardware and continue by typing wancfg_dahdi command to start configuration script.

    The on-screen prompts that present next will be unique to your Sangoma hardware and specific to your telco settings.We will not show these screens here, but if you wish to see more details on what screens would show next, please visit the specific wancfg_dahdi pages for detailsAfter you have completed the configuration section of your Sangoma hardware, the following summary screen will be presented.

    Example from configuration of 1 analog cardSelect option 3 below to save and stop Asterisk & Wanpipe (if already running). Any new configuration will apply only after restarting

    Select option 1 to start Wanpipe on system boot. If your server ever reboots unintentionally, you will want the driver to automatically start in order to have your server back in production without manual intervention

    Select option 1 (YES) to have ‘dahdi_cfg’ run after the Wanpipe driver starts. This step configures on Wanpipe ports for dahdi You have now fully installed and configured your Sangoma Hardware for your Asterisk server!To verify that you have successfully installed the Sangoma Wanpipe driver by typing the following command in your Linux command line:-> wanrouter hwprobeYou should see details of your Sangoma hardware auto-detected in your system.  If you see an error message, this means the Wanpipe driver was NOT installed correctly.  Please open /var/log/messages file for error details 

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

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

Adblock
detector