20151203

Быстрые заметки по awk


2. Отформатировать список адресов под junos address-book.
Есть список ip-адресов и имен серверов:

$ cat TEST-SERV-LOW
192.168.1.1;server1
192.168.1.2;server2
192.168.1.3;server3
192.168.1.4;server4

Этот список надо быстро добавить через "load set relative" в address-book.
Делаем address и address-set.

-- Поменяем регистр имен:
$ tr [:lower:] [:upper:] <TEST-SERV-LOW> TEST-SERV-UP
$ cat TEST-SERV-UP
192.168.1.1;SERVER1
192.168.1.2;SERVER2
192.168.1.3;SERVER3
192.168.1.4;SERVER4

-- С помощью awk печатаем команды:
$ awk -F ';' '{ print "set address " $2 " " $1}'  TEST-SERV-UP > server-set-load | awk -F ';' '{print "set address-set SET-SERVER-IP " $2}' TEST-SERV-UP >> server-set-load

$ cat server-set-load
set address SERVER1 192.168.1.1
set address SERVER2 192.168.1.2
set address SERVER3 192.168.1.3
set address SERVER4 192.168.1.4
set address-set SET-SERVER-IP SERVER1
set address-set SET-SERVER-IP SERVER2
set address-set SET-SERVER-IP SERVER3
set address-set SET-SERVER-IP SERVER4



1. Сумма чисел.

Есть вот такой лог, файл test1:
[18/Nov/2015 21:18:03] {pktdrop} Last message repeated 4 times
[18/Nov/2015 21:18:03] {pktdrop} Last message repeated 3 times
[18/Nov/2015 21:18:03] {pktdrop} Last message repeated 13 times
[18/Nov/2015 21:18:03] {pktdrop} Last message repeated 8 times
[18/Nov/2015 21:18:03] {pktdrop} Last message repeated 3 times

Надо посчитать сколько раз повторялось сообщение.

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

Что бы вывести только эти числа даем команду:
[k@redpc ~]$ awk -F ' ' '{print $7}' test1
4
3
13
8
3

Суммируем эти числа:
[k@redpc ~]$ awk -F ' ' '{print $7}' test1 | awk '{ x += $0 } END {print x}'
31

или можно сразу так:
[k@redpc ~]$  awk '{ x += $7 } END {print x}' test1
31


20150903

Установка VMwareTools на Centos.

1. Включаем ВМ.

2. Подключаем из esxi клиента образ с vmwaretools.
Правой кнопкой мыши по ВМ -> Guest -> Install/Upgrade VMware Tools

3. Монтируем cdrom с образом.
root@sbc2 ~
# mount /dev/cdrom /mnt
mount: block device /dev/sr0 is write-protected, mounting read-only

root@sbc2 ~
# ll /mnt/
total 62915
-r-xr-xr-x 1 root root     1970 Aug 22  2014 manifest.txt
-r-xr-xr-x 1 root root     1850 Aug 22  2014 run_upgrader.sh
-r--r--r-- 1 root root 63024310 Aug 22  2014 VMwareTools-9.4.10-2068191.tar.gz
-r-xr-xr-x 1 root root   693484 Aug 22  2014 vmware-tools-upgrader-32
-r-xr-xr-x 1 root root   702400 Aug 22  2014 vmware-tools-upgrader-64

4. Распаковываем архив. 
root@sbc2 ~ 
# mkdir vmtool

root@sbc2 ~ 
# cd vmtool/

root@sbc2 vmtool 
# tar zxpf /mnt/VMwareTools-9.4.10-2068191.tar.gz 

root@sbc2 vmtool 
# ll
total 4
drwxr-xr-x 7 root root 4096 Aug 22  2014 vmware-tools-distrib

root@sbc2 vmtool 
# cd vmware-tools-distrib/
root@sbc2 vmware-tools-distrib 
# ll
total 480
drwxr-xr-x  2 root root   4096 Aug 22  2014 bin
drwxr-xr-x  2 root root   4096 Aug 22  2014 doc
drwxr-xr-x  5 root root   4096 Aug 22  2014 etc
-rw-r--r--  1 root root 265487 Aug 22  2014 FILES
-rw-r--r--  1 root root   2538 Aug 22  2014 INSTALL
drwxr-xr-x  2 root root   4096 Aug 22  2014 installer
drwxr-xr-x 14 root root   4096 Aug 22  2014 lib
-rwxr-xr-x  1 root root 197302 Aug 22  2014 vmware-install.pl

5. Ставим. На все вопросы отвечаем по дефолту, просто жмем Enter.
root@sbc2 vmware-tools-distrib 
# ./vmware-install.pl 
Creating a new VMware Tools installer database using the tar4 format.

Installing VMware Tools.

In which directory do you want to install the binary files? 
[/usr/bin] 

What is the directory that contains the init directories (rc0.d/ to rc6.d/)? 
[/etc/rc.d] 

What is the directory that contains the init scripts? 
[/etc/rc.d/init.d] 

In which directory do you want to install the daemon files? 
[/usr/sbin] 

In which directory do you want to install the library files? 
[/usr/lib/vmware-tools] 

The path "/usr/lib/vmware-tools" does not exist currently. This program is 
going to create it, including needed parent directories. Is this what you want?
[yes] 

In which directory do you want to install the documentation files? 
[/usr/share/doc/vmware-tools] 

The path "/usr/share/doc/vmware-tools" does not exist currently. This program 
is going to create it, including needed parent directories. Is this what you 
want? [yes] 

The installation of VMware Tools 9.4.10 build-2068191 for Linux completed 
successfully. You can decide to remove this software from your system at any 
time by invoking the following command: "/usr/bin/vmware-uninstall-tools.pl".

Before running VMware Tools for the first time, you need to configure it by 
invoking the following command: "/usr/bin/vmware-config-tools.pl". Do you want 
this program to invoke the command for you now? [yes] 

Initializing...

Making sure services for VMware Tools are stopped.

Found a compatible pre-built module for vmci.  Installing it...


Found a compatible pre-built module for vsock.  Installing it...

The module vmxnet3 has already been installed on this system by another 
installer or package and will not be modified by this installer.

Use the flag --clobber-kernel-modules=vmxnet3 to override.

The module pvscsi has already been installed on this system by another 
installer or package and will not be modified by this installer.

Use the flag --clobber-kernel-modules=pvscsi to override.

The module vmmemctl has already been installed on this system by another 
installer or package and will not be modified by this installer.

Use the flag --clobber-kernel-modules=vmmemctl to override.

The VMware Host-Guest Filesystem allows for shared folders between the host OS 
and the guest OS in a Fusion or Workstation virtual environment.  Do you wish 
to enable this feature? [no] 

Found a compatible pre-built module for vmxnet.  Installing it...

The vmblock enables dragging or copying files between host and guest in a 
Fusion or Workstation virtual environment.  Do you wish to enable this feature?
[no] 

VMware automatic kernel modules enables automatic building and installation of
VMware kernel modules at boot that are not already present. This feature can be

enabled/disabled by re-running vmware-config-tools.pl.

Would you like to enable VMware automatic kernel modules?
[no] 

No X install found.

Creating a new initrd boot image for the kernel.

vmware-tools start/running
The configuration of VMware Tools 9.4.10 build-2068191 for Linux for this 
running kernel completed successfully.

You must restart your X session before any mouse or graphics changes take 
effect.

You can now run VMware Tools by invoking "/usr/bin/vmware-toolbox-cmd" from the
command line.

To enable advanced X features (e.g., guest resolution fit, drag and drop, and 
file and text copy/paste), you will need to do one (or more) of the following:
1. Manually start /usr/bin/vmware-user
2. Log out and log back into your desktop session; and,
3. Restart your X session.

Enjoy,

--the VMware team



20150902

Быстрые заметки по APC

2. Переключить web интерфейс обратно на http.
apc>web -S http
E002: Success
Reboot required for change to take effect.

apc>reboot
E000: Success
Reboot Management Interface
Enter 'YES' to continue or <ENTER> to cancel : yes

Rebooting...


1. Перезагрузка карты управления.
Из CLI
apc>reboot
E000: Success
Reboot Management Interface
Enter 'YES' to continue or <ENTER> to cancel : yes
Rebooting...

Сам ИБП продолжит работать. 


20150830

Насильно применить конфигурацию на развалившемся кластере состоящим из двух Juniper SRX.

Предположим что есть кластер на нодах которого, в результате неудачного обновления, стоят разные версии Junos (ну и там еще data-link порвали).

{primary:node0}[edit]
root@srx-n0#  run show system software
node0:
--------------------------------------------------------------------------
Information for junos:

Comment:
JUNOS Software Release [12.1X46-D35.1]

node1:
--------------------------------------------------------------------------
Information for junos:

Comment:
JUNOS Software Release [12.1X47-D25.4]

Обе RG работают на node0.
{primary:node0}[edit]
root@srx-n0# run show chassis cluster status
Monitor Failure codes:
    CS  Cold Sync monitoring        FL  Fabric Connection monitoring
    GR  GRES monitoring             HW  Hardware monitoring
    IF  Interface monitoring        IP  IP monitoring
    LB  Loopback monitoring         MB  Mbuf monitoring
    NH  Nexthop monitoring          NP  NPC monitoring            
    SP  SPU monitoring              SM  Schedule monitoring

Cluster ID: 3
Node   Priority Status         Preempt Manual   Monitor-failures

Redundancy group: 0 , Failover count: 1
node0  100      primary        no      no       None          
node1  1        secondary      no      no       None          

Redundancy group: 1 , Failover count: 1
node0  0        primary        no      no       IF CS        
node1  0        secondary      no      no       IF CS

Применить какие-либо изменения в конфигурации нельзя - srx ругается:

{primary:node0}[edit]
root@srx-n0# commit check
node0:
configuration check succeeds
error: error communicating with
error: remote commit-configuration failed on node1
error: configuration check-out failed
error:
Connection to node1 has been broken
error: remote unlock-configuration failed on node1

и 

{primary:node0}[edit]
root@srx-n0# commit 
node0: 

configuration check succeeds
error: 
Connection to node1 has been broken
warning: pull configuration failed, fallback to push configuration method
error: remote load-configuration failed on node1
error: remote unlock-configuration failed on node1

Поиск по подобным ошибкам выводит на команду "commit synchronize force".
В моем случае она не сработала.

{primary:node0}[edit]
root@srx-n0# commit synchronize force
node0:
configuration check succeeds
error:
Connection to node1 has been broken
warning: pull configuration failed, fallback to push configuration method
error: remote load-configuration failed on node1
error: remote unlock-configuration failed on node1


Для меня решением была скрытая команда "commit force", конфигурация применилась только на одной ноде.
{primary:node0}[edit]
root@msk-02-srx3-n0# commit fo                
                              ^
syntax error.
root@msk-02-srx3-n0# commit force          
node0:

commit complete

Вот.

20150827

Процесс установки сигнатур application-identification на кластер из srx.

В отличии от лицензий все действия с сигнатурами можно делать только на основной ноде.

Скачиваем сигнатуры.
{primary:node0}
root@srx-n0> request services application-identification download
Please use command
        "request services application-identification download status" to check download status

{primary:node0}
root@srx-n0> request services application-identification download status  
Fetching/Uncompressing https://signatures.juniper.net/xmlupdate/226/Libqmprotocols/2528/libqmprotocols.tgz

{primary:node0}
root@srx-n0> request services application-identification download status    
Downloading application package 2528 succeed.


Инсталируем сигнатуры.
{primary:node0}
root@srx-n0> request services application-identification install 
node0:
--------------------------------------------------------------------------
Please use command
        "request services application-identification install status" to check install status

node1:
--------------------------------------------------------------------------
Please use command
        "request services application-identification install status" to check install status


Следим за процессом. 
{primary:node0}
root@srx-n0> request services application-identification install status 
node0:
--------------------------------------------------------------------------
Checking compatibility of application package version 2528 ...

node1:
--------------------------------------------------------------------------
Checking compatibility of application package version 2528 ...


{primary:node0}
root@srx-n0> request services application-identification install status    
node0:
--------------------------------------------------------------------------
Installed Application package (2528) successfully in RE,
Application package and Protocol bundle installation in pfe is in progress

node1:
--------------------------------------------------------------------------
Cleaning up legacy configurations in Junos configuration ...


{primary:node0}
root@srx-n0> request services application-identification install status    
node0:
--------------------------------------------------------------------------
Installed Application package (2528) successfully in RE,
Application package and Protocol bundle installation in pfe is in progress

node1:
--------------------------------------------------------------------------
Installed Application package (2528) successfully in RE,
Application package and Protocol bundle installation in pfe is in progress



{primary:node0}
root@srx-n0> request services application-identification install status    
node0:
--------------------------------------------------------------------------
Installed
        Application package (2528) and Protocol bundle successfully

node1:
--------------------------------------------------------------------------
Installed Application package (2528) successfully in RE,
Application package and Protocol bundle installation in pfe is in progress


{primary:node0}
root@srx-n0> request services application-identification install status    
node0:
--------------------------------------------------------------------------
Installed
        Application package (2528) and Protocol bundle successfully

node1:
--------------------------------------------------------------------------
Installed
        Application package (2528) and Protocol bundle successfully


Проверяем версии.
{primary:node0}
root@srx-n0> show services application-identification version 
node0:
--------------------------------------------------------------------------

  Application package version: 2528

node1:
--------------------------------------------------------------------------

  Application package version: 2528

Смотрим на группы сигнатур.
{primary:node0}
root@srx-n0> show services application-identification group summary 
node0:
--------------------------------------------------------------------------
Application Group(s): 90
Application Groups                                Disabled  ID 
  junos:behavioral                                 No        92       
  junos:unassigned                                 No        91       
  junos:web:proxy                                  No        48       
  junos:remote-access:interactive-desktop          No        34       
  junos:infrastructure:mobile                      No        57       
  junos:web:wiki                                   No        54       
...


node1:
--------------------------------------------------------------------------
Application Group(s): 90
Application Groups                                Disabled  ID 
  junos:behavioral                                 No        92       
  junos:unassigned                                 No        91       
  junos:web:proxy                                  No        48       
  junos:remote-access:interactive-desktop          No        34       
  junos:infrastructure:mobile                      No        57       
  junos:web:wiki                                   No        54       
...

Ставим триальную лицензию на кластер из srx.

Лицензии надо ставить на каждой ноде отдельно.

Сначала будем ставить лицензии на node0 которая является главной нодой для RG0 (там, где RE крутится).
root@srx-n0> show chassis cluster status
Monitor Failure codes:
    CS  Cold Sync monitoring        FL  Fabric Connection monitoring
    GR  GRES monitoring             HW  Hardware monitoring
    IF  Interface monitoring        IP  IP monitoring
    LB  Loopback monitoring         MB  Mbuf monitoring
    NH  Nexthop monitoring          NP  NPC monitoring            
    SP  SPU monitoring              SM  Schedule monitoring
    CF  Config Sync monitoring

Cluster ID: 3
Node   Priority Status         Preempt Manual   Monitor-failures

Redundancy group: 0 , Failover count: 3
node0  100      primary        no      no       None          
node1  1        secondary      no      no       None          

Redundancy group: 1 , Failover count: 1
node0  100      primary        no      no       None          
node1  0        secondary      no      no       IF            

Запрашиваем лицензии.
{primary:node0}
root@srx-n0> request system license update trial

Trying to update trial license keys from https://ae1.juniper.net, use 'show system license' to check status.

Смотрим лицензии. 
{primary:node0}
root@srx-n0> show system license    
License usage: 
                                 Licenses     Licenses    Licenses    Expiry
  Feature name                       used    installed      needed 
  av_key_kaspersky_engine               0            1           0    2015-09-26 03:00:00 GMT-3
  anti_spam_key_sbl                     0            1           0    2015-09-26 03:00:00 GMT-3
  wf_key_surfcontrol_cpa                0            1           0    2015-09-26 03:00:00 GMT-3
  idp-sig                               0            1           0    2015-09-26 03:00:00 GMT-3
  dynamic-vpn                           0            2           0    permanent
  ax411-wlan-ap                         0            2           0    permanent
  appid-sig                             0            1           0    2015-09-26 03:00:00 GMT-3
  av_key_sophos_engine                  0            1           0    2015-09-26 03:00:00 GMT-3
  wf_key_websense_ewf                   0            1           0    2015-09-26 03:00:00 GMT-3

Licenses installed: 
....

Все хорошо. 

Руками переключаемся на node1. 
{primary:node0}
root@srx-n0> request chassis cluster failover redundancy-group 0 node 1 
node1:
--------------------------------------------------------------------------
Initiated manual failover for redundancy group 0

Переключилось.
root@srx-n1> show chassis cluster status      
Monitor Failure codes:
    CS  Cold Sync monitoring        FL  Fabric Connection monitoring
    GR  GRES monitoring             HW  Hardware monitoring
    IF  Interface monitoring        IP  IP monitoring
    LB  Loopback monitoring         MB  Mbuf monitoring
    NH  Nexthop monitoring          NP  NPC monitoring              
    SP  SPU monitoring              SM  Schedule monitoring
    CF  Config Sync monitoring
 
Cluster ID: 3
Node   Priority Status         Preempt Manual   Monitor-failures

Redundancy group: 0 , Failover count: 1
node0  100      secondary      no      yes      None           
node1  255      primary        no      yes      None           

Redundancy group: 1 , Failover count: 0
node0  100      primary        no      no       None           
node1  0        secondary      no      no       IF     

Запрашивем лицензии на node1.
{primary:node1}
root@srx-n1> request system license update trial 
Trying to update trial license keys from https://ae1.juniper.net, use 'show system license' to check status.
       
Все загрузилось.  
{primary:node1}
root@msk-02-srx3-n1> show system license                    
License usage: 
                                 Licenses     Licenses    Licenses    Expiry
  Feature name                       used    installed      needed 
  av_key_kaspersky_engine               0            1           0    2015-09-26 03:00:00 GMT-3
  anti_spam_key_sbl                     0            1           0    2015-09-26 03:00:00 GMT-3
  wf_key_surfcontrol_cpa                0            1           0    2015-09-26 03:00:00 GMT-3
  idp-sig                               0            1           0    2015-09-26 03:00:00 GMT-3
  dynamic-vpn                           0            2           0    permanent
  ax411-wlan-ap                         0            2           0    permanent
  appid-sig                             0            1           0    2015-09-26 03:00:00 GMT-3
  av_key_sophos_engine                  0            1           0    2015-09-26 03:00:00 GMT-3
  wf_key_websense_ewf                   0            1           0    2015-09-26 03:00:00 GMT-3

Licenses installed: 
...

Все. 

20150810

Быстрые заметки по Huawei

1. Посмотреть серийный номер коммутатора.
<s5328>display elabel
...
[Board Properties]
BoardType=CX77XC
BarCode=21023516101234567890
Item=02351300
Description=Quidway S5328C-EI,CX7Z128CM,S5328C-EI Mainframe(24 10/100/1000Base-T,Chassis,Dual Slots of power,Without Flexible Card and Power Module)
Manufactured=2012-10-07
VendorName=Huawei
IssueNumber=00
CLEICode=                                

BOM=                                    

Серийник указан в поле BarCode.

Большая дока с указанием где искать серийные номера на оборудовании huawei:
http://huaweienterpriseusa.com/system/files/resources/How%20to%20collect%20SN.pdf?nid=797

20150726

Логирование информации о проходящем через Juniper SRX трафике.

Точка съема информации.
Снимать информацию о трафике можно как минимум с двух точек:
-- Правила файрвола, уровень [edit firewall ] 
Тут видно просто факт прохождение пакета через фильтр, действие примененное к пакету, ip адреса и порты, протокол и  интерфейс.

-- Правила политик безопасности, уровень [edit security policies] 
На этом уровне можно получить гораздо больше информации. Здесь можно посмотреть номер сессии, ip адреса до и после ната, имена политик безопасности и пр.

Формат логов файрвола.
На syslog сервер логи приходят в таком формате:
Jul 24 04:50:49 srx srx PFE_FW_SYSLOG_IP: FW: fe-0/0/3.0   D  tcp 1.1.1.1 9.9.9.9 53291 33434 (1 packets)
Jul 24 04:50:50 srx srx PFE_FW_SYSLOG_IP: FW: fe-0/0/3.0   R udp 2.2.2.2 9.9.9.9 53971 5060
 (1 packets)
Jul 24 04:50:52 srx srx PFE_FW_SYSLOG_IP: FW: fe-0/0/3.0   A  tcp 3.3.3.3 9.9.9.9  47321 443 (1 packets)

* Код (тип) сообщения = PFE_FW_SYSLOG_IP:, удобно использовать для настройки фильтров на syslog сервере.
* Указатель на источник сообщений = FW:, сообщения которые были получены в соответствии с настройками фильтров файрвола.
* Интерфейс на котором висит фильтр = fe-0/0/3.0.
* Действие = D, R, A (discard, reject, accept).
* Протокол = tcp, udp, ospf и пр.
* Адрес источника = 1.1.1.1 
* Адрес назначение = 9.9.9.9
* Порт источника = 53291
* Порт назначения = 33434
* Количество пакетов = (1 packets), не припомню что бы было больше.

Формат логов политик безопасности.
Сообщения от политик безопасности могут быть трех видов:
-- создание сессии, указатель RT_FLOW_SESSION_CREATE
-- запрет сессии, указатель RT_FLOW_SESSION_DENY
-- закрытие сессии, указатель RT_FLOW_SESSION_CLOSE

Логи снимались с srx на котором работает AppFW. 
AppFW добавляет в лог несколько полей.

RT_FLOW_SESSION_CREATE
На syslog сервер логи приходят в таком формате:
2015-07-25T10:49:35.408+03:00 srx RT_FLOW:  RT_FLOW_SESSION_CREATE: session created 10.90.80.50/55871->87.240.131.99/80 junos-http 9.9.9.9/29419->87.240.131.99/80 src-nat-rule1 None 6 DEBUG-DENY-ANY-LOG VPN PX 21949 N/A(N/A) gr-0/0/0.14 HTTP INCONCLUSIVE No

###Стандартные поля###
* Код (тип) сообщения = RT_FLOW
* Адрес источника (source-address) = 10.90.80.50
* Порт источника (source-port) = 55871
* Адрес назначение (destination-address) = 87.240.131.99
* Порт назначение (destination-port) = 80
* Имя приложения (service-name) = junos-http
* Адрес источника после nat (nat-source-address) = 9.9.9.9
* Порт источника после nat (nat-source-port) = 29419
* Адрес назначение после nat (nat-destination-address) = 87.240.131.99
* Порт назначение после nat (nat-destination-port) = 80
* Имя правила по которому делался source nat (src-nat-rule-name) = src-nat-rule1
* Имя правила по которому делался destination nat (dst-nat-rule-name) = None
###N/A т.к. в данном случае srx не делает destination nat###
* Номер протокола (protocol-id) = 6, см. /etc/protocols (6 - tcp, 17 - udp, 1 - icmp)
* Имя политики безопасности (policy-name) = DEBUG-DENY-ANY-LOG
* Зона из которой идет трафик (source-zone-name) = VPN
* Зона в которую идет трафик (destination-zone-name) = PX
* Номер сессии (session-id-32) = 21949
* Имя пользователя (username) = N/A
* Принадлежность пользователя  (roles) = N/A
###N/A т.к. на srx не настроено source-identity###
* Интерфейс через который пришел трафик (packet-incoming-interface) = gr-0/0/0.14
###Поля AppFW###
* Тип приложения (application) = HTTP
* Тип вложенного приложения (nested-application)  = INCONCLUSIVE
###srx пока не разобрался что это за приложение и ставит тип incocnclusive т.к. прошел только syn пакет###
* Шифрование (encrypted) = No

RT_FLOW_SESSION_DENY
На syslog сервер логи приходят в таком формате:
2015-07-25T10:49:35.461+03:00 srx RT_FLOW: RT_FLOW_SESSION_DENY: session denied 10.90.80.50/55871->87.240.131.99/80 junos-http 6(0) DEBUG-DENY-ANY-LOG VPN PX HTTP VKONTAKTE N/A(N/A) gr-0/0/0.14 No appfw reject

* Код (тип) сообщения = RT_FLOW
* Адрес источника (source-address) = 10.90.80.50
* Порт источника (source-port) = 55871
* Адрес назначение (destination-address) = 87.240.131.99
* Порт назначение (destination-port) = 80
* Имя приложения (service-name) = junos-http
* Номер протокола (protocol-id) = 6, см. /etc/protocols (6 - tcp, 17 - udp, 1 - icmp)
* Тип icmp (icmp-type)  = (0), указывает на тип icmp пакета который был отброшен.
###Если это был не icmp пакет, то в этом поле всегда будет стоять "(0)"###
* Имя политики безопасности (policy-name) = DEBUG-DENY-ANY-LOG
* Зона из которой идет трафик (source-zone-name) = VPN
* Зона в которую идет трафик (destination-zone-name) = PX
* Тип приложения (application) = HTTP
* Тип вложенного приложения (nested-application)  = VKONTAKTE
* Имя пользователя (username) = N/A
* Принадлежность пользователя  (roles) = N/A
###N/A т.к. на srx не настроено source-identity###
* Интерфейс через который пришел трафик (packet-incoming-interface) = gr-0/0/0.14
* Шифрование (encrypted) = No
* Указатель на то как и кем была отвергнута сессия (reason) = appfw reject
###В данном случае сессию закрыл AppFW действием reject.  Без  AppFW, в этом поле будет стоять просто deny или reject###

RT_FLOW_SESSION_CLOSE
На syslog сервер логи приходят в таком формате:
2015-07-25T10:49:37.211+03:00 srx RT_FLOW: RT_FLOW_SESSION_CLOSE:  session closed TCP RST: 10.90.80.50/55871->87.240.131.99/80 junos-http 9.9.9.9/29419->87.240.131.99/80 src-nat-rule1 None 6 DEBUG-DENY-ANY-LOG VPN PX 21948 3(440) 7(6830) 2 HTTP VKONTAKTE N/A(N/A) gr-0/0/0.14 No

* Причина закрытия сессии (reason) = ТCP RST, с обоих сторон был получен RST (??).
В данном случае RST послал srx.
###Остальные возможные причины см. ниже.###
* Адрес источника (source-address) = 10.90.80.50
* Порт источника (source-port) = 55871
* Адрес назначение (destination-address) = 87.240.131.99
* Порт назначение (destination-port) = 80
* Имя приложения (service-name) = junos-http
* Адрес источника после nat (nat-source-address) = 9.9.9.9
* Порт источника после nat (nat-source-port) = 29419
* Адрес назначение после nat (nat-destination-address) = 87.240.131.99
* Порт назначение после nat (nat-destination-port) = 80
* Имя правила по которому делался source nat (src-nat-rule-name) = src-nat-rule1
* Имя правила по которому делался destination nat (dst-nat-rule-name) = None
###N/A т.к. в данном случае srx не делает destination nat###
* Номер протокола (protocol-id) = 6, см. /etc/protocols (6 - tcp, 17 - udp, 1 - icmp)
* Имя политики безопасности (policy-name) = DEBUG-DENY-ANY-LOG
* Зона из которой идет трафик (source-zone-name) = VPN
* Зона в которую идет трафик (destination-zone-name) = PX
* Номер сессии (session-id-32) = 21949
* Количество пакетов от источника (packets-from-client) = 3
* Количество байт от источника (bytes-from-client) = (440)
* Количество пакетов от назначения (packets-from-server) = 7
* Количество байт от назначени (bytes-from-server) = (6830)
* Длительность сессии в секундах (elapsed-time) = 2
* Тип приложения (application) = HTTP
* Тип вложенного приложения (nested-application)  = VKONTAKTE
* Имя пользователя (username) = N/A
* Принадлежность пользователя  (roles) = N/A
###N/A т.к. на srx не настроено source-identity###
* Интерфейс через который пришел трафик (packet-incoming-interface) = gr-0/0/0.14
* Шифрование (encrypted) = No

Причины закрытия сессии:
** idle Timeout - сессия закрылась по таймауту. По дефолту таймаут для tcp составляет 1800 секунд, для udp 60 секунд.
** unset - невозможно открыть сессию из-за проблем на control-plane, например кончилась память.
** ТCP FIN - получен RST.
** ТCP FIN - получен FIN.
** response received - был полчен ответ, напримен был получен icmp-reply на ранее посланный icmp-echo.
** ICMP error - пришел icmp пакет с сообщение об ошибке.
** aged out - вышло время жизни активной сессии.
** ALG - сессию закрыло ALG.
** HA
** auth 
** IDP - внутренняя ошибка idp.
** synproxy failure 
** synproxy limit
** parent closed - закрылась родительская сессия.
** CLI - сессию закрыли комендой из cli.
** CP NACK
** CP delete
** policy delete
** fwd session
** multicast route change
** first path reroute, session recreated
** source NAT allocation failure
** other
** error create IKE pass-through template 
** IKE pass-through chils session ageout 
** sess timeout on panding state
** unknown - хз, чё=) 


20150723

Настройка port-mirroring на Juniper SRX.

Настраиваем интерфейс srx к которому будет подключена машина с анализатором.
set interfaces fe-0/0/1 description server-name/port
set interfaces fe-0/0/1 unit 0 description span-port
set interfaces fe-0/0/1 unit 0 family inet address 10.11.12.1/30

set security zones security-zone MGMT interfaces fe-0/0/1.0 \
host-inbound-traffic system-services ping

set forwarding-options port-mirroring input rate 1
set forwarding-options port-mirroring input run-length 10
set forwarding-options port-mirroring family inet output interface fe-0/0/1.0 next-hop 10.11.12.2

Настраиваем правило файрволла для захвата трафика который хотим мирорить.
set firewall family inet filter PORT-MIRROR term PERMIT-ALL then port-mirror
set firewall family inet filter PORT-MIRROR term PERMIT-ALL then accept

Настраиваем интерфейс srx с которого будет мирорить трафик. 
set interfaces gr-0/0/0 unit 14 family inet filter input PORT-MIRROR
set interfaces gr-0/0/0 unit 14 family inet filter output PORT-MIRROR

###Замечание.
На машине на которой работает анализатор надо обязательно настроить ip который задан в настройках srx. Если адрес не настраивать, а просто перевести порт в promiscuous режим, работать не будет. Srx не будет отправляться трафик в порт fe-0/0/1, скорее всего потому что не видит arp для 10.11.12.2 (??). 

В итоге конфиг srx должен выглядеть так:
...
fe-0/0/1 {
    description server-name/port;
    unit 0 {
        description span-port;
        family inet {
            address 10.11.12.1/30;
        }
    }
}
...
security-zone MGMT {
    interfaces {
        fe-0/0/1.0 {
            host-inbound-traffic {
                system-services {
                    ping;
                }
            }
        }
    }
}
...
forwarding-options {
    port-mirroring {
        input {
            rate 1;
            run-length 10;
        }
        family inet {
            output {
                interface fe-0/0/1.0 {
                    next-hop 10.11.12.2;
                }
            }
        }
    }
}
...
firewall {
    family inet {
        filter PORT-MIRROR {
            term PERMIT-ALL {
                then {
                    port-mirror;
                    accept;
                }
            }
        }
    }
}
...
}
gr-0/0/0 {
    unit 14 {
        tunnel {
            source 1.1.1.1;
            destination 1.1.1.2;
        }
        family inet {
            filter {
                input PORT-MIRROR;
                output PORT-MIRROR;
            }
            address 10.11.12.5/30;
        }
    }





20150722

Быстрые заметки по wireshark\tcpdump

4. Увидеть номер vlan. 

tcpdump -nnee -i eth1 -c 10


3. Захватить CDP.
tcpdump -nn -vvv -i en0 -s 1500 -c 1 'ether[20:2] == 0x2000


2. Захватить мультикаст и бродкаст.
[root@blackpc ~]# tcpdump -i eth1 -n -c 300 "broadcast or multicast"

1. Посмотреть SNI (Server Name Indication) в SSL трафике. 
Wireshark
Применяем фильтры (в зависимости от версии WS):
- ssl.handshake.extensions_server_name
- ssl.handshake.extension.type == 0
- ssl.handshake.extension.type == "server_name"

Далее в отфильтрованном смотрим поле "Server Name:".
Путь:
Secure Sockets Layer -->
TLS Record Layer --> 
Handshake Protocol: Client Hello -->
Extension: server_name -->
Server Name Indication extension -->
Server Name: xakep.ru

Используем  ssl.handshake.extension.data contains "xakep.ru" когда надо отфильтровать пакеты с определенным SNI.

Tcpdump
Команда:
tcpdump -i eth1 -s 1500 -X  '(tcp[((tcp[12:1] & 0xf0) >> 2)+5:1] = 0x01) and (tcp[((tcp[12:1] & 0xf0) >> 2):1] = 0x16)' 

Пример:
[root@blackpc ~]# tcpdump -i eth1 -s 1500 -X  '(tcp[((tcp[12:1] & 0xf0) >> 2)+5:1] = 0x01)' and 
'(tcp[((tcp[12:1] & 0xf0) >> 2):1] = 0x16)' and host 178.248.232.27
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth1, link-type EN10MB (Ethernet), capture size 1500 bytes
14:44:29.950497 IP x.x.x.x.60044 > 178.248.232.27.https: Flags [P.], seq 2690445558:2690446075, ack 2960121525, win 115, options [nop,nop,TS val 100379054 ecr 1195184343], length 517
0x0000:  4500 0239 5960 4000 4006 769e c0a8 0d04  E..9Y`@.@.v.....
0x0010:  b2f8 e81b ea8c 01bb a05c f0f6 b06f deb5  .........\...o..
0x0020:  8018 0073 6aec 0000 0101 080a 05fb a9ae  ...sj...........
0x0030:  473d 10d7 1603 0102 0001 0001 fc03 0347  G=.............G
0x0040:  edab 33fe a68e 1625 904e 404c d99c dc12  ..3....%.N@L....
0x0050:  645e de6e f35f d2a3 5fe4 920a 51a6 8820  d^.n._.._...Q...
0x0060:  cf3b 1e81 07e6 a15c 5343 fb04 3e7e a684  .;.....\SC..>~..
0x0070:  ba9e 5fd3 5ad5 fcf6 5969 21a2 0035 bdbe  .._.Z...Yi!..5..
0x0080:  0024 c02b c02f 009e c00a c009 c013 c014  .$.+./..........
0x0090:  c007 c011 0033 0032 0039 009c 002f 0035  .....3.2.9.../.5
0x00a0:  000a 0005 0004 0100 018f 0000 000d 000b  ................
0x00b0:  0000 0878 616b 6570 2e72 75ff 0100 0100  ...xakep.ru.....
0x00c0:  000a 0008 0006 0017 0018 0019 000b 0002  ................
0x00d0:  0100 0023 00b0 8aec 9689 2d9d 7387 24ef  ...#......-.s.$.
0x00e0:  1c8d e0b6 08ce 283b c5a7 174b 09cd 43db  ......(;...K..C.
0x00f0:  87e3 3d9d f4ff 6cc8 c327 a9d3 9537 8e29  ..=...l..'...7.)
0x0100:  637f 7f7d e146 401c 84c5 b62d 38f6 284c  c..}.F@....-8.(L
0x0110:  656a d3ab c460 77c2 d024 2b09 cf7c 94ca  ej...`w..$+..|..
0x0120:  a603 e410 38c9 4154 8ed5 4e67 b871 60ee  ....8.AT..Ng.q`.
0x0130:  7ad0 e003 ccf4 dd49 67cf 32e8 881d 740d  z......Ig.2...t.
0x0140:  5ebc 99f3 d08a cf2c f24a 0a28 b5ea 3157  ^......,.J.(..1W
0x0150:  78fb c9f0 f2ef 87aa bdb2 822c 1c61 d47c  x..........,.a.|
0x0160:  68b7 b55c 0440 bf26 47f5 d5df acbf 6b3e  h..\.@.&G.....k>
0x0170:  d45d 7dc1 dd72 0abb abb2 183d 88a1 9237  .]}..r.....=...7
0x0180:  4cc4 9bfa 70ed 3374 0000 0010 001a 0018  L...p.3t........
0x0190:  0873 7064 792f 332e 3105 6832 2d31 3408  .spdy/3.1.h2-14.
0x01a0:  6874 7470 2f31 2e31 0005 0005 0100 0000  http/1.1........
0x01b0:  0000 1200 0000 0d00 1200 1004 0105 0102  ................
0x01c0:  0104 0305 0302 0304 0202 0200 1500 6a00  ..............j.
0x01d0:  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x01e0:  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x01f0:  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x0200:  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x0210:  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x0220:  0000 0000 0000 0000 0000 0000 0000 0000  ................
0x0230:  0000 0000 0000 0000 00                   .........

20150718

Перенос MediaWiki на новый сервер.

Создаем на новом сервер mysql базу и пользователя.
root@newserver# mysql -u root -p
mysql> create database wiki_db;
mysql> grant all privileges on wiki_db.* to wiki_user@localhost identified by 'pass';
mysql> flush privileges;

Копируем файлы mediawiki на новый сервер.
root@oldserver# cd /var/www/html
root@oldserver# tar zcvf /root/bup/mediawiki-$(date '+%Y%m%d').tgz mediawiki

root@oldserver# scp /root/bup/mediawiki-xxx.tgz root@newserver:/root/wiki-bup
root@newserver's password:
mediawiki-xxx.tgz                                                         100%   23MB  11.8MB/s   00:02

Создаем дамп базы на старом сервере и копируем на новый.
root@oldserver# mysqldump --add-locks --complete-insert -u wiki_user -p wiki_db \
> /root/bup/wiki_db-$(date '+%Y%m%d').sql

root@oldserver# scp /root/bup/wiki_db-xxx.sql root@newserver:/root/wiki-bup
root@newserver's password:
wiki_db-xxx.sql                                                             100% 4757KB   4.7MB/s   00:00

На новом сервере заливаем базу из дампа.
root@newserver# mysql -u wiki_user -p wiki_db < /root/wiki-bup/wiki_db-xxx.sql

Распаковываем файлы mediawiki новом сервере.
root@newserver: tar xvf /root/wiki-bup/mediawiki-xxx.tgz -C /var/www/                                                               
На новом сервере правим httpd.
vi /etc/httpd/conf.d/vhosts.conf
...
<VirtualHost *:80>
     ServerAdmin a@b.c
     DocumentRoot /var/www/mediawiki
     ServerName wiki.b.c
     ErrorLog logs/mediawiki_err_log
     CustomLog logs/mediawiki_acc_log common
</VirtualHost>
...

vi /etc/httpd/conf.d/mediawiki.conf
...
Alias /mediawiki /var/www/html/mediawiki
Alias /view /var/www/html/mediawiki/index.php
...

Если новый сервер совсем свежий, на него только поставили минимальный LAMP, то надо доставить php-xml.
root@newserver# yum install php-xml 



LAMP на Centos6

LAMP
L - Linux
A - Apache
M - MySQL
P- PHP

Ставим.
# yum install httpd mysql-server php php-mysql

Запускаем apache.
# /etc/init.d/httpd start
Starting httpd:                                            [  OK  ]

Запускаем mysql. 
# /etc/init.d/mysqld start
Initializing MySQL database:  Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h bender.ermoshin.pro password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl

Please report any problems with the /usr/bin/mysqlbug script!

                                                                      [  OK  ]
Starting mysqld:                                           [  OK  ]

Делаем первичную настройку mysql.
# /usr/bin/mysql_secure_installation
Задаем пароль для root и везде отвечаем "y".
Set root password? [Y/n] y
Remove anonymous users? [Y/n] y
Disallow root login remotely? [Y/n] y
Remove test database and access to it? [Y/n] y
Reload privilege tables now? [Y/n] y

 Проверяем php.
# vi /var/www/html/info.php
Пишем.
<?php
phpinfo();
?>

Перзапускаем httpd и по http://server_ip/info.php должна появиться инфрмация о текущей версии php. 

Включаем автозагрузку.
# chkconfig --level 2345 httpd on
# chkconfig --level 2345 mysqld on



Быстрые заметки по vi

9. Работа с несколькими файлами.
В командном режиме.
Ctrl-w n - открыть новое окно
:new /path/to/file открыть файл в новом окне (горизонтальное разделение)
:vnew /path/to/file открыть файл в новом окне (вертикальное разделение)
:n /path/to/file открыть файл в текущем окне

Ctrl-w w - последовательно переключаться между окнами
Ctrl-w "стрелки" - переключиться на окно в определенном направлении
Ctrl-w "hjkl" - то же самое, h - влево, j - вниз, k-вверх, l-вправо
Ctrl-w "HJKL" - Перенести текущее окно в определенном направлении

:q - закрыть текущее окно
:qall - закрыть все окна разом
:wqall - записать изменения и закрыть все окна разом

8. Скопировать выделенный текст.
В командном режиме.
y - поместить выделенный текст в буфер
p -  скопировать выделенный текст (ниже курсора)

7. Выделить текст.
В командном режиме.
v+"стрелки" - выделить область
Shift-v - выделять целыми строчками
Ctrl-v - выделять блоком

6. Замена.
В командном режиме.
:s/что меняем/чем заменяем/ - найти и заменить первое совпадение в текущей строке.
:s/что меняем/чем заменяем/с - найти первое совпадение в текущей строке и спросить о замене.
:s/что меняем/чем заменяем/g - найти и заменить все совпадение в текущей строке.
:%s/что меняем/чем заменяем/g - найти и заменить все совпадение во всем файле.

5. Отмена отмены действия.
В командном режиме.
Ctrl-r или :red или :redo

4. Отмена действия. Отмена отмены действия.
В командном режиме.
u или :undo или :u

3. Удалить или вырезать строчку
В командном режиме.
dd

2. Скопировать строчку.
В командном режиме.
yy - поместить строчку в буфер
p -  скопировать строчку (ниже курсора)

1. Два режима:
* Командный - удаление строк, копирование, поиск по тексту, запись, выход и пр.
* Редактирования - сообствено само редактирование текста.

Переход между режимами:
* из командного в режим редактирования - нажать "a" (add, текст после курсора) или "i" (insert, текст перед курсором), внизу появится "-- INSERT --".
* из режима редактирования в командный в режим редактирования - нажать Esc.

20150713

Быстрые заметки по Exim

Сводка недоступна. Нажмите эту ссылку, чтобы открыть запись.

20150219

Быстрые заметки по procurve.


6. Сбрость конфиг. 
Из cli. 
Дать команду erase startup-config.

Находясь перед коммуатором.
-- Одновременно нажать кнопки reset и clear.
-- Отпустить кнопку reset когда зажгутся лампочки Power и Fault
Кнопку clear продолжаем держать. 
-- Когда начнут мигать лампочки линков на портах (запустится процесс само тестирования) можно отпускать кнопку clear. 

To execute the factory default reset on the switch, perform these steps:
1. Using pointed objects, simultaneously press both the Reset and Clear buttons on the front of the switch. The power and fault lights come on.
2. Continue to press the Clear button while releasing the Reset button.
3. When the Self Test LED begins to flash, release the Clear button.
The switch will then complete its self test and begin operating with its configuration restored to the factory default settings.
 
5. Сбросить незначительные\временные ошибки. 
Нажать reset.


Resetting the switch
When the switch is powered on. This action clears any temporary error  conditions that may have occurred and executes the switch self test.


4. Сбросить пароли. 
Нажать на одну секунду кнопку clear.
Конфинурация при этом не сбросится.  

Deleting Passwords 
When pressed by itself for at least one second, the button deletes any switch console access passwords that you may have configured. Use this feature if you have misplaced the password and need console access. This button is provided as a convenience, however if you are concerned with the security of the switch configuration and operation, you should make sure the switch is installed in a secure location. This button can be disabled by a CLI command.

3. Копирование конфигурации через com порт. 
Сидим на коммутторе через minicom, надо залить на него конфигурацию из бэкапа или с другого коммутатора. 
-- 


2. Перенос конфигурации между двумя коммутаторами. 
Есть два коммутатора hp2626-1 и hp2626-2. Надо перенести конфирурацию с hp2626-1 на hp2626-2
-- Копируем на tftp сервер конфигурацию коммутатора hp2626-1.
hp2626-1# copy startup-config tftp x.x.x.x hp2626-1-config

-- При необходимости редактируем файл hp2626-1-config, меняем hostname, ip адреса и пр.

-- Копируем с tftp сервера конфигурацию на коммутатор hp2626-2.
hp2626-2# copy tftp startup-config x.x.x.x hp2626-1-config
Device may be rebooted, do you want to continue [y/n]? y
Rebooting switch...

##Если на коммутаторе hp2626-1 был включен ssh и https, а на коммутаторе hp2626-2 нет, то возникнет следующая ошибка:

"line: 8. https cannot be enabled with no certificate present. To install a
self-signed certificate,
  * Use 'crypto key generate...' to install RSA key; then
  * Use 'crypto host-cert generate...' to install certificate.

line: 168. ssh cannot be enabled until a host key is configured (use 'crypto' command).
Corrupted download file."

Для решения проблемы создаем ключи и сертификаты для ssh и https:

hp2626-2(config)# crypto key generate ssh
Installing new RSA key.  If the key/entropy cache is

depleted, this could take up to a minute.

hp2626-2(config)# crypto key generate cert 1024 
Installing new RSA key.  If the key/entropy cache is
depleted, this could take up to a minute.

hp2626-m9(config)# crypto host-cert generate self-signed 
 MM/DD[/[YY]YY]        Validity start date for certificate.
 <cr>
Validity start date [01/01/1990]: 02/01/2015
Validity end date   [02/01/2016]: 02/01/2025
Common name            [0.0.0.0]: hp2626-2
Organizational unit  [Dept Name]: IT-Dept
Organization      [Company Name]: IT-Comp
City or location  [City]: Moscow
State name               [State]: MOW
Country code                [US]: RU

Пробуем еще раз загрузить новую конфигурацию:hp2626-2# copy tftp startup-config x.x.x.x hp2626-1-config
Device may be rebooted, do you want to continue [y/n]? y

Rebooting switch...




1. Обновление коммутатора.
-- Проверяем, что в обоих флешках у нас одинаковая версия софта, при необходимости копируем софт из primary флешки в secondary.

hp2626# sh flash
Image           Size(Bytes)   Date   Version
-----           ----------  -------- -------
Primary Image   : 3431516   08/22/07 H.10.45
Secondary Image : 2142958   05/19/03 H.07.31
Boot Rom Version: H.08.02
Current Boot    : Primary

hp2626# copy flash flash secondary

hp2626# sh flash
Image           Size(Bytes)   Date   Version
-----           ----------  -------- -------
Primary Image   : 3431516   08/22/07 H.10.45
Secondary Image : 3431516   08/22/07 H.10.45:
Boot Rom Version: H.08.02
Current Boot    : Primary

-- C tftp сервера закачиваем на коммутатор свежий софт.

hp2626# copy tftp flash x.x.x.x H_10_115.swi
...
Validating and Writing System Software to FLASH...
...

hp2626# sh flash
Image           Size(Bytes)   Date   Version
-----           ----------  -------- -------
Primary Image   : 3525464   04/09/14 H.10.115
Secondary Image : 3431516   08/22/07 H.10.45:
Boot Rom Version: H.08.02
Current Boot    : Primary

-- Задаем флешку с которой будем загружаться.
hp2626# boot system flash primary

##Коммутатор предложит перегрузиться. 

-- Если коммутатор загрузился и все хорошо, то копируем новый софт на secondary флешку.


20150206

Установка и настройка связки Rancid+ViewVC

Статья переехала -> https://mykb.ru/doku.php?id=topic:rancid


Rancid
-- Доставляем необходимые пакеты
# yum install cvs expect gcc MySQL-python telnet

-- Скачиваем и распаковываем свежую версию Rancid.
# wget ftp://ftp.shrubbery.net/pub/rancid/rancid-3.1.tar.gz
# tar -zxvf rancid-3.1.tar.gz

-- Добавляем группу netadm в которую впоследствии будет добавлен пользователь apache.
# groupadd netadm

-- Создаем пользователя rancid и задаем ему пароль.
# useradd -g netadm -d /home/rancid rancid
# passwd rancid

-- Компилируем и устанавлваем rancid.
# pwd
/root/src/rancid-3.1

# ./configure --prefix=/home/rancid
# make install

-- Копируем файл в котором будут содержаться пароли от сетевого оборудования и выставляем права.
# cp /root/src/rancid-3.1/cloginrc.sample /home/rancid/.cloginrc
# chmod 0640 /home/rancid/.cloginrc
# chown -R rancid:netadm /home/rancid/
# chmod 770 /home/rancid/

-- В файле rancid.conf определяем группы сетевого оборудование.
# su - rancid
$ cp ~/etc/rancid.conf ~/etc/rancid.conf.orig
$ joe ~/etc/rancid.conf
...
# list of rancid groups
#LIST_OF_GROUPS="sl joebobisp"
# more groups...
#LIST_OF_GROUPS="$LIST_OF_GROUPS noc billybobisp"
LIST_OF_GROUPS="cisco juniper"
#
...

-- Создаем CVS репозиторий для ранее определенных групп.
$ /home/rancid/bin/rancid-cvs

-- Прописываем оборудование с которых будем снимать конфигурацию.
$ joe ~/var/juniper/router.db
...
srx-test;juniper;up

...
## Обращаем внимание, что в версиях rancid после 3.x в качестве разделителя используется ";".

-- Задаем пользователя, пароль и ip адрес для захода на сетевое оборудование
$ joe ~/.cloginrc
...
add method srx-test ssh
add user srx-test srx-user
add password srx-test srx-passwd
...

# joe /etc/hosts
...
x.x.x.x    srx-test
...

-- Вручную запускаем rancid (от пользователя rancid) и проверяем, что конфигурация снялась.
$ rancid-run -r srx-test
$ ll ~/var/juniper/configs/
total 484
drwxr-x---. 2 rancid netadm   4096 Feb  30 23:59 CVS
-rw-r-----  1 rancid netadm 488712 Feb  30 23:59 srx-test

-- Пишем правило cron для rancid.
$ crontab -e
...
# #############################################
# Crontab for rancid on myserver
# #############################################
# Hourly Check
1 * * * * /home/rancid/bin/rancid-run

# Daily Clean Up of Diff Files at 11 50 pm
50 23 * * * /usr/bin/find /home/rancid/var/logs -type f -mtime +2 -exec rm {} \;

# Daily Clean Up of .SITE.run.lock Files at 11 50 pm
50 23 * * * rm /tmp/.*.lock
...

###
### Написать про почту
###

ViewVC
-- Скачиваем и распаковываем свежую версию ViewVC.
# wget http://viewvc.tigris.org/files/documents/3330/49392/viewvc-1.1.23.tar.gz
# tar zxvf viewvc-1.1.23.tar.gz

-- Устанавливаем viewvc.
# cd viewvc-1.1.23
# ./viewvc-install
...
ViewVC file installation complete.

Consult the INSTALL document for detailed information on completing the
installation and configuration of ViewVC on your system.  Here's a brief
overview of the remaining steps:

  1) Edit the /usr/local/viewvc-1.1.23/viewvc.conf file.

  2) Either configure an existing web server to run
     /usr/local/viewvc-1.1.23/bin/cgi/viewvc.cgi.
     
     Or, copy /usr/local/viewvc-1.1.23/bin/cgi/viewvc.cgi to an
     already-configured cgi-bin directory.
     
     Or, use the standalone server provided by this distribution at
     /usr/local/viewvc-1.1.23/bin/standalone.py.
...

-- Настраиваем viewvc для работы с CVS репозиторием.
# cd /usr/local/viewvc-1.1.23/
# joe viewvc.conf
...
## Example:
## cvs_roots = cvsroot: /opt/cvs/repos1,
##             anotherroot: /usr/local/cvs/repos2
##
#cvs_roots =

cvs_roots = cvsroot: /home/rancid/var/CVS 
...
## Example:
## root_parents = /opt/svn: svn,
##                /opt/cvs: cvs
##
#root_parents =

root_parents = /home/rancid/var/CVS : cvs
...
## Example:
## rcs_dir = /usr/bin/
##
#rcs_dir =

rcs_dir = /usr/local/bin
...
## use_rcsparse: Use the rcsparse Python module to retrieve CVS
## repository information instead of invoking rcs utilities [EXPERIMENTAL]
##
use_rcsparse = 1
...

-- Копируем файлы query.cgi и viewvc.cgi в рабочую папку веб-сервера.
# cp /usr/local/viewvc-1.1.23/bin/cgi/*.cgi /var/www/cgi-bin
# ll /var/www/cgi-bin
total 8
-rwxr-xr-x. 1 root root 1782 Feb 30 23:59 query.cgi
-rwxr-xr-x. 1 root root 1781 Feb 30 21:59 viewvc.cgi

-- Правим /etc/https/conf.d/vhosts.conf
# joe /etc/https/conf.d/vhosts.conf
...
# Custom Rancid Config
<VirtualHost *:80>
        DocumentRoot /var/www
        ScriptAlias /cgi-bin/ "/var/www/cgi-bin"
        ScriptAlias /viewvc /var/www/cgi-bin/viewvc.cgi
        ScriptAlias /query /var/www/cgi-bin/query.cgi
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>
</VirtualHost>
...

-- Добавляем пользователя apache в группу netadm.
# joe /etc/group
...
netadm:x:5000:apache
...

-- Создаем mysql базу данных и пользователей.
# mysql -u root -p
mysql> create database viewvc_db;
mysql> create user 'viewvc_user'@'localhost' identified by 'pass1';
mysql> grant all privileges on viewvc_db.* to 'viewvc_user'@'localhost' with grant option;
mysql> create user 'viewvc_rouser'@'localhost' identified by 'pass2';
mysql> grant all privileges on viewvc_db.* to 'viewvc_rouser'@'localhost' with grant option;
mysql> flush privileges;

-- Создаем структуру базы данных viewvc_db.
# cd /usr/local/viewvc-1.1.23/bin/
# ./make-database
./make-database:20: DeprecationWarning: The popen2 module is deprecated.  Use the subprocess module.
  import popen2
MySQL Hostname (leave blank for default): 
MySQL Port (leave blank for default): 
MySQL User: viewvc_user
MySQL Password: pass1
ViewVC Database Name [default: ViewVC]: viewvc_db

Database created successfully.  Don't forget to configure the 
[cvsdb] section of your viewvc.conf file.

-- Настраиваем viewvc для работы с mysql.
# joe /usr/local/viewvc-1.1.23/viewvc.conf
...
[cvsdb]

## enabled: Enable database integration feature.
##
enabled = 1

## host: Database hostname.  Leave unset to use a local Unix socket
## connection.
##
host = localhost

## post: Database listening port.
##
port = 3306

## database_name: ViewVC database name.
##
database_name = viewvc_db

## user: Username of user with read/write privileges to the database
## specified by the 'database_name' configuration option.
##
user = viewvc_user

## passwd: Password of user with read/write privileges to the database
## specified by the 'database_name' configuration option.
##
passwd = pass1

## readonly_user: Username of user with read privileges to the database
## specified by the 'database_name' configuration option.
##
readonly_user = viewvc_rouser

## readonly_passwd: Password of user with read privileges to the database
## specified by the 'database_name' configuration option.
##
readonly_passwd = pass2
...

-- Заполняем базу данных. 
# cd /usr/local/viewvc-1.1.23/bin/
# ./cvsdbadmin rebuild /home/rancid/var/CVS/CVSROOT/
Using repository root `/home/rancid/var/CVS'
Purging existing data for repository root `/home/rancid/var/CVS'
[CVSROOT/loginfo [0 commits]]
[CVSROOT/editinfo [0 commits]]
[CVSROOT/config [0 commits]]
[CVSROOT/notify [0 commits]]
[CVSROOT/verifymsg [0 commits]]
[CVSROOT/cvswrappers [0 commits]]
[CVSROOT/rcsinfo [0 commits]]
[CVSROOT/modules [0 commits]]
[CVSROOT/commitinfo [0 commits]]
[CVSROOT/checkoutlist [0 commits]]
[CVSROOT/taginfo [0 commits]]

-- Пробуем зайти на веб-интерфейс
http://x.x.x.x/viewvc

Все должно быть хорошо.

## Нормальной работе мне мешал selinux, в чем проблема не разбирался, просто отключил.

###
###Написать про https и пароли
checking Socket.pm version... Socket version 2.006 required--this is only version 1.82 at -e line 1.
BEGIN failed--compilation aborted at -e line 1.
configure: error: Socket.pm is older than 2.006; upgrade from http://metacpan.org/pod/Socket

cpan App::cpanminus
cpanm Socket



###

--- 

При написании заметки использовались материалы:
http://www.cj-gerow.com/ceg/?p=1900
http://ciscoskills.net/2015/01/03/install-rancid-and-viewvc-on-centos-7/

Установка и бэкап RackTables

1. Скачиваем свежий racktables.
# wget http://downloads.sourceforge.net/project/racktables/RackTables-0.20.10.tar.gz

2. Распаковываем архив.
# tar zxvf RackTables-0.20.10.tar.gz

3. Копируем файлы в директорию где будет работать racktables.
# cp -r RackTables-0.20.10/wwwroot/ /var/www/html/racktables/

4. Создаем базу racktables_db.
# mysql -u root -p
mysql> create database racktables_db;
mysql> grant all on racktables_db.* to racktables_user;
mysql> grant all on racktables_db.* to racktables_user@localhost;
mysql> set password for racktables_user@localhost=password('xxx');

5. Доставляем необходимые пакеты.
# yum install php-mbstring php-bcmath

6. Заходим браузером на http://x.x.x.x/racktables и следуем инструкциям.
Когда попросят создаем файл secret.php и задаем права.
# touch /var/www/html/racktables/inc/secret.php
# chmod 666 /var/www/html/racktables/inc/secret.php

Когда попросят меняем права и владельца для secret.php.
# chown apache:root /var/www/html/racktables/inc/secret.php
# chmod 400 /var/www/html/racktables/inc/secret.php

7. Правим /etc/httpd/conf.d/vhosts.conf
<VirtualHost *:80>
     ServerAdmin i@xxx.org
     DocumentRoot /var/www/html/racktables
     ServerName racktables.xxx.org
     ServerAlias www.racktables.xxx.org
     ErrorLog logs/racktables_err_log
     CustomLog logs/rackables_acc_log common
</VirtualHost>

8. Бэкап и восстановление.
# mysqldump -u racktables_user -p  racktables_db > racktables_db.dump
# mysql -u racktables_user -p racktables_db < racktables_db.dump

---

При написании заметки использовались материалы:
http://www.binaryroyale.com/installing-racktables/
https://wiki.racktables.org/index.php/RackTablesInstallHowto

20150205

Быстрые заметки по junos

19. Ошщибка комита при достижении максимального количества зон безопасности. 

root@srx100B# commit check
error: zone quota exceeded (usage 11 > max 10)
error: configuration check-out failed
 


18. Ошибки на физическом интерфейсе. 
http://networking.ringofsaturn.com/Routers/junipershowint.php

Input errors:
Errors: 0, Drops: 0, Framing errors: 0, Runts: 0, Policed discards: 0, L3 incompletes: 0, L2 channel errors: 0, L2 mismatch timeouts: 0, FIFO errors: 0, Resource errors: 0


Output errors:
Carrier transitions: 5, Errors: 0, Drops: 0, Collisions: 0, Aged packets: 0, FIFO errors: 0, HS link CRC errors: 0, MTU errors: 0, Resource errors: 0


Carrier transitions:
"Carrier transitions just mean the link has flapped. See the exact description from Juniper

   Carrier transitions—Number of times the interface has gone from down
     to up. This number does not normally increment quickly,
    increasing only when the cable is unplugged, the far-end system is
    powered down and then up, or another problem occurs. If the number
    of carrier transitions increments quickly (perhaps once every 10 seconds),
    the cable, the far-end system, or the PIC or PIM is malfunctioning.

You would need to do basic troubleshooting to find out why the link is flapping. Those steps would be different if it was a telco circuit or an P2P ethernet cable."

Input errors:
Errors: 468, Drops: 0, Framing errors: 468, Runts: 0, Policed discards: 71, L3 incompletes: 0, L2 channel errors: 0, L2 mismatch timeouts: 0, FIFO errors: 0, Resource errors: 0

Framing errors:
KB27597
Это ошибка в контрольнной сумме пришедшего на интерфейс пакета, пакет "бьется" и контрольные суммы отправленного и полученно пакета не совпадают.

Решение проблемы с Framing errors заключается в:
-- проверить, что с обоих концов правильно настроены скорость и дуплекс порта.
-- поменять патч-корд
-- поменять порт оборудования


Policed discards: 71
Дропаются протоколы которык не в "security interface host-inbound-traffic protocols". При случае проверить с ospf.

"Frames that the incoming packet match code discarded because they were not recognized or of interest. Usually, this field reports protocols that the JUNOS software does not handle, such as CDP."




17. Скорость создания сессий.
KB23428

root@srx2> show security monitoring fpc ?
Possible completions:
  <fpc-slot>           FPC slot number (0..0)
root@srx2> show security monitoring fpc 0 ?
Possible completions:
  <[Enter]>            Execute this command
  |                    Pipe through a command
admin@msk-01-srx2> show security monitoring fpc 0  
FPC 0
  PIC 0
    CPU utilization          :    3 %
    Memory utilization       :   57 %
    Current flow session     :  469
    Current flow session IPv4:  469
    Current flow session IPv6:    0
    Max flow session         : 524288
Total Session Creation Per Second (for last 96 seconds on average):   15
IPv4  Session Creation Per Second (for last 96 seconds on average):   15

IPv6  Session Creation Per Second (for last 96 seconds on average):    0

SNMP OID
root@srx2> show snmp mib walk .1.3.6.1.4.1.2636.3.39.1.12.1.4.1.5 
jnxJsNodeSessionCreationPerSecond.0 = 15

Когда два srx работают в режиме кластера в выводе появится строка "jnxJsNodeSessionCreationPerSecond.1 = "

root@srx2> show snmp mib walk .1.3.6.1.4.1.2636.3.39.1.12.1.4.1      
jnxJsClusterMonitoringNodeIndex.0 = 0
jnxJsClusterMonitoringNodeDescr.0 = single
jnxJsNodeCurrentTotalSession.0 = 485
jnxJsNodeMaxTotalSession.0 = 0
jnxJsNodeSessionCreationPerSecond.0 = 15
jnxJsNodeSessCreationPerSecIPv4.0 = 15
jnxJsNodeSessCreationPerSecIPv6.0 = 0
jnxJsNodeCurrentTotalSessIPv4.0 = 485
jnxJsNodeCurrentTotalSessIPv6.0 = 0

16. MOTD
Message of the day
set system login message "Privet Serega! NE PEREGRUZHAI srx! Lozhis` spat`=) WBR EKS and Levin."

15. Залить текущий junos на бэкапный раздел. 
root@srx-master> request system snapshot slice alternate
node0:
--------------------------------------------------------------------------
Formatting alternate root (/dev/ad0s1a)...

Copying '/dev/ad0s2a' to '/dev/ad0s1a' .. (this may take a few minutes)
The following filesystems were archived: /

node1:
--------------------------------------------------------------------------
Formatting alternate root (/dev/ad0s2a)...
Copying '/dev/ad0s1a' to '/dev/ad0s2a' .. (this may take a few minutes)
The following filesystems were

На кластере можно дать команду только на активной ноде.


14. Перенести кусок конфигурации с одного srx на другой. 
Будем переносить записи в address book.

Отображаем конфирацию  в set стиле.
[edit security address-book UNTRUST-BOOK]
root@srx-old# show | display set    
set security address-book UNTRUST-BOOK address perevod-korona.ru dns-name perevod-korona.ru ipv4-only
set security address-book UNTRUST-BOOK address wupos.westernunion.com dns-name wupos.westernunion.com ipv4-only
...

Подгружаем конфигурацию.
У команды load есть ключ relative который подкружает set не от корня конфигуации, а от текущего места. 
{primary:node1}[edit security address-book]
root@srx-new# load set terminal 
[Type ^D at a new line to end input]
set security address-book UNTRUST-BOOK address perevod-korona.ru dns-name perevod-korona.ru ipv4-only
set security address-book UNTRUST-BOOK address wupos.westernunion.com dns-name wupos.westernunion.com ipv4-only
...
^D

Нюансы.
Если сразу переносить много конфига, то RE возможно будет не успевать его отрабатывать и будут появляться ошибки вида - "terminal:2:(4) syntax error: address".
Проблема описана в KB15472. Как решить в линуксовом терминале пока не придумал.
Если сидеть на srx через череp minicom, то заливаться будет без ошибок - скорость соединения маленькая.


13. Обновить софт в srx
root> request system software add ?              
Possible completions:
  <package-name>       URL or pathname of package
  best-effort-load     Load succeeds if at least one statement is valid
  delay-restart        Don't restart processes
  no-copy              Don't save copies of package files
  no-validate          Don't check compatibility with current configuration
  partition            Format and re-partition the media before installation
  reboot               Reboot system after adding package
  unlink               Remove the package after successful installation

  validate             Check compatibility with current configuration

root> request system software add no-copy http://192.168.10.12/junos/junos-srxsme-12.1X47-D25.4-domestic.tgz

12. KB25265
http://kb.juniper.net/InfoCenter/index?page=content&id=KB25265

root@srx> ping ocsp.comodoca.com      
PING6(56=40+8+8 bytes) :: --> 2a02:1788:2fd::b2ff:5301
ping: sendmsg: No route to host
ping6: wrote ocsp.comodoca.com 16 chars, ret=-1
^C
--- ocsp.comodoca.com ping6 statistics ---
1 packets transmitted, 0 packets received, 100% packet loss

root@srx> ping ocsp.comodoca.com inet
PING ocsp.comodoca.com (178.255.83.1): 56 data bytes
64 bytes from 178.255.83.1: icmp_seq=0 ttl=57 time=79.415 ms
^C
--- ocsp.comodoca.com ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max/stddev = 79.415/79.415/79.415/0.000 ms

11. Записать вывод команды в файл. 
root@srx> show services application-identification application detail | save ai-app-detail
Файл запишется в домашнюю директорию пользователя.

10. Истекли лицензии  appid-sig и idp-sig. 
root@srx> show system license
License usage:
                                 Licenses     Licenses    Licenses    Expiry
  Feature name                       used    installed      needed
  av_key_kaspersky_engine               1            0           1    28 days
  dynamic-vpn                           0            2           0    permanent
  ax411-wlan-ap                         0            2           0    permanent
  appid-sig                             1            0           1    invalid
        - APPID Signature

Все ранее настроенные политики продолждают работать.
Нельзя обновить сигнатуры и верме комита увеличилось секунд на 40.

root@srx# commit
[edit security idp idp-policy Recommended rulebase-ips rule 1 match attacks]
  'predefined-attack-groups "[Recommended]IP - Critical"'
    Security Package is being used, however license is not valid/has expired. This may be in violation of policy.
commit complete

9. Смысл maximum-transactions в настройках вложенных приложений (nested applications).
nested-application my:XAKEP-SSL {
    type XAKEP;
    protocol SSL;
    signature NestedApplication:XAKEP-SSL {
        member m01 {
            context ssl-server-name;
            pattern xakep.ru;
            direction client-to-server;
        }
        maximum-transactions 1;
    }
}

maximum-transactions - максимальное количество совпадений  с "подписью" при  при достижении которого считается, что это именно это приложение. 

8. Посмотеть список и детальную информацию по типам приложений с которыми работает AppFW и IDP на srx.

root@srx> show services application-identification application summary
Application(s): 800
Nested Application(s): 981
  Applications                                 Disabled         ID      Order
  junos:ZENGUARD-SSL                            No               1987    33799
  junos:FACEBOOK-TIMELINE                       No               1986    33793
  junos:FACEBOOK-STATUS-UPDATE                  No               1985    33794
  junos:GOLFZON-MEMBERS-SSL                     No               1984    33792
  junos:AFREECA-HTTP-STREAM                     No               1982    33790
....

root@srx> show services application-identification application summary | match HTTP    
  junos:AFREECA-HTTP-STREAM                     No               1982    33790   
  junos:WECHAT-HTTP                             No               1932    33751   
  junos:SSH-OVER-HTTP                           No               1907    33586   
  junos:YAHOO-FINANCE-HTTP                      No               1896    33722   
  junos:AIM-HTTP-API                            No               1865    33700   
  junos:ALIWANGWANG-HTTP                        No               1863    33704   
  junos:BAIDU-HI-HTTP                           No               1859    33703   
  junos:GROOVE-HTTP                             No               1264    33669   
...

root@srx> show services application-identification application detail junos:YAHOO-FINANCE-HTTP
Application Name: junos:YAHOO-FINANCE-HTTP                                  
Application type: YAHOO-FINANCE-HTTP                                        
Description: This signature detects Yahoo! finance, a site from Yahoo! that provides financial news and information.
Application ID: 1896  
Disabled: No              
Number of Parent Group(s): 1    
Application Groups:
    junos:web:finance                          
Application Tags:
    characteristic        : Bandwidth Consumer                              
    characteristic        : Loss of Productivity                            
    risk                  : 2                                              
    subcategory           : Finance                                        
    category              : Web                                            
Signature NestedApplication:YAHOO-FINANCE-HTTP                          
    Layer-7 Protocol: HTTP                                              
    Chain Order: no      
    Maximum Transactions: 1                
    Order: 33722          
    Member(s): 1          
        Member 0      
            Context: http-header-host    
            Pattern: (.*\.)?finance\.yahoo\.com                        
            Direction: CTS                                

7. Посмотреть настройки стантардных junos application
root> show configuration groups junos-defaults applications

6. Посмотреть кто залогинился.
root> show system users no-resolve  
 5:38PM  up 28 days,  2:04, 4 users, load averages: 0.10, 0.06, 0.04
USER     TTY      FROM                              LOGIN@  IDLE WHAT
root     p0                                                          3:17PM   2:04 cli        
root     p1                                                          3:03PM     55 cli        
root     p2                                                          4:21PM     56 cli        
root     p3                                                          5:31PM      - cli

5. Поставить таймаут на ssh/telnet сессию.
root> set cli idle-timeout 60
Idle timeout set to 60 minutes

root> show cli
CLI complete-on-space set to on
CLI idle-timeout set to 60 minutes
CLI restart-on-upgrade set to on
CLI screen-length set to 55
CLI screen-width set to 207
CLI terminal is 'xterm'
CLI is operating in enhanced mode
CLI timestamp disabled
CLI working directory is '/cf/root'


4. Передернуть руками ноду в кластере.


root> request chassis cluster failover redundancy-group [0|1] node [0|1]

Увести RG0 на node1
root> request chassis cluster failover redundancy-group 0 node 1

После этого приоритет node1 для RG0 станет равным 255.
Что бы привести приоритет в соответствие с настройками надо дать комануду:  
root> request chassis cluster failover reset redundancy-group 0

После этого, в зависимости от настройки "Preempt", RG0 останется или на node1 или вернется на node0.


3. Сброс конфигурации junos.
[edit]
root# load factory-default  
warning: activating factory configuration

[edit]
root# set system root-authentication plain-text-password         
New password:
Retype new password:

[edit]
root# commit 
commit complete

2. Сброс пароля для root.
-- Подключиться консолью к маршрутизатору и включить его.
Дождаться "Hit [Enter] to boot immediately, or space bar for command prompt."
и нажать пробел.  Появится приглашение "loader>".

-- Загрузиться в single mode.
loader> boot -s
Kernel entry at 0x801000d8 ...

Дождаться "Enter full pathname of shell or 'recovery' for root password recovery or RETURN for /bin/sh:" и ввести команду "recovery". Ждем приглашения "root>".

NOTE: Once in the CLI, you will need to enter configuration mode using
NOTE: the 'configure' command to make any required changes. For example,
NOTE: to reset the root password, type:
NOTE:    configure
NOTE:    set system root-authentication plain-text-password
NOTE:    (enter the new password when asked)
NOTE:    commit
NOTE:    exit
NOTE:    exit
NOTE: When you exit the CLI, you will be asked if you want to reboot
NOTE: the system

Starting CLI ... 
root> 

-- Задаем новый пароль root, применяем конфигурацию и перезагружаемся. 
root> configure 
Entering configuration mode

root# set system root-authentication plain-text-password     
New password:
Retype new password:

[edit]
root# commit 
commit complete

[edit]
root# exit 
Exiting configuration mode

root> request system reboot 
Reboot the system ? [yes,no] (no) yes 

Shutdown NOW!

--
Подробное описание процедуры:
http://www.juniper.net/documentation/en_US/junos13.3/topics/task/configuration/authentication-root-password-recovering.html

1. Посмотреть загрузку cpu.
user@srx> show chassis routing-engine
Routing Engine status:
    Temperature                 57 degrees C / 134 degrees F
    Total memory              1024 MB Max   655 MB used ( 64 percent)
      Control plane memory     544 MB Max   457 MB used ( 84 percent)
      Data plane memory        480 MB Max   202 MB used ( 42 percent)
    CPU utilization:
      User                       4 percent
      Background                 0 percent
      Kernel                    10 percent
      Interrupt                  0 percent
      Idle                      85 percent
    Model                      
    Serial ID                  
    Start time                     2015-02-04 19:03:18 GMT-3
    Uptime                         26 minutes, 6 seconds
    Last reboot reason             0x200:normal shutdown
    Load averages:                 1 minute   5 minute  15 minute
                                       0.07       0.17       0.61

user@srx> show chassis forwarding      
FWDD status:
  State                                 Online  
  Microkernel CPU utilization        14 percent
  Real-time threads CPU utilization   0 percent
  Heap utilization                   42 percent
  Buffer utilization                  1 percent
  Uptime:                               22 minutes, 39 seconds