Экспорт / импорт GPG ключей generate

Список ключей
gpg –list-keys
Проверить ключи
gpg –check-sigs B33B4659
Экспорт открытого ключа (gpg id=BD52654B)в файл.
gpg --export -a BD52654B > public.asc

Экспорт приватного ключа в файл.

gpg --export-secret-keys -a BD52654B > secret.asc

 

Импорт открытого ключа из файла.

gpg --import public.asc
or gpg --allow-non-selfsigned-uid --import public.asc

Импорт закрытого ключа из файла.

gpg --allow-secret-key-import --import secret.asc
or gpg  --allow-non-selfsigned-uid --allow-secret-key-import --import secret.asc

Отзываем ключ

gpg –gen-revoke BD52654B

Удаляем ключи, сначала приватный затем паблик

gpg –delete-secret-key BD52654B

gpg –delete-key BD52654B


Skip to end of metadata

Go to start of metadata

This is a quick step-by-step guide to generating a GPG Key that can be used to sign FreePBX Modules.

[root@localhost devtools]# gpg --gen-key
gpg (GnuPG) 2.0.14; Copyright (C) 2009 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n>  = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0) 1y
Key expires at Tue 17 Nov 2015 03:43:38 PM AEST
Is this correct? (y/N) y
GnuPG needs to construct a user ID to identify your key.
Real name: Ed Led Ovum
Email address: edled@ovum.com
Comment: Ovum.com FreePBX Module Signing Key
You selected this USER-ID:
"Ed Led Ovum (Ovum.com FreePBX Module Signing Key) <edled@ovum.com>"
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.
can't connect to `/root/.gnupg/S.gpg-agent': No such file or directory
You don't want a passphrase - this is probably a *bad* idea!
I will do it anyway.  You can change your passphrase at any time,
using this program with the option "--edit-key".
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: key E407B7AB marked as ultimately trusted
public and secret key created and signed.
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0  valid:   4  signed:   1  trust: 0-, 0q, 0n, 0m, 0f, 4u
gpg: depth: 1  valid:   1  signed:   0  trust: 0-, 0q, 0n, 1m, 0f, 0u
gpg: next trustdb check due at 2015-11-17
pub   2048R/E407B7AB 2014-11-17 [expires: 2015-11-17]
Key fingerprint = 7054 A588 0D84 AFF9 D449  626B 9503 530A E407 B7AB
uid                  Ed Led Ovum (Ovum.com FreePBX Module Signing Key) <edled@ovum.com>
sub   2048R/19663421 2014-11-17 [expires: 2015-11-17]
[root@localhost devtools]#

If the machine freezes after saying ‘We need to generate a lot of random bytes’, this is often because the machine does not have enough entropy to generate a secure random number. This is extremely common on Virtual Machines. There are several workarounds for this, but the best thing to do is to generate your key on raw hardware, with a reasonably recently Intel or AMD CPU that has hardware random number generation.

Please feel free to ask in IRC for further assistance if you’re stuck.

The ‘pub’ line is your new Key. Whilst you can use that for other things, it’s probably best to keep it only for signing FreePBX Modules.  Note that if this key is ever detected as compromised, it will be revoked (by us) and all modules that key has signed will be unusable. Take care of it, and back it up!

After you’ve generated the key, and you’re happy with it, you then need to publish it to the global Web Of Trust network. This is done simply with the following command:

[root@localhost devtools]# gpg --send-keys E407B7AB
gpg: sending key E407B7AB to hkp server keys.gnupg.net
[root@localhost devtools]#

You don’t need to specifically send it to any one keyserver, as they transparently replicate changes amongst themselves. However, if you’re unable to reach that cluster for some reason, Ubuntu offers a keyserver on port 80, and you can explicitly send your key to that host with the following command:

[root@localhost devtools]# gpg --keyserver hkp://keyserver.ubuntu.com:80 --send-keys E407B7AB
gpg: sending key E407B7AB to hkp server keyserver.ubuntu.com
[root@localhost devtools]#

As above, you only need to export your key to ONE keyserver, and they will share it amongst themselves.

It’s a good idea to keep note of the initial server you sent the key to when sending a request for FreePBX signing otherwise you will have to wait up to 24 hours for keys to replicate.

Now that key is out in the wild, you can request it be Signed by FreePBX or use it locally!.

Не забываем после того как ключ будет добавлен в белый список Sangom

делаем команду

gpg --keyserver hkp://keyserver.ubuntu.com:80 --refresh-keys 

You will see ‘Updated: 1’ when our signature has propagated to your machine.

voipmonitor install

mostly from here https://www.voipmonitor.org/doc/Centos_7

yum install subversion mtr rrdtool unixODBC-devel mysql-devel libogg libogg-devel vorbis-tools libvorbis libvorbis-devel libpcap-devel zlib-devel

#GUI
cd /var/www/html 
wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&allowed&phpver=54" -O w.tar.gz
tar xzf w.tar.gz 
mv voipmonitor-gui*/* ./
rm -f index.html
chown nginx /var/spool/voipmonitor/
wget http://sourceforge.net/projects/voipmonitor/files/wkhtml/0.10.0_rc2/wkhtmltoimage-x86_64 -O "/var/www/html/bin/wkhtmltoimage-x86_64"
chmod +x "/var/www/html/bin/wkhtmltoimage-x86_64"
wget http://sourceforge.net/projects/voipmonitor/files/wkhtml/0.10.0_rc2/wkhtmltopdf-x86_64 -O "/var/www/html/bin/wkhtmltopdf-x86_64"
chmod +x "/var/www/html/bin/wkhtmltopdf-x86_64"
wget http://voipmonitor.org/ioncube/x86_64/ioncube_loader_lin_5.6.so -O /usr/lib64/php/modules/ioncube_loader_lin_5.6.so
echo "zend_extension = /usr/lib64/php/modules/ioncube_loader_lin_5.6.so" > /etc/php.d/01_ioncube.ini
chmod 755 /usr/lib64/php/modules/ioncube_loader_lin_5.6.so

chown -R nginx /var/www/html
setenforce 0
systemctl restart php-fpm
systemctl restart nginx

 

 

 

 

 

 

 

tcpdump usage examples

In most cases you will need root permission to be able to capture packets on an interface. Using tcpdump (with root) to capture the packets and saving them to a file to analyze with Wireshark (using a regular account) is recommended over using Wireshark with a root account to capture packets on an “untrusted” interface. See the Wireshark security advisories for reasons why.

See the list of interfaces on which tcpdump can listen:

tcpdump -D

Listen on interface eth0:

tcpdump -i eth0

Listen on any available interface (cannot be done in promiscuous mode. Requires Linux kernel 2.2 or greater):

tcpdump -i any

Be verbose while capturing packets:

tcpdump -v

Be more verbose while capturing packets:

tcpdump -vv

Be very verbose while capturing packets:

tcpdump -vvv

Be verbose and print the data of each packet in both hex and ASCII, excluding the link level header:

tcpdump -v -X

Be verbose and print the data of each packet in both hex and ASCII, also including the link level header:

tcpdump -v -XX

Be less verbose (than the default) while capturing packets:

tcpdump -q

Limit the capture to 100 packets:

tcpdump -c 100

Record the packet capture to a file called capture.cap:

tcpdump -w capture.cap

Record the packet capture to a file called capture.cap but display on-screen how many packets have been captured in real-time:

tcpdump -v -w capture.cap

Display the packets of a file called capture.cap:

tcpdump -r capture.cap

Display the packets using maximum detail of a file called capture.cap:

tcpdump -vvv -r capture.cap

Display IP addresses and port numbers instead of domain and service names when capturing packets (note: on some systems you need to specify -nn to display port numbers):

tcpdump -n

Capture any packets where the destination host is 192.168.1.1. Display IP addresses and port numbers:

tcpdump -n dst host 192.168.1.1

Capture any packets where the source host is 192.168.1.1. Display IP addresses and port numbers:

tcpdump -n src host 192.168.1.1

Capture any packets where the source or destination host is 192.168.1.1. Display IP addresses and port numbers:

tcpdump -n host 192.168.1.1

Capture any packets where the destination network is 192.168.1.0/24. Display IP addresses and port numbers:

tcpdump -n dst net 192.168.1.0/24

Capture any packets where the source network is 192.168.1.0/24. Display IP addresses and port numbers:

tcpdump -n src net 192.168.1.0/24

Capture any packets where the source or destination network is 192.168.1.0/24. Display IP addresses and port numbers:

tcpdump -n net 192.168.1.0/24

Capture any packets where the destination port is 23. Display IP addresses and port numbers:

tcpdump -n dst port 23

Capture any packets where the destination port is is between 1 and 1023 inclusive. Display IP addresses and port numbers:

tcpdump -n dst portrange 1-1023

Capture only TCP packets where the destination port is is between 1 and 1023 inclusive. Display IP addresses and port numbers:

tcpdump -n tcp dst portrange 1-1023

Capture only UDP packets where the destination port is is between 1 and 1023 inclusive. Display IP addresses and port numbers:

tcpdump -n udp dst portrange 1-1023

Capture any packets with destination IP 192.168.1.1 and destination port 23. Display IP addresses and port numbers:

tcpdump -n "dst host 192.168.1.1 and dst port 23"

Capture any packets with destination IP 192.168.1.1 and destination port 80 or 443. Display IP addresses and port numbers:

tcpdump -n "dst host 192.168.1.1 and (dst port 80 or dst port 443)"

Capture any ICMP packets:

tcpdump -v icmp

Capture any ARP packets:

tcpdump -v arp

Capture either ICMP or ARP packets:

tcpdump -v "icmp or arp"

Capture any packets that are broadcast or multicast:

tcpdump -n "broadcast or multicast"

Capture 500 bytes of data for each packet rather than the default of 68 bytes:

tcpdump -s 500

Capture all bytes of data within the packet:

tcpdump -s 0

 

backup mysql with SELECT INTO FILE

  1. Create  ssh key for direct access

 

2. mkdir /mysqldump
3. chown -R mysql. mysqldump/

4. yum install mutt

 

#!/bin/sh

date1=`date -d “yesterday” ‘+%Y-%m-%d’`
date2=`date -d “2 days ago” ‘+%Y-%m-%d’`

#creating dump
mysql -uasterisk -ppassword asterisk -e “SELECT calldate, clid, src, dst, dcontext, lastapp, lastdata, duration, billsec, disposition, channel, dstchannel, amaflags, accountcode, uniqueid, userfield, answer, end FROM cdr WHERE calldate BETWEEN ‘$date2’ AND ‘$date1’ INTO OUTFILE ‘/mysqldump/cdrast.txt'”
# login to remote server
ftp -n -i -v 10.1.2.43 <<EOF
user aster01 fsklnfss45
put /mysqldump/cdrast01.txt cdrast01.txt
quit
EOF

#email
echo “Check it out” | mutt -s “subject 10.1.0.5 mysql dump” — shurubov@tbm.ru

on the other server:

mysql -uroot -pvoip2voip asterisk -e “LOAD DATA INFILE ‘/home/cdrdump.txt’ INTO TABLE cdr (calldate, clid, src, dst, dcontext, lastapp, lastdata, duration, billsec, disposition, channel, dstchannel, amaflags, accountcode, uniqueid, userfield, answer, end)”
rm /home/cdrdump.txt
mysql -uroot -ppassword asterisk -e “ANALYZE TABLE cdr”

vsftpd install

yum install vsftpd

systemctl enable vsftpd

 

/etc/vsftpd/vsftpd.conf

anonymous_enable=NO

local_enable=YES

chroot_local_user=YES

local_root=/home/aster01
userlist_enable=YES
userlist_file=/etc/vsftpd/user_list
userlist_deny=NO

 

useradd user

passwd user

chmod a-w /home/user

 

systemctl start vsftpd

Editor SED

Потоковый редактор SED

 

(sed -i.bak ‘s/local_time.ntp_server1 = /local_time.ntp_server1 = ntp.tbm.ru/g’ 0015*.cfg

find /tftpboot/ -type f | xargs sed -i ‘s/tftp:\/\/10.1.2.56/tftp:\/\/10.1.2.43/g’

)

Введение

Команда sed – это редактор потока данных (StreamEDitor) для автоматического редактирования текстов. “Редактор потока” – в том смысле, что может редактировать входящий поток данных непрерывно, скажем, в составе программного канала (pipe). Автоматически – это значит, что, как только вы зададите правила редактирования, дальнейшее происходит без вашего утомительного участия. Другими словами, редактор sed не является интерактивным.

Программа sed сложнее, чем те команды, что мы уже успели рассмотреть в предыдущих статьях цикла HuMan. В ее составе арсенал собственных команд, поэтому, дабы избежать тавтологии и путаницы, в этой статье команда sed впредь будет именоваться “программой” или “редактором”, а команды редактора sed – просто командами.

Программа sed способна выполнять сложные задания, и нужно потратить время, чтобы научиться эти задания формулировать.

Но наряду со сложными действиями, у команды sed есть простые, но весьма полезные возможности, освоить которые не труднее, чем прочие команды Юникс. Не позволяйте себе из-за сложности освоения всей программы, отказываться от ее простых аспектов.

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

Команда s – substitution (замена)

Программа sed имеет множество собственных команд. Большинство пользователей знают только команду s, и этого вполне хватает, чтобы работать с редактором sed. Команда s заменяет ОБРАЗЕЦ на ЗАМЕНУ:

sed s/ОБРАЗЕЦ/ЗАМЕНА/

$ echo день | sed s/день/ночь/ (Enter)

 

ночь

Проще не бывает. А вот пример с вводом из файла zar.txt:

По утрам он делал зарядку.

Молния – электрический заряд.

$ sed s/заряд/разряд/ zar.txt

 

По утрам он делал разрядку.

Молния – электрический разряд.

Я не брал выражение s/ОБРАЗЕЦ/ЗАМЕНУ/ в кавычки, так как данный пример не нуждается в кавычках, но если бы в нем присутствовали метасимволы, то кавычки были бы обязательны. Чтобы не ломать себе каждый раз голову, и не ошибиться ненароком, всегда ставьте кавычки, лучше более “сильные” одинарные, это хорошая привычка. Кашу маслом не испортишь. Я тоже во всех последующих примерах не буду манкировать кавычками.

Как мы видим, заменяющая команда s имеет четыре составляющих:

s              сама команда

 

/…/…/      разделитель

 

ОБРАЗЕЦобразец для поиска и последующей замены

 

ЗАМЕНА         выражение, которое заменит собой ОБРАЗЕЦ, буде таковой найден.

Прямой слэш (/) используется в качестве разделителя по традиции, так как предок программы sed – редактор ed использует их (как и редактор vi). В некоторых случаях такой разделитель весьма неудобен, например, когда надо менять пути (path) к директориям, которые тоже содержат прямой слэш (/usr/local/bin). В этом случае приходится разделять прямыеслэши обратными:

sed ‘s/\/usr\/local\/bin/\/common\/bin/’

Это называется “частокол” и выглядит весьма уродливо, а главное, непонятно.

Уникальность программы sed в том, что она позволяет использовать любой разделитель, например знак подчеркивания:

$ echo день | seds_день_ночь_

 

ночь

или двоеточие:

$ echo день | sed s:день:ночь:

 

ночь

Если в поисках разделителя, который вам нравится, вы получаете сообщение “незавершенная команда `s'”, значит этот символ не годится в качестве разделителя, или вы просто забыли поставить один-два разделителя.

В этой статье я вынужден использовать традиционный разделитель (/) чтобы не сбивать читателя с толку, но в случае необходимости стану использовать в качестве разделителя тильду (~).

Регулярныевыражения (РВ)

(Regular expressions, regexp, RE)

Тема регулярных выражений настолько обширна, что ей посвящены целые книги (смотри ссылки в конце статьи). Тем не менее, говорить всерьез о редакторе sed, не применяя регулярных выражений, также непродуктивно, как разговаривать о тригонометрии при помощи счетных палочек. Поэтому необходимо рассказать хотя бы о тех регулярных выражениях, которые часто используются с программой sed.

с Или любая другая буква. Большинство букв, цифр и прочих неспециальных символов считаются регулярными выражениями, представляющими сами себя.

* Астериск, следующий за каким-либо символом или регулярным выражением, означает любое число (в том числе и нулевое) повторов этого символа или регулярного выражения.

\+ Означает один или более повтор символа или регулярного выражения.

\? Означает ни одного или один повтор.

\{i\} Означает ровно i повторов.

\{i,j\} Число повторов находится в интервале от i до j включительно.

\{i,\} Число повторов больше или равно i.

\{,j\} Число повторов меньше или равно j.

\(RE\) Запомнить регулярное выражение или его часть с целью дальнейшего использования как единое целое. Например, \(а-я\)* будет искать любое сочетание любого количества (в том числе и нулевого) строчных букв.

. Означает любой символ, в том числе символ новой строки.

^ Означает нулевое выражение в начале строки. Другими словами, то, перед чем стоит этот знак, должно появляться в начале строки. Например, ^#include будет искать строки, начинающиеся с #include.

$ То же, что и предыдущее, только относится к концу строки.

[СПИСОК] Означает любой символ из СПИСКА. Например, [aeiou] будет искать любую английскую гласную букву.

[^СПИСОК] Означает любой символ, кроме тех, что в списке. Например, [^aeiou] будет искать любую согласную. Примечание: СПИСОК может быть интервалом, например [а-я], что будет означать любую строчную букву. Если нужно включить в СПИСОК ] (квадратную скобку) укажите ее в списке первой; если нужно включить в СПИСОК – (дефис), то укажите его в списке первым или последним.

RE1\|RE2 Означает РВ1 или РВ2.

RE1RE2 Означает объединение регулярных выражений РВ1 и РВ2.

\n Означает символ новой строки.

\$; \*; \.; \[; \\; \^ Означают соответственно: $; *; .; [; \; ^

Внимание: Остальные условные обозначения на основе обратного слэша (\), принятые в языке С, не поддерживаются программой sed.

\1 \2 \3 \4 \5 \6 \7 \8 \9 Означает соответствующую по счету часть регулярного выражения, запомненную при помощи знаков \( и \).

Несколько примеров:

abcdef Означает abcdef

a*b Означает ноль или любое количество букв а и одна буква b. Например, aaaaaab; ab; или b.

a\?b Означает b или ab

a\+b\+ Означает одну или больше букв а и одну или больше букв b. Например: ab; aaaab; abbbbb; или aaaaaabbbbbbb.

.* Означает все символы на строке, на всех строках, включая пустые.

.\+ Означает все символы на строке, но только на строках, содержащих хотя бы один символ. Пустые строки не соответствуют данному регулярному выражению.

^main.*(.*) Будет искать строки, начинающиеся со слова main, а также имеющие в своем составе открывающую и закрывающие скобки, причем перед и после открывающей скобки может находиться любое количество символов (а может и не находиться).

^# Будет искать строки, начинающиеся со знака # (например комментарии).

\\$ Будет искать строки, заканчивающиеся обратным слэшем (\).

[a-zA-Z_] Любые буквы или цифры

[^ ]\+ (В квадратной скобке, кроме символа ^, содержится еще пробел и табуляция) –Означает один или любое количество любых символов, кроме пробела и табуляции. Обычно имеется в виду слово.

^.*A.*$ Означает заглавную букву А точно в середине строки.

A.\{9\}$ Означает заглавную букву А, точно десятую по счету от конца строки.

^.\{,15\}A Означает заглавную букву А, точно шестнадцатую по счету от начала строки.

Теперь, когда мы познакомились с некоторыми регулярными выражениями, вернемся к команде s редактора sed.

Использование символа& когда ОБРАЗЕЦ неизвестен

“Как это неизвестен?”, – спросите вы – “Ты разве не знаешь, что хочешь заменить?” Отвечу: я хочу взять в скобки любые цифры, найденные в тексте. Как это сделать? Ответ: применить символ &.

Символ & (амперсанд), будучи помещен в состав ЗАМЕНЫ, означает любой найденный в тексте ОБРАЗЕЦ. Например:

$ echo 1234 | sed ‘s/[0-9]*/(&)/’

 

(1234)

Звездочка (астериск) после интервала [0-9] нужна чтобы заменены были все цифры, встретившиеся в образце. Без нее получилось бы:

$ echo 1234 | sed ‘s/[0-9]/(&)/’

 

(1)234

То есть в качестве образца взята была первая же найденная цифра.

Вот пример со вполне осмысленной нагрузкой: составим файл formula.txt:

a+432-10=n

и применим к нему команду:

$ sed ‘s/[0-9]*-[0-9]*/(&)/’ formula.txt

 

a+(432-10)=n

Математическая формула приобрела однозначный смысл.

Еще символ амперсанда можно использовать для удвоения ОБРАЗЦА:

$ echo 123 | sed “s/[0-9]*/&&/”

 

123 123

Тут есть одна тонкость. Если мы чуть усложним пример:

$ echo “123 abc” | sed “s/[0-9]*/&&/”

 

123 123 abc

как и следовало ожидать, удваиваются только цифры, так как в ОБРАЗЦЕ нет букв. Но если мы поменяем части текста местами:

$ echo “abc 123” | sed “s/[0-9]*/&&/”

 

abc 123

то никакого удвоения цифр не получится. Это особенность регулярного выражения [0-9]* – оно ищет соответствия только в первом символе строки. Если мы хотим удвоения цифр, где бы они ни находились, нужно доработать регулярное выражение в ЗАМЕНЕ:

$ echo “abc defg 123” | sed “s/[0-9][0-9]*/&&/”

 

abcdefg 123 123

тогда цифры будут удваиваться, независимо от количества предшествующих “слов”.

Использование условных знаков \(, \) и \1 для обработки части ОБРАЗЦА

Условные знаки \( и \) (escapedparentheses) применяются для запоминания части регулярного выражения.

Условный знак \1 означает первую запомненную часть, \2 – вторую, и так далее, вплоть до девяти запомненных частей (больше программа не поддерживает). Разберем пример:

$ echo abcd123 | sed ‘s/\([a-z]*\).*/\1/’

 

abcd

Здесь \([a-z]*\) означает, что программа должна запомнить все буквенные символы в любом количестве; .* означает любое количество символов после первой запомненной части; а \1 означает , что мы хотим видеть только первую запомненную часть. Так и есть: в выводе программы мы видим только буквы и никаких цифр.

Для того, чтобы поменять слова местами, нужно запомнить два суб-ОБРАЗЦА, а потом поменять их местами:

$ echo глупый пингвин |sed ‘s/\([а-я]*\) \([а-я]*\)/\2 \1/’

 

пингвин глупый

Здесь \2 означает второй суб-ОБРАЗЕЦ, а \1 -первый. Обратите внимание на интервал между первым выражением \([а-я]*\) и вторым выражением \([а-я]*\). Он необходим, чтобы были найдены два слова.

Знак \1 вовсе не обязан быть только в ЗАМЕНЕ, он может присутствовать также и в ОБРАЗЦЕ, например, когда мы хотим удалить дубликаты слов:

$ echo пингвин пингвин | sed ‘s/\([а-я]*\) \1/\1/’

 

пингвин

Модификаторы замены команды s

Модификаторы замены ставятся после последнего разделителя. Эти модификаторы определяют действия программы в случае, если в строке нашлось более одного совпадения с ОБРАЗЦОМ, и каким образом производить замену.

Модификатор /g

– Глобальная замена (Globalreplacement)

Программа sed, как и большинство утилит Юникс, при работе с файлами считывают по одной строке. Если мы приказываем заменить слово, программа заменит только первое совпавшее с ОБРАЗЦОМ слово на данной строке. Если мы хотим изменить каждое слово, совпавшее с образцом, то следует ввести модификатор /g.

Без модификатора /g:

$ echo кот этот, был самый обычный кот | sed ‘s/кот/котенок/’

 

котенок этот, был самый обычный кот

Редактор заменил только первое совпавшее слово.

А теперь с модификатором глобальной замены:

$ echo кот этот, был самый обычный кот | sed ‘s/кот/котенок/g’

 

котенок этот, был самый обычный котенок

Все совпадения в данной строке были заменены.

А если нужно изменить все слова, скажем взять их в скобки? Тогда на помощь снова придут регулярные выражения. Чтобы выбрать все буквенные символы, как верхнего, так и нижнего регистра, можно воспользоваться конструкцией [А-Яа-я], но в нее не попадут такие слова как “что-то” или “с’езд”. Гораздо удобнее конструкция [^ ]*, которая соответствует всем символам, кроме пробела. Итак:

$ echo глупый пингвин робко прячет | sed ‘s/[^ ]*/(&)/g’

 

(глупый) (пингвин) (робко) (прячет)

Как выбрать нужное совпадение из нескольких

Если не применять модификаторов, то программа sed заменит только первое совпавшее с ОБРАЗЦОМ слово. Если применить модификатор /g, то программа заменит каждое совпавшее слово. А как можно выбрать одно из совпадений, если их несколько на строке? – При помощи уже знакомых нам условных знаков \( и \) запомнить суб-ОБРАЗЦЫ и выбрать нужный при помощи знаков \1 – \9.

$ echo глупый пингвин | sed ‘s/\([а-я]*\) \([а-я]*\)/\2 /’

 

пингвин

В этом примере мы запомнили оба слова, и, поставив второе (пингвин) на первое место, первое (глупый) удалили, поставив в секции ЗАМЕНЫ вместо него пробел. Если мы поставим вместо пробела какое-либо слово, то оно заменит первое (глупый):

$ echo глупый пингвин | sed ‘s/\([а-я]*\) \([а-я]*\)/\2 умный /’

 

пингвин умный

Числовой модификатор

Это одно/двух/трех -значное число, которое ставится после последнего разделителя и указывает, какое по счету совпадение подлежит замене.

$ echo очень глупый пингвин | sed ‘s/[а-я]*/хороший/2’

 

очень хороший пингвин

В этом примере каждое слово является совпадением, и мы указали редактору, какое по счету слово мы хотим заменить, поставив модификатор 2 после секции ЗАМЕНЫ.

Можно комбинировать цифровой модификатор с модификатором /g. Если нужно оставить неизменным первое слово, а второе и последующие заменить на слово “(удалено)”, то команда будет такая:

$ echo очень глупый пингвин | sed ‘s/[а-я]*/(удалено)/2g’

 

очень (удалено) (удалено)

Если нужно действительно удалить все последующие совпадения, кроме первого, то в секции ЗАМЕНЫ следует поставить пробел:

$ echo очень глупый пингвин | sed ‘s/[а-я]*/ /2g’

 

очень

Или вовсе ничего не ставить:

$ echo очень глупый пингвин | sed ‘s/[^ ]*//2g’

 

очень

Числовой модификатор может быть любым целым числом от 1 до 512. Например, если нужно поставить двоеточие после 80 символа каждой строки, то поможет команда:

$ sed ‘s/./&:/80’ имя_файла

Модификатор /p – выдавать на стандартный выход (печатать – print)

Программа sed и так по умолчанию выдает результат на стандартный выход (например экран монитора). Этот модификатор применяется только с опцией sed -n, которая как раз блокирует вывод результата на экран.

Модификатор /w

Позволяет записывать результаты обработки текста в указанный файл:

$ sed ‘s/ОБРАЗЕЦ/ЗАМЕНА/w имя_файла

Модификатор /e (расширение GNU)

Позволяет указать команду шелла (не программы sed) в качестве ЗАМЕНЫ. Если соответствие ОБРАЗЦУ будет найдено, то оно будет заменено на вывод указанной в секции ЗАМЕНЫ команды. Пример:

$ echo ночь | sed ‘s/ночь/echo день/e’

 

день

Модификаторы /I и /i (расширение GNU)

Делают процесс замены нечувствительным к регистру символов.

$ echo Night | sed ‘s/night/day/i’

 

day

Комбинации модификаторов

Модификаторы можно комбинировать, когда это имеет смысл. При этом следует ставить модификатор w последним.

Условные обозначения (расширение GNU)

Их всего пять:

  • \L переводит символы ЗАМЕНЫ в нижний регистр
  • \l переводит следующий символ ЗАМЕНЫ в нижний регистр
  • \U переводит символы ЗАМЕНЫ в верхний регистр
  • \u переводит следующий символ ЗАМЕНЫ в верхний регистр
  • \E отменяет перевод, начатый \L или \U

По очевидным причинам эти условные обозначения применяются по одиночке. Например:

$ echo глупый пингвин | sed ‘s/глупый/\u&/’

 

Глупый пингвин

или:

$ echo маленький щенок | sed ‘s/[а-я]*/\u&/2’

 

маленький Щенок

Мы рассмотрели почти все аспекты команды s редактора sed. Теперь настала очередь рассмотреть опции этой программы.

Опции программы sed

Программа имеет на удивление мало опций. (Что несколько компенсирует избыток команд, модификаторов и прочих функций). Кроме общеизвестных опций –help (-h) и –version (-V), которые мы рассматривать не будем, их всего три:

Опция -e

–expression=набор_команд

Один из способов выполнения нескольких команд – применение опции -e. Например:

sed -e ‘s/a/A/’ -e ‘s/b/B/’ имя_файла

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

Опция -f

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

sed -f sedscriptимя-файла

Sedscript здесь – имя файла, содержащего команды. Этот файл называется скриптом программы sed (далее просто скрипт). Каждая команда скрипта должна занимать отдельную строку. Например:

# комментарий – Этот скрипт изменит все строчные гласные буквы на заглавные

s/a/A/g

s/e/E/g

s/i/I/g

s/o/O/g

s/u/U/g

Назвать скрипт можно как угодно, важно не путать файл скрипта с обрабатываемым файлом.

Опция -n

Программа sed -n не выводит ничего на стандартный выход. Чтобы получить вывод нужно специальное указание. Мы уже познакомились с модификатором /p, при помощи которого можно дать такое указание. Вспомним файл zar.txt:

$ sed ‘s/1-9/&/p’ zar.txt

 

По утрам он делал зарядку.

Молния – электрический заряд.

Так как совпадений с ОБРАЗЦОМ не найдено (в файле нет цифр), то команда s с модификатором /p и знаком & в качестве ЗАМЕНЫ (напомню, что амперсанд означает сам ОБРАЗЕЦ), работает как команда cat.

Если ОБРАЗЕЦ будет найден в файле, то строки, содержащие ОБРАЗЕЦ, будут удвоены:

$ sed ‘s/зарядку/&/p’ zar.txt

 

По утрам он делал зарядку.

По утрам он делал зарядку.

Молния – электрический заряд.

Теперь добавим опцию -n:

$ sed -n ‘s/зарядк/&/p’ zar.txt

 

По утрам он делал зарядку.

Теперь наша программа работает как команда grep – возвращает только строки, содержащие ОБРАЗЕЦ.

Выбор нужных элементов редактируемого текста

Используя лишь одну команду s, мы убедились в необыкновенно широких возможностях редактора sed. А ведь все, что он делает, сводится к поиску и замене. Причем в процессе работы sed редактирует каждую строку поодиночке, не обращая внимания на другие. Было бы удобно ограничить круг строк, подлежащих изменению, например:

  • Выбирать строки по номерам
  • Выбирать строки в некотором диапазоне номеров
  • Выбирать только строки, содержащие некое выражение
  • Выбирать только строки между некоторыми выражениями
  • Выбирать только строки от начала файла и до некоторого выражения
  • Выбирать только строки от некоторого выражения и до конца файла

Программа sed умеет все это и даже больше. Любая команда редактора sed может применяться адресно, в некотором диапазоне адресов, или с вышеперечисленными ограничениями круга строк. Адрес или ограничение должны непосредственно предшествовать команде:

sed ‘адрес/ограничение команда’

Выбор строк по номерам

Это самый простой случай. Просто указываем номер нужной строки перед командой:

$ sed ‘4 s/[а-я]*//i’ gumilev.txt

 

Какая странная нега

В ранних сумерках утра,

В таянии вешнего снега,

всем, что гибнет и мудро.

Или:

$ sed ‘3 s/В/(В)/’ gumilev.txt

 

Какая странная нега

В ранних сумерках утра,

(В) таянии вешнего снега,

Во всем, что гибнет и мудро.

Выбор строк в диапазоне номеров

Диапазон указывается, как не удивительно, через запятую:

$ sed ‘2,3 s/В/(В)/’ gumilev.txt

 

Какая странная нега

(В) ранних сумерках утра,

(В) таянии вешнего снега,

Во всем, что гибнет и мудро.

Если нужно указать диапазон до последней строки файла, а вы не знаете, сколько в нем строк, то воспользуйтесь знаком $:

$ sed ‘2,$ s/в/(в)/i’ gumilev.txt

 

Какая странная нега

(в) ранних сумерках утра,

(в) таянии вешнего снега,

(в)о всем, что гибнет и мудро.

Выбор строк, содержащих некое выражение

Искомое выражение заключается в прямыеслэши (/) и ставится перед командой:

$ sed ‘/утра/ s/в/(в)/i’ gumilev.txt

 

Какая странная нега

(в) ранних сумерках утра,

В таянии вешнего снега,

Во всем, что гибнет и мудро.

Выбор строк в диапазоне между двумя выражениями

Также как и в случае с номерами строк, диапазон задается через запятую:

$ sed ‘/утра/,/мудро/ s/в/(в)/i’ gumilev.txt

 

Какая странная нега

(в) ранних сумерках утра,

(в) таянии вешнего снега,

(в)о всем, что гибнет и мудро.

Выбор строк от начала файла и до некоего выражения

$ sed ‘1,/снега/ s/в/(в)/i’ gumilev.txt

 

Какая странная нега

(в) ранних сумерках утра,

(в) таянии вешнего снега,

Во всем, что гибнет и мудро.

Выбор строк от некоего выражения и до конца файла

$ sed ‘/снега/,$ s/в/(в)/i’ gumilev.txt

 

Какая странная нега

В ранних сумерках утра,

(в) таянии вешнего снега,

(в)о всем, что гибнет и мудро.

Другие команды редактора sed

Команда d (delete)

Удаляет из стандартного вывода указанные строки:

$ sed ‘2 d’ gumilev.txt

 

Какая странная нега

В таянии вешнего снега,

Во всем, что гибнет и мудро.

Причем чаще пишут проще (без пробела):

sed ‘2d’ gumilev.txt

Все, что было сказано в предыдущем разделе о адресации строк, справедливо и для команды d (как и для почти всех команд редактора sed).

При помощи команды d удобно выбросить ненужную “шапку” какого-нибудь почтового сообщения:

$ sed ‘1,/^$/ d’ имя_файла

(Удалить строки с первой и до первой пустой строки).

Избавится от комментариев в конфигурационном файле:

$ sed ‘/^#/ d’ /boot/grub/menu.lst

И мало ли, где нужно удалить лишние строчки!

Команда p (print)

Английское слово “print” переводится как “печатать”, что в русском языке ассоциируется с принтером, или, по крайней мере, с клавиатурой. На самом же деле, слово это в английском контексте зачастую означает просто вывод на экран монитора. Так что команда p ничего не печатает, а просто выводит на экран указанные строки.

Будучи примененной сама по себе, команда p удваивает строки в выводе (ведь программа sed по умолчанию выводит строку на экран, а команда p выводит ту же строку вторично).

$ echo у меня есть кот | sed ‘p’

 

у меня есть кот

у меня есть кот

Этому свойству находится применение, например удвоить пустые строки для улучшения вида текста:

$ sed ‘/^$/ p имя_файла

Но истинное свое лицо команда p раскрывает в сочетании с опцией -n, которая, как вы помните, запрещает вывод строк на экран. Комбинируя опцию -n с командой p, можно получить в выводе только нужные строки.

Например, просмотреть строки с первой по десятую:

$ sed -n ‘1,10 p’ имя_файла

Или только комментарии:

$ sed -n ‘/^#/ p’ /boot/grub/menu.lst

 

# GRUB configuration file ‘/boot/grub/menu.lst’.

# generated by ‘grubconfig’.  Вск 23 Мар 2008 21:45:41

#

# Start GRUB global section

# End GRUB global section

# Linux bootable partition config begins

# Linux bootable partition config ends

# Linux bootable partition config begins

# Linux bootable partition config ends

Что весьма напоминает работу программы grep, с чем мы уже сталкивались, когда говорили об опции -n с модификатором /p. Но, в отличие от команды grep, редактор sed дает возможность не только найти эти строки, но и изменить их, заменив, например, везде Linux на Unix:

$ sed -n ‘/^#/ p’ /boot/grub/menu.lst | sed ‘s/Linux/Unix/’

 

# GRUB configuration file ‘/boot/grub/menu.lst’.

# generated by ‘grubconfig’.  Вск 23 Мар 2008 21:45:41

#

# Start GRUB global section

# End GRUB global section

# Unix bootable partition config begins

# Unix bootable partition config ends

# Unix bootable partition config begins

# Unix bootable partition config ends

Команда !

Иногда нужно бывает редактировать все строки, кроме тех, что соответствуют ОБРАЗЦУ, либо выбору. Символ восклицательного знака (!) инвертирует выбор. Например удалим все строки, кроме второй из четверостишия Гумилева:

$ sed ‘2 !d’ gumilev.txt

 

В ранних сумерках утра,

Или выберем все строки, кроме комментариев, из файла /boot/grub/menu.lst:

$  sed -n ‘/^#/ !p’ /boot/grub/menu.lst

 

default 1

timeout 20

gfxmenu (hd0,3)/boot/message

title SuSe on (/dev/hda3)

root (hd0,2)

kernel /boot/vmlinuz root=/dev/hda3 ro vga=773 acpi=off

title Linux on (/dev/hda4)

root (hd0,3)

kernel /boot/vmlinuz root=/dev/hda4 ro vga=0x317

Команда q (quit)

Команда q прекращает работу программы sed после указанной строки. Это удобно, если нужно прекратить редактирование после достижения определенного места в тексте:

$  sed ’11 q’ имя_файла

Эта команда закончит работу по достижению 11-й строки.

Команда q – одна из немногих команд sed, не принимающих диапазонов строк. Не может же команда прекратить работу 10 раз подряд, если мы введем:

sed ‘1,10 q’

Абсурд!

Команда w (write)

Подобно модификатору w команды s, эта команда позволяет записать вывод программы в файл:

$ sed -n ‘3,$ w gum.txt’ gumilev.txt

Мы получим файл gum.txt, содержащий две последние строки четверостишия Гумилева из файла gumilev.txt. Причем, если такой файл уже существует, то будет перезаписан. Если не ввести опцию -n, то программа, кроме создания файла gum.txt, еще и выведет на экран все содержание файла gumilev.txt.

Для работы в командной строке, удобнее пользоваться обычным перенаправлением вывода (> или >>), но в sed скриптах, вероятно, команда w найдет свое применение.

Команда r (read)

Эта команда не только прочтет указанный файл, но и вставит его содержимое в нужное место редактируемого файла. Для выбора “нужного места” используется уже знакомая нам адресация (по номерам строк, по выражениям, и проч.). Пример:

$ echo Из стихотворения Гумилева: | sed ‘r gumilev.txt’

 

Из стихотворения Гумилева:

Какая странная нега

В ранних сумерках утра,

В таянии вешнего снега,

Во всем, что гибнет и мудро.

Команда =

Выдаст номер указанной строки:

$ sed  ‘/снега/=’ gumilev.txt

 

Какая странная нега

В ранних сумерках утра,

3

В таянии вешнего снега,

Во всем, что гибнет и мудро.

Или:

$ sed -n  ‘/снега/=’ gumilev.txt

 

3

Команда принимает только один адрес, не принимает интервалов.

Команда y

Эта команда заменяет символы из секции ОБРАЗЕЦ символами секции ЗАМЕНА, работая как программа tr.

$  echo Автомобиль – наследие прошлого | sed ‘y/Авто/Паро/’

 

Паромобиль – наследие прошлого

Команда y работает, только если количество символов в ОБРАЗЦЕ равно количеству символов в ЗАМЕНЕ.

Скрипты программы sed

Для того, чтобы пользоваться редактором sed как полноценным текстовым редактором, необходимо освоить составление скриптов sed. Программа sed имеет собственный несложный язык программирования, позволяющий составлять скрипты, способные творить чудеса.

Эта статья не может вместить описания скриптов sed, как и ее автор не ставит себе задачу освоение языка программирования sed. В этой статье я делал акцент на использование редактора sed в командной строке, имея прицел на использование его в качестве фильтра в программных каналах (pipes). По этой причине я опустил многочисленные команды sed, применяющиеся только в его скриптах.

Существует множество любителей редактора sed, и множество статей на тему скриптописания, в том числе и в Рунете. Так что для заинтересовавшихся этой замечательной программой не составит труда пополнить свои знания.

Программа sed и символы кириллицы

Как видно из примеров в этой статье, программа sed на правильно русифицированной системе свободно владеет “великим и могучим” языком.

Резюме программы sed

Программа sed – это многофункциональный редактор потока данных, незаменимый для:

  • Редактирования больших текстовых массивов
  • Редактирования файлов любой величины, когда последовательность редактирующих действий слишком сложна
  • Редактирования данных по мере их поступления, в том числе в режиме реального времени

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

Для освоения программы sed в полном объеме потребуются недели или даже месяцы работы, так как для этого необходимо:

  • Изучить регулярные выражения
  • Научиться писать скрипты sed, освоив несложный язык программирования, применяющийся в этих скриптах

С другой стороны, освоить несколько наиболее употребительных команд редактора sed не сложнее, чем любую команду Юникс; надеюсь, данная статья поможет вам в этом.

Послесловие

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

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

sipsak

dapper (1) sipsak.1.gz
Provided by: sipsak_0.9.5-1_i386 bug


NAME

       sipsak - a utility for various tests on sip servers and user agents

SYNOPSIS

       sipsak  [-dFGhiILnNMRSTUVvwz]  [-a PASSWORD ] [-b NUMBER ] [-c SIPURI ]
       [-C SIPURI ] [-D NUMBER ] [-e NUMBER ] [-E STRING  ]  [-f  FILE  ]  [-g
       STRING  ]  [-H  HOSTNAME  ]  [-l  PORT  ] [-m NUMBER ] [-o NUMBER ] [-p
       HOSTNAME ] [-P NUMBER ] [-q REGEXP ] [-r PORT ] [-t NUMBER ] [-u STRING
       ] [-W NUMBER ] [-x NUMBER ] -s SIPURI

DESCRIPTION

       sipsak  is a SIP stress and diagnostics utility.  It sends SIP requests
       to the server within the sip-uri and examines received  responses.   It
       runs in one of the following modes:

       - default mode
              A SIP message is sent to destination in sip-uri and reply status
              is displayed.  The request is  either  taken  from  filename  or
              generated as a new OPTIONS message.

       - traceroute mode (-T)
              This  mode  is  useful  for learning request’s path. It operates
              similarly to IP-layer utility traceroute(8).

       - message mode (-M)
              Sends a short message (similar to SMS from the mobile phones) to
              a  given  target.  With the option -B the content of the MESSAGE
              can be set. Usefull might be the options -c and -O in this mode.

       - usrloc mode (-U)
              Stress  mode  for  SIP registrar.  sipsak keeps registering to a
              SIP server at  high  pace.  Additionaly  the  registrar  can  be
              stressed with the -I or the -M option.  If -I and -M are omitted
              sipsak can be used to register any given contact  (with  the  -C
              option)  for  an account at a registrar and to query the current
              bindings for an account at a registrar.

       - randtrash mode (-R)
              Parser torture mode.  sipsak keeps  sending  randomly  corrupted
              messages to torture a SIP server’s parser.

       - flood mode (-F)
              Stress mode for SIP servers.  sipsak keeps sending requests to a
              SIP server at high pace.

       If libruli (http://www.nongnu.org/ruli/) support is compiled  into  the
       sipsak  binary, then first a SRV lookup for _sip._udp.hostname is made.
       And if this lookup fails a normal A lookup is made. If a port was given
       in   the   target  URI  the  SRV  lookup  is  omitted.  Failover,  load
       distribution and other transports are not supported yet.

OPTIONS

       -a, --pasword PASSWORD
              With the given PASSWORD  an  authentication  will  be  tryed  on
              received  ’401  Unauthorized’.  Authorization  will  be tryed on
              time. If this option is omitted an authorization with  an  empty
              password ("") will be tryed.

       -A, --timing
              prints  only  the  timing values of the test run if verbosity is
              zero because no -v was given. If one or more -v were given  this
              option will be ignored.

       -b, --apendix-begin NUMBER
              The  starting  number  which is appended to the user name in the
              usrloc mode.  This NUMBER is  increased  until  it  reaches  the
              value  given by the -e parameter. If omitted the starting number
              will be one.

       -B, --message-body STRING
              The given STRING will be used as the body for  outgoing  MESSAGE
              requests.

       -c, --from SIPURI
              The  given SIPURI will be used in the From header if sipsak runs
              in the message mode (initiated with  the  -M  option).  This  is
              helpfull  to present the receiver of a MESSAGE a meaningfull and
              usable address to where maybe even responses can be send.

       -C, --contact SIPURI
              This is the content of the Contact header in  the  usrloc  mode.
              This  allows  to  insert forwards like for mail. For example you
              can insert the uri  of  your  first  SIP  account  at  a  second
              account,  thus all calls to the second account will be forwarded
              to the first account.  As the argument to this option  will  not
              be  enclosed  in brackets you can give also multiple contacts in
              the raw format as comma seperated list.  The special words empty
              or none will result in no contact header in the REGISTER request
              and thus the server should answer with the current bindings  for
              the account at the registrar.

       -d, --ignore-redirects
              If  this option is set all redirects will be ignored. By default
              without this option received redirects will be  respected.  This
              option is automaticly activated in the randtrash mode and in the
              flood mode.

       -D, --timeout-factor NUMBER
              The SIP_T1 timer is getting multiplied with  the  given  NUMBER.
              After receiving a provisional response for an INVITE request, or
              when a reliable transport like TCP or TLS is used  sipsak  waits
              for  the  resulting amount of time for a final response until it
              gives up.

       -e, --appendix-end NUMBER
              The ending number which is appended to  the  user  name  in  the
              usrloc  mode.   This  number  is increased until it reaches this
              ending number.  In the flood mode this is the maximum number  of
              messages  which  will  be send.  If omitted the default value is
              2^31 (2147483647) in the flood mode.

       -E, --transport STRING
              The value of STRING will be used as IP transport for sending and
              receiving  requests  and  responses.  This option overwrites any
              result from the URI evaluation and SRV lookup.   Currently  only
              ’udp’ and ’tcp’ are accepted as value for STRING.

       -f, --filename FILE
              The  content  of FILE will be read in in binary mode and will be
              used as replacement for the alternatively  created  sip  header.
              This  can  used  in the default mode to make other requests than
              OPTIONS requests (e.g.  INVITE).  By  default  missing  carriage
              returns  in  front of line feeds will be inserted (use -L to de-
              activate this function).  But be warned  that  the  manipulation
              functions  (e.g.  inserting Via header) are only tested with RFC
              conform requests. Additionaly special strings  within  the  file
              can  be  replaced with some local or given values (see -g and -G
              for details).

       -F, --flood-mode
              This options activates the flood  mode.  In  this  mode  OPTIONS
              requests  with  increasing  CSeq numbers are sent to the server.
              Replies are ignored -- source port 9 (discard) of  localhost  is
              advertised in topmost Via.

       -h, --help
              Prints  out  a  simple  usage  help  message. If the long option
              --help is available it will print out a help  message  with  the
              available long options.

       -g, --replace-string STRING
              Activates  the  replacement  of  $replace$  within  the  request
              (usualy read in from a file) with the STRING.

       -G, --replace
              Activates the automatic replacement of the  following  variables
              in  the  request (usualy read in from a file): $dsthost$ will be
              replaced by with the host or domainname which is given by the -s
              parameter.   $srchost$  will  be replaced by the hostname of the
              local machine.  $port$ will be replaced by the  local  listening
              port  of  sipsak.  $user$ will be replaced by the username which
              is given by the -s parameter.

       -H, --hostname HOSTNAME
              Overwrites the automatic detection  of  the  hostname  with  the
              given  parameter.   Warning:  use  this with caution (preferable
              only if the automatic detection fails).

       -i, --no-via
              Deactivates the insertion of the  Via  line  of  the  localhost.
              Warning:  this  probably disables the receiving of the responses
              from the server.

       -I, --invite-mode
              Activates the Invites cycles within the usrloc mode.  It  should
              be   combined   with  -U.   In  this  combination  sipsak  first
              registeres a user, and then  simulates  an  invitation  to  this
              user.  First  an Invite is sent, this is replied with 200 OK and
              finaly an ACK is sent. This option can also be used without -U ,
              but  you should be sure to NOT invite real UAs with this option.
              In the case of a missing -U the -l PORT is required because only
              if  you made a -U run with a fixed local port before, a run with
              -I and the same fixed local port can  be  successful.   Warning:
              sipsak  is  no real UA and invitations to real UAs can result in
              unexpected behaivior.

       -l, --local-port PORT
              The receiving UDP  socket  will  use  the  local  network  port.
              Useful  if  a  file  is given by -f which contains a correct Via
              line. Check the -S option  for  details  how  sipsak  sends  and
              receives messages.

       -L, --no-crlf
              De-activates  the  insertion of carriage returns (\r) before all
              line feeds (\n) (which is not  allready  proceeded  by  carraige
              return) if the input is comming from a file ( -f ). Without this
              option also an empty line will be appended  to  the  request  if
              required.

       -m, --max-forwards NUMBER
              This  sets the value of the Max-Forward header field. If omitted
              no Max-Forward  field  will  be  inserted.  If  omitted  in  the
              traceroute mode number will be 255.

       -M, --message-mode
              This activates the Messages cycles within the usrloc mode (known
              from sipsak versions pre 0.8.0 within the normal  usrloc  test).
              This  option  should  be  combined  with  -U so that a succesful
              registration will be tested with a test message to the user  and
              replied  with  200  OK. But this option can also be used without
              the -U option.  Warning: using without -U can  cause  unexpected
              behaivor.

       -n, --numeric
              Instead of the full qualified domain name in the Via line the IP
              of the local host will  be  used.  This  option  is  now  on  by
              default.

       -N, --nagios-code
              Use  Nagios  comliant  return codes instead of the normal sipsak
              ones. This means sipsak will return 0 if everything was ok and 2
              in case of any error (local or remote).

       -o, --sleep NUMBER
              sipsak  will sleep for NUMBER ms before it starts the next cycle
              in the usrloc mode. This will slow down the whole  test  process
              to be more realistic. Each cycle will be still completed as fast
              as possible, but the whole test will be slowed down.

       -O, --disposition STRING
              The given STRING will be used as the content  for  the  Content-
              Disposition  header.  Without  this  option  there  will  be  no
              Content-Disposition header in the request.

       -p, --outbound-proxy HOSTNAME[:PORT]
              the address of the hostname is the target where the request will
              be sent to (outgoing proxy). Use this if the destination host is
              different then the host part of the request uri. The hostname is
              resolved  via  DNS  SRV  if  supported  (see description for SRV
              resolving) and no port is given.

       -P, --processes NUMBER
              Start NUMBER of processes in parallel to do the send  and  reply
              checking. Makes only sence if a higher number for -e is given in
              the usrloc, message or invite mode.

       -q, --search REGEXP
              match replies against  REGEXP  and  return  false  if  no  match
              occured.  Useful  for  example  to  detect server name in Server
              header field.

       -r, --remote-port PORT
              Instead of the default sip port 5060  the  PORT  will  be  used.
              Alternatively the remote port can be given within the sip uri of
              the -s parameter.

       -R, --random-mode
              This activates the randtrash mode. In this mode OPTIONS requests
              will  be  send  to  server  with  increasing numbers of randomly
              crashed characters within this request. The position within  the
              request  and  the  replacing  character are randomly chosen. Any
              other response than Bad request (4xx) will stop this mode.  Also
              three  unresponded  sends  will  stop  this  mode.  With  the -t
              parameter the maximum of trashed characters can be given.

       -s, --sip-uri SIPURI
              This mandatory option sets the destination of  the  request.  It
              depends on the mode if only the server name or also an user name
              is mandatory. Example for a full SIPURI  :  sip:test@foo.bar:123
              See  the  note  in  the  description  part about SRV lookups for
              details how the hostname of this URI is converted into an IP and
              port.

       -S, --symmetric
              With  this  option sipsak will use only one port for sending and
              receiving messages. With this option the local port for  sending
              will be the value from the -l option. In the default mode sipsak
              sends from a random port and listens on the given port from  the
              -l  option.   Note:  With this option sipsak will not be able to
              receive replies from  servers  with  asymmetric  signaling  (and
              broken  rport  implementation)  like the Cisco proxy. If you run
              sipsak as root and with raw socket  support  (check  the  output
              from  the -V option) then this option is not required because in
              this case sipsak already uses only  one  port  for  sending  and
              receiving messages.

       -t, --trash-chars NUMBER
              This  parameter  specifies  the maximum of trashed characters in
              the randtrash mode. If omitted NUMBER will be set to the  length
              of the request.

       -T, --traceroute-mode
              This  activates  the  traceroute  mode. This mode works like the
              well known traceroute(8) command expect that not the  number  of
              network  hops are counted rather the number of server on the way
              to the destination user.  Also  the  round  trip  time  of  each
              request  is  printed out, but due to a limitation within the sip
              protocol the identity (IP  or  name)  can  only  determined  and
              printed  out  if the response from the server contains a warning
              header field. In this mode on each outgoing request the value of
              the  Max-Forwards  header field is increased, starting with one.
              The maximum of the Max-Forwards header  will  255  if  no  other
              value  is given by the -m parameter. Any other response than 483
              or 1xx are treated as a final response and will  terminate  this
              mode.

       -u, --auth-username STRING
              Use  the  given  STRING as username value for the authentication
              (different account and authentication username).

       -U, --usrloc-mode
              This activates the usrloc mode. Without the -I or the -M option,
              this  only registers users at a registrar. With one of the above
              options the previous registered user will also be  probed  ether
              with a simulated call flow (invite, 200, ack) or with an instant
              message (message, 200). One  password  for  all  users  accounts
              within  the usrloc test can be given with the -a option. An user
              name is mandatory for this mode in the -s parameter. The  number
              starting  from  the -b parameter to the -e parameter is appended
              the user name. If the -b and the -e parameter are omitted,  only
              one  runs  with the given username, but without append number to
              the usernames is done.

       -v, --verbose
              This parameter increases  the  output  verbosity.  No  -v  means
              nearly  no  output  except in traceroute and error messages. The
              maximum of three v’s prints  out  the  content  of  all  packets
              received and sent.

       -V, --version
              Prints out the name and version number of sipsak and the options
              which were compiled into the binary.

       -w, --extract-ip
              Activates the extraction of the IP or hostname from the  Warning
              header field.

       -W, --nagios-warn NUMBER
              Return   Nagios   warn   exit   code   (1)   if  the  number  of
              retransmissions before success was above the given number.

       -x, --expires NUMBER
              Sets the value of the Expires header to the given number.

       -z, --remove-bindings
              Activates the randomly removing of old bindings  in  the  usrloc
              mode.  How  many  per  cent  of the bindings will be removed, is
              determined by the USRLOC_REMOVE_PERCENT define within  the  code
              (set  it  before compilation).  Multiple removing of bindings is
              possible, and cannot be prevented.

RETURN VALUES

       The return value 0 means that a 200 was  received.  1  means  something
       else  then 1xx or 2xx was received.  2 will be returned on local errors
       like non resolvable names or  wrong  options  combination.  3  will  be
       returned  on  remote  errors  like  socket  errors  (e.g.  icmp error),
       redirects without a contact header or simply no answer (timeout).

       If the -N option was given the return code will be 2  in  case  of  any
       (local or remote) error. 1 in case there have been retransmissions from
       sipsak to the server. And 0 if there was no error at all.

CAUTION

       Use sipsak responsibly. Running it in any  of  the  stress  modes  puts
       substantial burden on network and server under test.

EXAMPLES

       sipsak -vv -s sip:nobody@foo.bar
              displays received replies.

       sipsak -T -s sip:nobody@foo.bar
              traces SIP path to nobody.

       sipsak -U -C sip:me@home -x 3600 -a password -s sip:myself@company
              inserts forwarding from work to home for one hour.

LIMITATIONS / NOT IMPLEMENTED

       Many  servers  may  decide  NOT to include SIP "Warning" header fields.
       Unfortunately, this makes displaying IP addresses  of  SIP  servers  in
       traceroute mode impossible.

       IPv6 is not supported.

       Missing support for the Record-Route and Route header.

BUGS

       sipsak is only tested against the SIP Express Router (ser) though their
       could be various bugs. Please feel free to mail them to the author.

AUTHOR

       Nils Ohlmeier <nils at sipsak dot org>

SEE ALSO

       traceroute(8)

 

sipsak can also send customer methods (NOTIFY Event: check-sync;reboot=true causing yealink phone to reboot):
# sipsak -f reboot_yealink.sipfile -s sip:1234@192.168.1.10

cat reboot_yealink.sipfile

NOTIFY sip:192.168.0.197 SIP/2.0
To: sip:192.168.0.197
From: sip:sipsak@192.168.1.48
CSeq: 10 NOTIFY
Call-ID: 1234@192.168.1.48
Event: check-sync;reboot=true