20160130

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

8. Сбросить рутовый пароль
Останавливаем mysql
# /etc/init.d/mysqld stop
Stopping mysqld:                                           [  OK  ]

Запускаем mysql в безопасном режиме.
# /usr/bin/mysqld_safe --skip-grant-tables --user=root &
[1] 6363
# 160206 12:54:08 mysqld_safe Logging to '/var/log/mysqld.log'.
160206 12:54:09 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

Заходим под рутом без пароля.
# mysql -u root

Переключаемся на базу mysql.
mysql> USE mysql;

Смотрим список таблиц и содержаение таблицы user.

mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
...
| user                      |
+---------------------------+
23 rows in set (0.00 sec)

mysql> SELECT * FROM user

В таблице user так же есть пароли и настройки всех остальных пользователей.

Задаем новый пароль P@s$ = меняем значение поля Password

mysql> UPDATE user SET Password=PASSWORD('P@s$') WHERE User='root';
Функция "PASSWORD()" используется для шифрования.


Выходим и перезапускаем mysql
mysql> exit
Bye
# /etc/init.d/mysqld restart
160206 13:12:50 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
Stopping mysqld:                                           [  OK  ]
Starting mysqld:                                           [  OK  ]
[1]+  Done                    /usr/bin/mysqld_safe --skip-grant-tables --user=root


7. Изменить значение поля в строке
Есть строка.
mysql> SELECT * FROM logcon_views;
+----+-------------+-------------------------------------+--------+---------+
| ID | DisplayName | Columns                             | userid | groupid |
+----+-------------+-------------------------------------+--------+---------+
|  2 | SRX-FILTER  | SRX, TIME_UTC_6, TIME_UTC, msg, 111 |   NULL |    NULL |
+----+-------------+-------------------------------------+--------+---------+

1 row in set (0.00 sec)

Хотим изменить значение поля Columns  в строке с ID равным 2. 
mysql> UPDATE logcon_views SET Columns = 'SRX, TIME_UTC_6, TIME_UTC, msg' WHERE ID = 2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0



6. Удалить строку из таблицы
Есть такая таблица.
mysql> select * from logcon_fields;
+--------------+------------------+--------------+
| FieldID      | FieldDefine      | FieldCaption |
+--------------+------------------+--------------+
| SRX          | SYSLOG_SRX       | SRX          |
| TIME (UTC+6) | SYSLOG_TIME_UTC6 | TIME (UTC+6) |
+--------------+------------------+--------------+
2 rows in set (0.00 sec)

Хотим удалить вторую строку. 
mysql> DELETE FROM logcon_fields WHERE FieldID ="TIME (UTC+6)";
Query OK, 1 row affected (0.00 sec)

5. Создать базу из шаблона
Есть вот такой шаблон базы для rsyslog.
]# cat /usr/share/doc/rsyslog-mysql-5.8.10/createDB.sql
CREATE DATABASE rsyslog_db;
USE rsyslog_db;
CREATE TABLE SystemEvents
(
        ID int unsigned not null auto_increment primary key,
        CustomerID bigint,
#....
       SystemID int NULL
);

CREATE TABLE SystemEventsProperties
(
        ID int unsigned not null auto_increment primary key,
        SystemEventID int NULL ,
        ParamName varchar(255) NULL ,
        ParamValue text NULL
);

Что бы создать эту базу даем след. команду:
# mysql -u root -p < /usr/share/doc/rsyslog-mysql-5.8.10/createDB.sql

Проверяем.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| cacti_db           |
| mysql              |
| racktables_db      |
| rsyslog_db         |
| viewvc_db          |
+--------------------+
6 rows in set (0.00 sec)

mysql> use rsyslog_db;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+------------------------+
| Tables_in_rsyslog_db   |
+------------------------+
| SystemEvents           |
| SystemEventsProperties |
+------------------------+
2 rows in set (0.00 sec)

6. Дать права пользователю на базу и задать пароль.
mysql> grant all privileges on rsyslog_db.* to rsyslog_user@localhost identified by 'P@Ss';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;

Query OK, 0 rows affected (0.00 sec)

5. Создать пользователя
mysql> create user rsyslog_user@localhost;
Query OK, 0 rows affected (0.00 sec)

4. Удалить пользователя
mysql> drop user rsyslog_user@localhost;

Query OK, 0 rows affected (0.00 sec)


3. Удалить базу
mysql> drop database rsyslog_db;

Query OK, 13 rows affected (0.00 sec)


2. Посмотреть имеющиеся базы
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| cacti_db           |
| mysql              |
| racktables_db      |
| rsyslog_db         |
| viewvc_db          |
+--------------------+
6 rows in set (0.00 sec)


1. Заход
Заход под root на localhost, пароль надо ввести.
# mysql -u root -p
Enter password:


20160114

bash скрипты

3.Переместить файл и добавить в имя дату и время перемещения.
#!/bin/sh
mv /var/www/html/dump/dump.xml /var/www/html/dump/dump.xml.$(date +"%Y%m%d-%H%M")
cp /home/rkn/dump.xml /var/www/html/dump/dump.xml



2. Переместить логи которые заархивировал logrotate и удалить логи странше 60 дней. 
#!/bin/sh
mv /var/log/somelog/*.gz /var/log/somelog/archive/
find /var/log/somelog/archive/ -type f -mtime +60 -delete


Культурнее. 
#!/bin/bash
branch_dir=(offce1 office2)

for i in ${branch_dir[@]}; do
    mv /var/log/somelog/$i/*.gz /var/log/somelog/1archive-$i/
    find /var/log/somelog/1archive-$i/ -type f -mtime +60 -delete

 


1. Сравнить ip адрес у url без\с www
#!/bin/sh
url=$1
host $url | head -n 1
host www.$url | head -n 1

20160103

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

3. Базовый набор плагинов.
habrahabr.ru/post/195052/
Adblock Plus
NoScript
Cookie Monster
Download YouTube Videos as MP4
 

2. Приватный рехим при старте FF.
2.1 kostya@aee:~$ firefox --private --no-remote
2.2 kostya@aee:~$ firefox -P newprofile1 --no-remote
about:config
browser.privatebrowsing.autostart -> true

Визуально понять, что находишься в приватном режиме можно только с помощью мемменджера "Firefox Hello", иконка будет в виде пустого облачка разговора.

1. Создание и запуск нового профиля.
Что бы запустить меню где можно сделать еще один профиль даем команду:
kostya@aee:~$ firefox -P

Запусть новый профиль:
kostya@aee:~$ firefox -P newprofile1 --no-remote

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

Вот.