Skip to content

Как вставить баннер на все страницы. Apache

2013 July 30
Comments Off
Posted by shirker2006

Небольшая подборка архивов на эту тему
http://forum.searchengines.ru/archive/index.php/t-120875.html
http://forum.ru-board.com/topic.cgi?forum=8&topic=7017#1
http://forum.ru-board.com/topic.cgi?forum=31&topic=8653

Have you tried Kangle web server?

2013 July 30
Comments Off
Posted by shirker2006

http://freevps.us/thread-8612.html

hylafax iptables problem

2013 July 30
Comments Off
Posted by shirker2006

add to /etc/sysconfig/iptables

-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 4559 -j ACCEPT

then run modprobe ip_conntrack_ftp ports=4559

sort php array without sort()

2013 July 7
Comments Off
Posted by shirker2006

Как-то давно проходил собеседование, и там была задача — не используя встроенных функций сортировки, отсортировать массив(вернее список имен из файла) от «а» до «я». Задачу тогда не смог решить и ушел ни с чем… И вот тут недавно вспомнил, стало интересно, каково же, все таки, решение?
Нашел кое-что тут: http://muruganasm.blogspot.com/2011/01/sort-array-of-string-without-using-php.html. Немного доработал для работы с именами. Например, есть файл listnames.txt:

Salopatan Dolot
   Lucara Vanibo
   Xyxelan Ubem
   Irabon Seboribal
   Abasixi Abubodul
   Sasipabi Itatop
   Latanybor Ocifil
   Obi Onu
   Laso pubyl
владимир петров
Илья бронштейн
Александр Мельников
  алексей шнырюк
512

Для вывода «по-красивее», решил обработать стринги функцией ucwords(). Но, как ни странно, она не захотела работать с русской кодировкой. setlocale() тоже не помогла нисколько. Тут, возможно сыграли настройки сервера. Вобщем, пошел довольно таки сложным путем. Надеюсь, кому-нибудь будет интересно:

<!--?php
$filename = 'listnames.txt';
$file_cont = (file_exists($filename))? file_get_contents($filename):die('No such file '.$filename);
$str2 = (!empty($file_cont))? preg_split("/[\n,]|[\r,]+/",$file_cont):die('No content was given from '.$filename);
print_r($str2);
$str = array_map("trim",$str2);
$str = array_map("ucwords", $str);
$str = array_map("non_en_to_uppercase", $str);
function non_en_to_uppercase($str){
    if( preg_match("/[А-я]{1,}+(\s+[А-я]{1,})?/i", $str)){
       $arr = preg_split("/[\s,]+/",$str);
       var_dump($arr);
       $new_str = "";
       foreach($arr as $word){
           $word = trim($word);
           $strlen = mb_strlen($word);
           $word = mb_strtoupper(mb_substr($word,0,1,'UTF-8'),'UTF-8') . mb_strtolower(mb_substr($word,1,$strlen),'UTF-8');
           $new_str .= " ".$word;
       }
       return trim($new_str);
    }
    else return $str;
}
$array_length = sizeof($str);
     for($x = 0; $x < $array_length; $x++) {
          for($y = 0; $y < $array_length; $y++) {
               if(strcasecmp($str[$x],$str[$y])<0) {
                     $hold = $str[$x];
                     $str[$x] = $str[$y];
                     $str[$y] = $hold;
               }
          }
     }
$str = array_filter($str);
echo "After sorting";
print_r($str);
?>

проверяем, если есть заданный файл. Если есть – читаем и построчно засовываем в массив $str2:

$file_cont = (file_exists($filename))? file_get_contents($filename):die(‘No such file ‘.$filename);
$str2 = (!empty($file_cont))? preg_split(“/[\n,]|[\r,]+/”,$file_cont):die(‘No content was given from ‘.$filename);

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

$str = array_map(“trim”,$str2);

Приводим имена в «нормальный» вид. Т.е. иван петров в Иван Петров

$str = array_map(“ucwords”, $str);
$str = array_map(“non_en_to_uppercase”, $str);

Скорее всего, я где-то перемудрил с функцией non_en_to_uppercase(), но суть ее – проверить, если стринг в русской кодировке, и, если да, принудительно конвертировать первые буквы имени и фимилии в заглавные, а остальные – в строчные

Далее в двойном цикле с помощью регистронезависимой функции strcasecmp сравниваем элементы массива, и меняем их местами в зависимости от результата сравнения:

if(strcasecmp($str[$x],$str[$y]) $hold = $str[$x];
$str[$x] = $str[$y];
$str[$y] = $hold;

Для примера Код:

$a = ‘a’;
$b = ‘b’;
echo strcasecmp($a,$b); //-1

выводит -1
и

echo strcasecmp($b,$a); //1

выдаст 1
Для пущей наглядности можно запустить этот код и увидеть, как элементы меняются местами

$str = array('Z','c','A','C','E','B','M','N');
$array_length = sizeof($str);
for($x = 0; $x < $array_length; $x++) {
    for($y = 0; $y < $array_length; $y++) {
        if(strcasecmp($str[$x],$str[$y]) }
    }
}

Напомню, что strcasecmp() не работает нормально с русской кодировкой. буквы «а» и «А» не равны. Поэтому мне пришлось выше приводить имена к единому регистру самописной функцией non_en_to_uppercase($str)

Теперь очистим вывод от пустых значений и печатаем отсортированный массив:

$str = array_filter($str);
echo ”
After sorting
“;
print_r($str);

Свой SVN сервер. Установка subversion на CentOS

2013 July 1
Comments Off
Posted by shirker2006

http://dandreev.com/blog/administrirovanie/svoj-svn-server-ustanovka-subversion-na-centos/

Система контроля версий Subversion крайне полезная вещь. Особенно, при совместной разработке проектов с несколькими участниками. Только трудной найти хороший бесплатный сервер SVN, потому лучше создать свой.

Установка subversion и WEB_DAV_SVN

Устанавливаем модуль Apache для доступа к репозиторию,
а также модуль шифрования соединения SSL.
Затем установим сам SVN сервер subversion.
Если у вас CentOS 5.4 или 5.5, а Yum не установлен(на виртуальных среверах такое часто бывает),
можете установить его по инструкции здесь.

1.# yum install mod_dav_svn mod_ssl
2.# yum install subversion

Создание репозитория

Создадим репозиторий project в папке /var/www/svn

1.# mkdir /var/www/svn
2.# svnadmin create /var/www/svn/project

Всё репозиторий абсолютно чистый готов к работе, теперь обеспечим доступ к нему по сети.

Настройка доступа через Apache SSL

Для начала отредактируем файл конфигурации SVN

1.# vi /etc/httpd/conf.d/subversion.conf

Нужно в конце доавить следующийе правила

01.<location /svn >;
02.DAV svn                    # запросы по данному пути будут направляться к SVN серверу
03.SVNParentPath /var/www/svn # путь до репозитория
04.SVNListParentPath on       # формировать список репозиториев и файлов в них при просмотре через браузер
05.
06.# Limit write permission to list of valid users.
07.# <limitexcept GET PROPFIND OPTIONS REPORT>
08.# Require SSL connection for password protection.
09.SSLRequireSSL           # необходимо шифрованное соединение по протоколу https
10.
11.AuthType Basic          # тип авторизации - базовая
12.AuthName &amp;amp;amp;amp;quot;Authorization Realm&amp;amp;amp;amp;quot;
13.AuthUserFile /var/www/svn/conf/htpasswd # файл с пользователями и паролями
14.AuthzSVNAccessFile /var/www/svn/conf/svn-access # файл доступа к репозиториям
15.Require valid-user                      # авторизация обязательна
16.# </limitexcept>
17.</location>

Всё конфигурация апача готова, теперь можно его перезапустить

1.# /etc/init.d/httpd restart

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

Сосздадим файл пользователей и паролей для авторизации

1.# htpasswd -c /var/www/svn/conf/htpasswd test
2.New password:
3.Re-type new password:
4.Adding password for user test

После можно добавлять туда пользователей уже без ключа -c

1.# htpasswd /var/www/svn/conf/htpasswd test

Теперь сделаем файл прав доступа заведенным пользователям

1.# vi /var/www/svn/conf/svn-access

В нем распишем, что доступ ко всем репозиториям любым пользователям запрещен,
а нашему новому пользователю test разрешена запись и чтение из всех репозиториев

[/]
* =
test = rw

Теперь назначим всей папке svn и вложенным подпапкам и файлам пользователя apache, а иначе он не сможет получить доступ до репозиториев и всё что мы получим, это сообщение об ошибке “You don’t have permission to access /svn/ on this server.”

1.# chown -R apache:apache /var/www/svn

Вот и всё теперь сервер готов к использованию. Теперь зайдя по сслыке в вашем браузере

https://ваш_ip/svn/project/

Вам будет предложено авторизоваться, а после вы увидите, что ваш репозиторий пустой и находится в состоянии ревизии 0.
“Revision 0: /”

how to merge data from two columns mysql

2013 May 3
Comments Off
Posted by shirker2006
I have the following data in a MySQL table.

+----------------+----------------+----------+
|    zipcode     |      city      |   state  |
+----------------+----------------+----------+
|     10954      |     Nanuet     |    NY    |
+----------------+----------------+----------+
Is there any way to make a new column called combined (for example) and have it display the following:

10954 - Nanuet, NY

So it would look like...

+----------------+----------------+----------+---------------------+
|    zipcode     |      city      |   state  |      combined       |
+----------------+----------------+----------+---------------------+
|     10954      |     Nanuet     |    NY    | 10954 - Nanuet, NY  |
+----------------+----------------+----------+---------------------+
I want to loop through the entire table to combine these three columns into a single column (without destroying the original three columns).

Any suggestions?

ANSWER:


Create the column:

alter table add column combined varchar(50);

Update the current values:

update table set combined = concat(zipcode, ' - ', city, ', ', state);

Update all future values automatically:

create trigger insert_trigger before insert on table 
for each row set new.combined = concat(new.zipcode, ' - ', new.city, ', ', new.state); 
create trigger update_trigger before update on table 
for each row set new.combined = concat(new.zipcode, ' - ', new.city, ', ', new.state);

http://stackoverflow.com/questions/5774532/mysql-combine-two-columns-and-add-into-new-column

in my own case:

ALTER TABLE  `YP_US_industry_done` ADD  `entry_full_code` VARCHAR( 50 ) NOT NULL AFTER  `area_done`

update YP_US_industry_done set `entry_full_code` = concat(`area_done`, '-', `ind_id_done`)

create trigger insert_YP_US_industry_done_trigger
before insert on YP_US_industry_done
for each row
set new.entry_full_code = concat(new.area_done, '-', new.ind_id_done);

create trigger update_YP_US_industry_done_trigger
before update on YP_US_industry_done
for each row
set new.entry_full_code = concat(new.area_done, '-', new.ind_id_done);

SED replacing string with slashes, apostrophes and spaces

2013 January 31
Comments Off
Posted by shirker2006

I was working to embed phpmyadmin to my website, and had some idea to remove footer including from all files.

I.e.  replace
“require ‘./libraries/footer.inc.php”

to

“//require ‘./libraries/footer.inc.php”
This is the solution by using “sed”:

~# sed -i s#"require './libraries/footer.inc.php"#"//require './libraries/footer.inc.php"#g *.php

~# sed --version
GNU sed version 4.2.1

GET HTTP bash GET command not found

2013 January 9
Comments Off
Posted by shirker2006

To fix this you need to install libwww-perl

then copy it to /usr/bin (or wherever you want):

cp /usr/bin/lwp-request /usr/bin/GET

here is more specific:

http://webhostingneeds.com/GET:_command_not_found

GET: command not found

On running cronjob, i get following error

/bin/sh: GET: command not found

This is due to GET command not available on the server. To fix, install libwww

yum list|grep libwww
yum install perl-libwww-perl.noarch

After install you will see GET at /usr/bin folder.

[root@server26 ~]# which GET
/usr/bin/GET
[root@server26 ~]#

10 Sep 2008

I tried to install perl-libwww-perl on a centOS server. perl-libwww-perl was not available on yum.

So i installed with cpan

# cpan
CPAN: File::HomeDir loaded ok (v0.80)
Exiting subroutine via last at /usr/lib/perl5/5.8.8/CPAN.pm line 1450.
cpan> install Bundle::LWP
.....
.....
.....
cpan> exit
Lockfile removed.
#

After install there was no GET command. Instead, there is “lwp-request” command, which is same as GET, you can create a sym link.

cp /usr/bin/lwp-request /usr/bin/GET

exim + dovecot + clamav + postfixadmin

2012 December 31
Comments Off
Posted by shirker2006

http://blog.eulinux.org/2009/09/exim-dovecot-clamav-postfixadmin.html

Ok, here we go…

I needed to quickly configure a mailserver, initially – for a single domain (but probably will host more later).

I am using exim over the last two years, I don’t like qmail because it’s very old, and to add some new feature to it – requires patching it. BTW, did you ever try reading qmail’s logs? :D
I don’t like postfix, but this is probably because I didn’t use it too often.

Also, as an Imap/POP3 server, I do like dovecot, easy to configure, yet very comfortable to use, and also quite stable.
Adding domains/users manually isn’t too much fun, we need some sort of web interface too, to manage virtual domains, mailboxes, aliases.

Prerequisites:
- apache
- php
- mysql

I will leave this as an exercise to the reader :)

All this setup was done on a CentOS 5.3 system, so I’ll give examples using yum to install the packages (on Fedora/RedHat you could use the same yum, on Debian/Ubuntu – use aptitude or apt-get)

First of all, create a MySQL database to store all the settings:

mysql> CREATE DATABASE vexim;
mysql> GRANT ALL ON vexim.* to vexim@localhost identified by 'kieHeed3ailuph8b';

Next, download the latest postfixadmin tarball from http://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-2.2.1.1/postfixadmin-2.2.1.1.tar.gz, and unpack it to /var/www/html/mailadmin/

Adjust: /var/www/html/mailadmin/config.inc.php, more exactly, the following section:

...
// Database Config
// mysql = MySQL 3.23 and 4.0
// mysqli = MySQL 4.1
// pgsql = PostgreSQL
$CONF['database_type'] = 'mysql';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'vexim';
$CONF['database_password'] = 'kieHeed3ailuph8b';
$CONF['database_name'] = 'vexim';
$CONF['database_prefix'] = '';
...

We will need clamd installed, in order to enable virus checks in exim.
Debian/Ubuntu have this in the base repositories, CentOS – doesn’t.
We can use the rpmforge packages, see http://dag.wieers.com/rpm/FAQ.php#B2 on how to add the rpmforge repositories to your system.

Install clamd:

[root@server #] yum install clamd

Adjust the following parameters in clamd settings:

#In /etc/clamd.conf:
...
User exim
...
#In /etc/freshclam.conf:
...
DatabaseOwner exim
...

Adjust permissions/ownership:

[root@server #] chown -R exim:exim /var/log/clamav/
[root@server #] chown -R exim:exim /var/clamav/

Now on to exim, dovecot and postfixadmin.
Install exim and dovecot from repositories,

[root@server #] yum install dovecot exim
[root@server #] mv /etc/exim/exim.conf /etc/exim/exim.conf-orig
[root@server #] mv /etc/dovecot.conf /etc/dovecot.conf-orig

Sample config used for exim, this doesn’t include spam filtering, or rbl checks, but this can be easily added:
===============================

primary_hostname = mail.eulinux.org
hide mysql_servers = localhost/vexim/vexim/kieHeed3ailuph8b

domainlist local_domains = ${lookup mysql{SELECT `domain` \
                            FROM `domain` WHERE \
                            `domain`='${quote_mysql:$domain}' AND \
                            `active`='1'}}

domainlist relay_to_domains = ${lookup mysql{SELECT `domain` \
                            FROM `domain` WHERE \
                            `domain`='${quote_mysql:$domain}' AND \
                            `active`='1'}}

hostlist   relay_from_hosts = localhost:127.0.0.0/8:192.168.0.0/16  #add the hosts from which you allow relaying here

acl_smtp_rcpt = acl_check_rcpt
acl_smtp_data = acl_check_data

av_scanner = clamd:/var/run/clamav/clamd.sock

# spamd_address = 127.0.0.1 783

qualify_domain = mail.playlainc.com
qualify_recipient = mail.playlainc.com
allow_domain_literals = false
exim_user = exim
exim_group = exim
never_users = root
rfc1413_query_timeout = 0s

sender_unqualified_hosts = +relay_from_hosts
recipient_unqualified_hosts = +relay_from_hosts

ignore_bounce_errors_after = 45m
timeout_frozen_after = 15d
helo_accept_junk_hosts = 192.168.0.0/16
auto_thaw = 1h
smtp_banner = "$primary_hostname, ESMTP EXIM $version_number"
smtp_accept_max = 50
smtp_accept_max_per_connection = 25
smtp_connect_backlog = 30
smtp_accept_max_per_host = 20
split_spool_directory = true
remote_max_parallel = 15
return_size_limit = 70k
message_size_limit = 64M
helo_allow_chars = _
smtp_enforce_sync = true

log_selector = \
    +all_parents \
    +connection_reject \
    +incoming_interface \
    +lost_incoming_connection \
    +received_sender \
    +received_recipients \
    +smtp_confirmation \
    +smtp_syntax_error \
    +smtp_protocol_error \
    -queue_run

syslog_timestamp = no

begin acl

acl_check_rcpt:
  accept  hosts = :
  deny    message       = "incorrect symbol in address"
          domains       = +local_domains
          local_parts   = ^[.] : ^.*[@%!/|]

  deny    message       = "incorrect symbol in address"
          domains       = !+local_domains
          local_parts   = ^[./|] : ^.*[@%!] : ^.*/\\.\\./

  accept  local_parts   = postmaster
          domains       = +local_domains

  deny    message       = "HELO/EHLO required by SMTP RFC"
          condition     = ${if eq{$sender_helo_name}{}{yes}{no}}

  accept  authenticated = *

  deny    message       = "Your IP in HELO - access denied!"
          hosts         =  * : !+relay_from_hosts : !81-196.lissyara.su
          condition     = ${if eq{$sender_helo_name}\
    {$sender_host_address}{true}{false}}

  deny    condition     = ${if eq{$sender_helo_name}\
    {$interface_address}{yes}{no}}
          hosts         = !127.0.0.1 : !localhost : *
          message       = "My IP in your HELO! Access denied!"

  deny    condition     = ${if match{$sender_helo_name}\
    {\N^\d+$\N}{yes}{no}}
          hosts         = !127.0.0.1 : !localhost : *
          message       = "Incorrect HELO string"

# filter spammers from dynamic ips
  deny    message       = "your hostname is bad (adsl, poll, ppp & etc)."
          condition     = ${if match{$sender_host_name} \
                               {adsl|dialup|pool|peer|dhcp} \
                               {yes}{no}}

  warn
        set acl_m0 = 30s
  warn
        hosts = +relay_from_hosts:4.3.2.1/32:192.168.0.0/16 #disable waits for 'friendly' hosts
        set acl_m0 = 0s
  warn
        logwrite = Delay $acl_m0 for $sender_host_name \
[$sender_host_address] with HELO=$sender_helo_name. Mail \
from $sender_address to $local_part@$domain.
        delay = $acl_m0

  accept  domains       = +local_domains
          endpass
          message       = "No such user"
          verify        = recipient

  accept  domains       = +relay_to_domains
          endpass
          message       = "i don't know how to relay to this address"
          verify        = recipient

#  deny    message       = "you in blacklist - $dnslist_domain \n $dnslist_text"
#          dnslists      = opm.blitzed.org : \
#                          cbl.abuseat.org : \
#                          bl.csma.biz 

  accept  hosts         = +relay_from_hosts

  deny    message       = "Homo hominus lupus est"

acl_check_data:

  # check for viruses
  deny malware = *
  message = "Your message contains viruses: $malware_name"

  # if needed - add spam filtering here

  # permit everything else
  accept

begin routers

dnslookup:
  driver = dnslookup
  domains = ! +local_domains
  transport = remote_smtp
  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
  no_more

system_aliases:
    driver      = redirect
    allow_fail
    allow_defer
    data = ${lookup mysql{SELECT `goto` FROM `alias` WHERE \
            `address`='${quote_mysql:$local_part@$domain}' OR \
                `address`='${quote_mysql:@$domain}'}}

dovecot_user:
  driver = accept
  condition = ${lookup mysql{SELECT `goto` FROM \
  `alias` WHERE \
  `address`='${quote_mysql:$local_part@$domain}' OR \
  `address`='${quote_mysql:@$domain}'}{yes}{no}}
  transport = dovecot_delivery

begin transports

remote_smtp:
  driver = smtp
  interface = 4.3.2.1 #your public ip address, if it's the main server ip - you could skip this parameter. if it's an alias- it must be specified in clear

dovecot_delivery:
  driver = pipe
  command = /usr/libexec/dovecot/deliver -d $local_part@$domain
  message_prefix =
  message_suffix =
  delivery_date_add
  envelope_to_add
  return_path_add
  log_output
  user = exim

address_pipe:
  driver = pipe
  return_output

address_reply:
  driver = autoreply

begin retry

*                    *       F,2h,15m; G,16h,1h,1.5; F,4d,6h

begin rewrite

begin authenticators

auth_plain:
  driver = plaintext
  public_name = PLAIN
  server_condition = ${lookup mysql{SELECT `username` FROM \
                     `mailbox` WHERE `username` = \
                     '${quote_mysql:$auth2}' AND `password` = \
                     '${quote_mysql:$auth3}'}{yes}{no}}
  server_prompts = :
  server_set_id = $auth2

auth_login:
  driver = plaintext
  public_name = LOGIN
  server_condition = ${lookup mysql{SELECT `username` FROM \
                     `mailbox` WHERE `username` = \
                     '${quote_mysql:$auth1}' AND `password` = \
                     '${quote_mysql:$auth2}'}{yes}{no}}
  server_prompts = Username:: : Password::
  server_set_id = $auth1

auth_cram_md5:
  driver = cram_md5
  public_name = CRAM-MD5
  server_secret = ${lookup mysql{SELECT `password` FROM \
                        `mailbox` WHERE `username` \
                        = '${quote_mysql:$auth1}'}{$value}fail}
  server_set_id = $auth2

Now, on to dovecot:

#File: /etc/dovecot.conf
base_dir = /var/run/dovecot/
protocols = imap pop3

listen = *
disable_plaintext_auth = no
shutdown_clients = yes
log_timestamp = "%b %d %H:%M:%S "
syslog_facility = mail
ssl_disable = yes

login_dir = /var/run/dovecot/login
login_chroot = no

login_process_size = 64
login_process_per_connection = yes
login_processes_count = 3
login_max_processes_count = 128
login_max_connections = 256
login_greeting = Dovecot ready man.
login_log_format_elements = user=<%u> method=%m rip=%r lip=%l %c
login_log_format = %$: %s
mail_location = maildir:~/home/vmail/%d/%n

first_valid_uid=93
last_valid_uid=0

protocol imap {
  mail_plugins = quota imap_quota
  imap_client_workarounds = outlook-idle netscape-eoh tb-extra-mailbox-sep
}

protocol pop3 {
  pop3_uidl_format = %08Xu%08Xv
  pop3_client_workarounds = outlook-no-nuls oe-ns-eoh
}

protocol lda {
  postmaster_address = admin@eulinux.org
  auth_socket_path = /var/run/dovecot/auth-master
}

auth default {
  mechanisms = plain
  passdb pam {
  }

  passdb sql {
    args = /etc/dovecot-mysql.conf
  }

  userdb passwd {
  }

  userdb sql {
    args = /etc/dovecot-mysql.conf
  }
  user = root
  socket listen {
    master {
      path = /var/run/dovecot/auth-master
      mode = 0660
      user = exim
      group = exim
    }
  }
}

dict {
}

plugin {
}
#File: /etc/dovecot-mysql.conf
driver = mysql
connect = host=localhost dbname=vexim user=vexim password=kieHeed3ailuph8b
default_pass_scheme = CRYPT
password_query = SELECT `username` as `user`, `password` FROM  `mailbox` WHERE `username` = '%n@%d' AND `active`='1'
user_query = SELECT "" AS `home`, 93 AS `uid`, 93 AS `gid` FROM `mailbox` WHERE `username` = '%n@%d' AND `active`='1'

Now, start the services:

for srv in exim dovecot clamd;
do
 service ${srv} start
done

Access your postfixadmin configuration file at:

http://hostname/mailadmin/setup.php

You should see a list of ‘OK’ messages.

The setup.php script will attempt to create the database structure
(or upgrade it if you’re coming from a previous version).

Assuming everything is OK you can create the admin user using the form displayed.

Once you submit the form, all that’s left to do is to delete “setup.php”

That seems to be all! ;)

adding a system user for daemon

2012 December 31
Comments Off
Posted by shirker2006

Example

groupadd -g 36 dovcot

useradd -d /dev/null -c “Dovecot User” -g dovcot -s /bin/false -u 36 dovecot

..openssl/lib/libssl.a: could not read symbols: Bad value

2012 December 30
Comments Off
Posted by shirker2006

/usr/bin/ld: /usr/pw/apache/openssl/lib/libssl.a(s3_srvr.o): relocation R_X86_64_32 against `.rodata’ can not be used when making a shared object; recompile with -fPIC

https://www.apachelounge.com/viewtopic.php?p=21376

The root problem seems to be with your compile of OpenSSL-1.0.1, not Apache.

Per the error message “recompile with -fPIC ”, you should add the switch -fPIC to your ./config (or your ./Configure) command when you build OpenSSL. You may also want to add no-gost to this command too.
I use these commands to build OpenSSL on X64 Linux:

Code:
./config –prefix=${destination_dir} -fPIC no-gost no-shared no-zlib
make
make install

Position Independent Code is necessary for a module like mod_ssl which may get placed anywhere in memory at runtime. It is not necessary for the standalone OpenSSL test program, which is why make test worked OK without -fPIC.

FYI – The OpenSSL code for the 1970′s-era Soviet GOST cipher can cause problems when compiling with -fPIC on X64 platforms. Since GOST is not used by modern browsers, omitting this cipher should not cause you any problems with mod_ssl.

LFS: Unable to boot on vmware workstation kernel panic

2012 December 29
Comments Off
Posted by shirker2006

http://www.linuxquestions.org/questions/linux-newbie-8/unable-to-boot-on-vmware-workstation-6-5-kernel-panic-824851/

To fix this without changing to an IDE disk (keep SCSI), make sure the following options are enabled in the kernel config:

Device Drivers —>[*] Fusion MPT device support —>
<*> Fusion MPT ScsiHost drivers for SPI
<*> Fusion MPT ScsiHost drivers for FC
<*> Fusion MPT ScsiHost drivers for SAS

If you enable these on top of the “make defconfig” kernel, it should work.
Note that I’m using VMWare Player 3.1.4 and Linux 2.6.37.2.

How to block all facebook’s IPs with pfsense

2012 November 28
Comments Off
Posted by shirker2006

To get networks list just do in linux shell

whois -h whois.radb.net '!gAS32934'

AS32934 is “OriginAS:” name of Facebook, can be seen at http://centralops.net/co/

“OriginAS:” of YOUTUBE are:

AS43515, AS36040, AS36561

Now what you have to do, just put these networks to txt file, upload to your webserver.
Next step – Go to pFsense, create new alias in firewall tabs. Type of alias – URL and insert web path to your file with targeted networks. pFsense will read that file, and if format is correct – will save these networks. Make name to that alias. Example: “facebook”. Then go to Firewall-> Rules. Click your LAN rules. Create and move up new rule – Block/Reject all, instead IP address put – facebook. Save and refresh rules.

How to Setup MRTG step by step

2012 October 31
Comments Off
Posted by shirker2006

http://www.linux-noob.com/forums/index.php?/topic/1907-how-to-setup-mrtg-step-by-step/

Ok so it has been a while since I wrote a how-to for this site so here goes. This seems to be one of the more sought after confgiurations for network monitoring. You will need apache (httpd), mrt, and net-snmp-utils installed. since most noobs use RPM installations I am sure you can figure ou how to use the add remove programs or rpm -ivh <rpm>.

Below is the example of me adding my internet ip of my firewall to mrtg. First you need to make sure you can get snmp data from the device you wish to monitor.

Quote

snmpwalk -v 1 -c public 69.250.150.54 system

#you hould see this output for snmp walk:

Quote

[root@webfc4 ~]# snmpwalk -v 1 -c public 69.250.150.54 system
SNMPv2-MIB::sysDescr.0 = STRING: Linux fw1 2.4.9-39cp #1 Sun Jun 1 10:32:06 GMT 2003 i686
SNMPv2-MIB::sysObjectID.0 = OID: NET-SNMP-MIB::netSnmpAgentOIDs.10
SNMPv2-MIB::sysUpTime.0 = Timeticks: (230122338) 26 days, 15:13:43.38
SNMPv2-MIB::sysContact.0 = STRING: Unknown
SNMPv2-MIB::sysName.0 = STRING: fw1
SNMPv2-MIB::sysLocation.0 = STRING: “Unknown”
SNMPv2-MIB::sysServices.0 = INTEGER: 76
SNMPv2-MIB::sysORLastChange.0 = Timeticks: (9) 0:00:00.09
SNMPv2-MIB::sysORID.1 = OID: IF-MIB::ifMIB
SNMPv2-MIB::sysORID.2 = OID: SNMPv2-MIB::snmpMIB
SNMPv2-MIB::sysORID.3 = OID: TCP-MIB::tcpMIB
SNMPv2-MIB::sysORID.4 = OID: IP-MIB::ip
SNMPv2-MIB::sysORID.5 = OID: UDP-MIB::udpMIB
SNMPv2-MIB::sysORID.6 = OID: SNMP-VIEW-BASED-ACM-MIB::vacmBasicGroup
SNMPv2-MIB::sysORID.7 = OID: SNMP-FRAMEWORK-MIB::snmpFrameworkMIBCompliance
SNMPv2-MIB::sysORID.8 = OID: SNMP-MPD-MIB::snmpMPDCompliance
SNMPv2-MIB::sysORID.9 = OID: SNMP-USER-BASED-SM-MIB::usmMIBCompliance
SNMPv2-MIB::sysORDescr.1 = STRING: The MIB module to describe generic objects for network interface sub-layers
SNMPv2-MIB::sysORDescr.2 = STRING: The MIB module for SNMPv2 entities
SNMPv2-MIB::sysORDescr.3 = STRING: The MIB module for managing TCP implementations
SNMPv2-MIB::sysORDescr.4 = STRING: The MIB module for managing IP and ICMP implementations
SNMPv2-MIB::sysORDescr.5 = STRING: The MIB module for managing UDP implementations
SNMPv2-MIB::sysORDescr.6 = STRING: View-based Access Control Model for SNMP.
SNMPv2-MIB::sysORDescr.7 = STRING: The SNMP Management Architecture MIB.
SNMPv2-MIB::sysORDescr.8 = STRING: The MIB for Message Processing and Dispatching.
SNMPv2-MIB::sysORDescr.9 = STRING: The management information definitions for the SNMP User-based Security Model.
SNMPv2-MIB::sysORUpTime.1 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.2 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.3 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.4 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.5 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.6 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.7 = Timeticks: (9) 0:00:00.09
SNMPv2-MIB::sysORUpTime.8 = Timeticks: (9) 0:00:00.09
SNMPv2-MIB::sysORUpTime.9 = Timeticks: (9) 0:00:00.09
[root@webfc4 ~]#

Now you need to make the config (cfg) file for the device you want to monitor.

Quote

/usr/bin/cfgmaker –output=/etc/mrtg/69.250.150.54.cfg –ifref=ip –global “workdir: /var/www/mrtg” –snmp-options=:::::1 public@69.250.150.54

Now you need to run the env statement “three” times:

Quote

#run three times
#env LANG=C /usr/bin/mrtg /etc/mrtg/mrtg.cfg
env LANG=C /usr/bin/mrtg /etc/mrtg/69.250.150.54.cfg

#You should see this after each time ran:

Quote

[root@webfc4 ~]# env LANG=C /usr/bin/mrtg /etc/mrtg/69.250.150.54.cfg
Rateup WARNING: /usr/bin/rateup could not read the primary log file for 69.250.150.54_192.168.1.2
Rateup WARNING: /usr/bin/rateup The backup log file for 69.250.150.54_192.168.1.2 was invalid as well
Rateup WARNING: /usr/bin/rateup Can’t remove 69.250.150.54_192.168.1.2.old updating log file
Rateup WARNING: /usr/bin/rateup Can’t rename 69.250.150.54_192.168.1.2.log to 69.250.150.54_192.168.1.2.old updating log file
[root@webfc4 ~]# env LANG=C /usr/bin/mrtg /etc/mrtg/69.250.150.54.cfg
Rateup WARNING: /usr/bin/rateup Can’t remove 69.250.150.54_192.168.1.2.old updating log file
[root@webfc4 ~]# env LANG=C /usr/bin/mrtg /etc/mrtg/69.250.150.54.cfg
[root@webfc4 ~]#

Now you need to make the actual index files for each machine:
#Very important you need to append the new machine to the line each time, if you do not you will only see
the newest entry.

Quote

indexmaker –output=/var/www/mrtg/index.html /etc/mrtg/mrtg.cfg /etc/mrtg/192.168.1.100.cfg /etc/mrtg/192.168.1.102.cfg /etc/mrtg/192.168.1.204.cfg /etc/mrtg/192.168.1.2.cfg /etc/mrtg/69.250.150.54.cfg

Now lets edit mrtg to poll ever 5 minutes:

Quote

vi /etc/cron.d/mrtg

#Enter in you machines like my example below:

0-59/5 * * * * root env LANG=C /usr/bin/mrtg /etc/mrtg/mrtg.cfg
0-59/5 * * * * root env LANG=C /usr/bin/mrtg /etc/mrtg/192.168.1.100.cfg
0-59/5 * * * * root env LANG=C /usr/bin/mrtg /etc/mrtg/192.168.1.102.cfg
0-59/5 * * * * root env LANG=C /usr/bin/mrtg /etc/mrtg/192.168.1.204.cfg
0-59/5 * * * * root env LANG=C /usr/bin/mrtg /etc/mrtg/192.168.1.2.cfg
0-59/5 * * * * root env LANG=C /usr/bin/mrtg /etc/mrtg/69.250.150.54.cfg

Now restart the crond service.

Quote

service crond restart

Strabo

ssh Fail to ban – simple script

2012 September 23
Comments Off
Posted by shirker2006

This script will block those guys who attempted and failed to connect by ssh to your server
just make new script, and add it to cron every 5min
NOTE: there will be no chance for mistakes
edit your local net IP

[root@asterisk21 ~]# cat /usr/share/astguiclient/ssh_control.sh
#!/bin/bash

for i in `cat /var/log/secure | grep -v "192.168.0" | grep Failed | grep -Eo '(([0-9]{1,3}\.){3}[0-9]{1,3})' | uniq`; do
     VAR=`/sbin/iptables -nvL | grep $i | awk '{print $8}'| grep -v "0.0.0.0"| uniq`;
     #echo $VAR;
     #echo $i;
        if [ "$VAR" != "$i" ]; then
            /sbin/iptables -A INPUT -s $i -j DROP
            /sbin/iptables -A OUTPUT -d $i -j DROP
            echo "IP $i has been blocked"
        fi
done

Installing and Configuring VSFTPD FTP Server for Redhat Enterprise Linux, CentOS & Fedora

2012 August 30
Comments Off
Posted by shirker2006

from http://www.firewall.cx/linux-knowledgebase-tutorials/system-and-network-services/875-linux-vsftpd-setup-configure.html
Vsftpd is a popular FTP server for Unix/Linux systems. For thoes unaware of the vsftpd ftp server, note that this is not just another ftp server, but a mature product that has been around for over 12 years in the Unix world. While Vsftpd it is found as an installation option on many Linux distributions, it is not often Linux system administrators are seeking for installation and configuration instructions for it, which is the reason we decide to cover it on Firewall.cx.

This article focuses on the installation and setup of the Vsftpd service on Linux Redhat Enterprise, Fedora and CentOS, however it is applicable to almost all other Linux distributions.  We’ll also take a look at a number of great tips which include setting quotas, restricting access to anonymous users, disabling uploads, setting a dedicated partition for the FTP service, configuring the system’s IPTable firewall and much more.

VSFTPD Features

Following is a list of vsftpd’s features which confirms this small FTP package is capable of delivering a lot more than most FTP servers out there:

  • Virtual IP configurations
  • Virtual users
  • Standalone or inetd operation
  • Powerful per-user configurability
  • Bandwidth throttling
  • Per-source-IP configurability
  • Per-source-IP limits
  • IPv6
  • Encryption support through SSL integration
  • and much more….!

Installing the VSFTPD Linux Server

To initiate the installation of the vsftpd package, simply open your CLI prompt and use the yum command (you need root privileges) as shown below:

yum install vsftpd

Yum will automatically locate, download and install the latest vsftpd version.

Configure VSFTPD Server

To open the configuration file, type:

vi /etc/vsftpd/vsftpd.conf

Turn off standard ftpd xferlog log format and turn on verbose vsftpd log format by making the following changes in the vsftpd.conf file:

xferlog_std_format=NO
log_ftp_protocol=YES
Note: the default vsftpd log file is /var/log/vsftpd.log.

Above two directives will enable logging of all FTP transactions.

To lock down users to their home directories:

chroot_local_user=YES

You can create warning banners for all FTP users, by defining the path:

banner_file=/etc/vsftpd/issue

Now you can create the /etc/vsftpd/issue file with a message compliant with the local site policy or a legal disclaimer:

“NOTICE TO USERS – Use of this system constitutes consent to security monitoring and testing. All activity is logged with your host name and IP address”.

Turn On VFSTPD Service

Turn on vsftpd on boot:

systemctl enable vsftpd@.service

Start the service:

systemctl start vsftpd@vsftpd.service

You can verify the service is running and listening on the correct port using the following command:

netstat -tulpn | grep :21

Here’s the expected output:

tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      LISTEN 9734/vsftpd

Configure IPtables To Protect The FTP Server

In case IPTables are configured on the system, it will be necessary to edit the iptables file and open the ports used by FTP to ensure the service’s operation.

To open file /etc/sysconfig/iptables, enter:

vi /etc/sysconfig/iptables

Add the following lines, ensuring that they appear before the final LOG and DROP lines for the RH-Firewall-1-INPUT:

-A RH-Firewall-1-INPUT -m state –state NEW -p tcp –dport 21 -j ACCEPT

Next, open file /etc/sysconfig/iptables-config, and enter:

vi /etc/sysconfig/iptables-config

Ensure that the space-separated list of modules contains the FTP connection-tracking module:

IPTABLES_MODULES=”ip_conntrack_ftp”

Save and close the file and finally restart the firewall using the following commands:

systemctl restart iptables.service
systemctl restart ip6tables.service


Tip: View FTP Log File

Type the following command:

tail -f /var/log/vsftpd.log

Tip: Restricting Access to Anonymous User Only

Edit the vsftpd configuration file /etc/vsftpd/vsftpd.conf and add the following:

local_enable=NO

Tip: To Disable FTP Uploads

Edit the vsftpd configuration file /etc/vsftpd/vsftpd.conf and add the following:

write_enable=NO

Tip: To Enable Disk Quota

Disk quota must be enabled to prevent users from filling a disk used by FTP upload services. Edit the vsftpd configuration file. Add or correct the following configuration options to represents a directory which vsftpd will try to change into after an anonymous login:

anon_root=/ftp/ftp/pub

The ftp users are the same users as those on the hosting machine.

You could have a separate group for ftp users, to help keep their privileges down (for example ‘anonftpusers’). Knowing that, your script should do:

useradd -d /www/htdocs/hosted/bob -g anonftpusers -s /sbin/nologin bob

echo bobspassword | passwd –stdin bob
echo bob >> /etc/vsftpd/user_list

Be extremely careful with your scripts, as they will have to be run as root.

However, for this to work you will have to have the following options enabled in /etc/vsftpd/vsftpd.conf:

userlist_enable=YES
userlist_deny=NO

Security Tip: Place the FTP Directory on its Own Partition

Separation of the operating system files from FTP users files may result into a better and secure system. Restricting the growth of certain file systems is possible using various techniques. For example, use /ftp partition to store all ftp home directories and mount ftp with nosuid, nodev and noexec options. A sample /etc/fstab entry:

/dev/sda5  /ftp          ext3    defaults,nosuid,nodev,noexec,usrquota 1 2


Example File for vsftpd.conf

Following is an example for vsftpd.conf. It allows the users listed in the user_list file to log in, no anonymous users, and quite tight restrictions on what users can do:

# Allow anonymous FTP?

anonymous_enable=NO
#
# Allow local users to log in?
local_enable=YES
#
# Allow any form of FTP write command.
write_enable=YES
#
# To make files uploaded by your users writable by only
# themselves, but readable by everyone and if, through some
# misconfiguration, an anonymous user manages to upload a file, # the file will have no read, write or execute permission. Just to be # safe.
local_umask=0000
file_open_mode=0644
anon_umask=0777
#
# Allow the anonymous FTP user to upload files?
anon_upload_enable=NO
#
# Activate directory messages – messages given to remote users when they
# go into a certain directory.
dirmessage_enable=NO
#
# Activate logging of uploads/downloads?
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data)?
connect_from_port_20=YES
#
# Log file in standard ftpd xferlog format?
xferlog_std_format=NO
#
# User for vsftpd to run as?
nopriv_user=vsftpd
#
# Login banner string:
ftpd_banner= NOTICE TO USERS – Use of this system constitutes consent to security monitoring and testing. All activity is logged with your host name and IP address.
#
# chroot local users (only allow users to see their directory)?
chroot_local_user=YES
#
# PAM service name?
pam_service_name=vsftpd
#
# Enable user_list (see next option)?
userlist_enable=YES
#
# Should the user_list file specify users to deny(=YES) or to allow(=NO)
userlist_deny=NO
#
# Standalone (not run through xinetd) listen mode?
listen=YES
#
#
tcp_wrappers=NO
#
# Log all ftp actions (not just transfers)?
log_ftp_protocol=YES
# Initially YES for trouble shooting, later change to NO
#
# Show file ownership as ftp:ftp instead of real users?
hide_ids=YES
#
# Allow ftp users to change permissions of files?
chmod_enable=NO
#
# Use local time?
use_localtime=YES
#
# List of raw FTP commands, which are allowed (some commands may be a security hazard):
cmds_allowed=ABOR,QUIT,LIST,PASV,RETR,CWD,STOR,TYPE,PWD,SIZE,NLST,PORT,SYST,PRET,MDTM,DEL,MKD,RMD

With this config, uploaded files are not readable or executable by anyone, so the server is acting as a ‘dropbox‘. Change thefile_open_modeoption to change that.Lastly, it is also advised to have a look at ‘man vsftpd.conf‘ for a full list and description of all options.

PHP Deprecated: Function ereg() is deprecated in…

2012 August 16
Comments Off
Posted by shirker2006

http://www.cyberforum.ru/php-beginners/thread159985.html

Цитата Сообщение от SATMAN Посмотреть сообщение
Код PHP
1
if (ereg ('^[a-zA-Z0-9 \._\-]',$names))
Код PHP
1
if (preg_match ('/^[a-zA-Z0-9 \\._\\-]/',$names))

Важно шаблон указывать в ограничителях и не забывать экранировать ограничитель внутри шаблона, если он там есть. После закрывающего ограничителя могут быть модификаторы.
Пример. Раньше было

Код PHP
1
2
ereg('шаблон', $s)
eregi('шаблон', $s)

Теперь стало

Код PHP
1
2
preg_match('/шаблон/', $s)
preg_match('/шаблон/i', $s)

zabbix through gmail

2012 August 4
Comments Off
Posted by shirker2006

http://dev.aperto.fr/projects/3/wiki/Advanced_email_notifications

Zabbix integrated Email media facility is restricted to basic SMTP protocol. It does not support advanced SMTP capabilities such as authentication or encrypted communication with TLS

Zabbix notification system can be extended with external programs. This solution is based on msmtp command line utility that integrates advanced SMTP capabilities.

Email content customization

Zabbix integrated Email media facility can only send simple text emails.
With an external script, it is possible to add custom email headers. It allows to use HTML formatted messages or change message priority.

Installation

Prerequisites

msmtp must be installed.

  • On Debian or Ubuntu:
    apt-get install msmtp

msmtp media script

zext_msmtp.sh script (latest version) should be installed in alert scripts directory on Zabbix server.
This directory is defined in zabbix_server.conf by AlertScriptsPath parameter.
Default value is:

AlertScriptsPath=/etc/zabbix/alert.d/

By default, zext_msmtp.sh uses zabbix account as defined in msmtp configuration file (/etc/msmtprc by default).
See configuration examples below.

Configuration

Simple SMTP configuration

This configuration is equivalent to Zabbix internal email media. It does not use any advanced SMTP capability but is useful for email content customization.

/etc/msmtprc

account zabbix
host smtp.example.org
domain example.org
from zabbix@example.org

Advanced SMTP configuration

This example illustrate how to configure msmtp to use a Gmail account to send messages as described in Gmail help. It sets authentication and uses TLS/STARTTLS (port 587).

/etc/msmtprc

account zabbix
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
host smtp.gmail.com
port 587
auth on
from zabbixaccount@gmail.com
user zabbixaccount@gmail.com
password ***********

Media definition

In Zabbix Web interface, Administration/Media Types page, create a new media type:

and save it.

User media configuration

In Zabbix Web interface, Administration/Users page; select user and add a new media:

and save it.

Set message priority

X-Priority sets the priority for an email. its value ranges from “1″ to “5″ where “1″ is the highest priority, “3″ is normal, and “5″ is the lowest priority.

In Configuration/Actions, select an action and set message content to:

X-Priority: 1

{TRIGGER.NAME}: {TRIGGER.STATUS}
Last value: {ITEM.LASTVALUE}

{TRIGGER.URL}

will send notification messages with highest priority.

HTML formatted message

Previous message in HTML format:

X-Priority: 1
Content-Type: text/html

<html>
<body>
<h1>{TRIGGER.NAME}: {TRIGGER.STATUS}</h1>
<p>Last value: {ITEM.LASTVALUE}</p>
<p><a href="{TRIGGER.URL}">Trigger URL</a></p>
</body>
</html>

zabbix-zext_msmtp-media.png (12.7 ) Joseph Bueno, 02/24/2011 02:45 pm

zabbix-zext_msmtp-user_media.png (18.9 ) Joseph Bueno, 02/24/2011 02:45 pm

#! /bin/sh
################################################################################
# Zabbix extensions (C) 2011-* Joseph Bueno <zabbixextensions@aperto.fr>
# Published under GNU General Public License version 2 or later.
# See LICENSE.txt
#-------------------------------------------------------------------------------
# Usage:
#   zext_msmtp.sh <recipient> <subject> <message>
#
# Description:
#  Uses msmtp to send an email.
#  This script inserts headers:
#    From:    see FROM variable
#    To:      using <recipient>
#    Date:    dynamically computed
#    Subject: using <subject>
#
#  <message> may start with headers, msmtp will seperate them from message body
#  and put them in message headers section.
#
# It uses an msmtp account as defined in MSMTP_ACCOUNT
# Account is defined in /etc/msmtprc
#
# simple account configuration
# ----------------------------
# account zabbix
# host smtp.example.org
# from zabbix@example.org
#
# advanced account setup (authentication + TLS on Gmail)
# ------------------------------------------------------
# account zabbix
# tls on
# tls_starttls on
# tls_trust_file /etc/ssl/certs/ca-certificates.crt
# host smtp.gmail.com
# port 587
# auth on
# from zabbixaccount@gmail.com
# user zabbixaccount@gmail.com
# password ***********
#
# (from, user and password should be replaced with real values).
#
# Dependencies
#  It needs msmtp utility
#  On Debian and Ubuntu:
#    apt-get install msmtp
#
################################################################################
DEBUG=0
if [ $DEBUG -gt 0 ]
then
        exec 2>>/tmp/zext_msmtp.log
        set -x
fi
# Default parameters
FROM='zabbix@simplex-bpo.us'
MSMTP_ACCOUNT='zabbix'

# Parameters (as passed by Zabbix):
#  $1 : Recipient
#  $2 : Subject
#  $3 : Message
recipient=$1
#recipient=vlad@simplex-bpo.us
subject=$2
message=$3

date=`date --rfc-2822`

# Replace linefeeds (LF) with CRLF and send message
sed 's/$/\r/' <<EOF | /usr/local/bin/msmtp -C /etc/msmtp/config --account $MSMTP_ACCOUNT $recipient
From: <$FROM>
To: <$recipient>
Subject: $subject
Date: $date
$message
EOF

Vicibox SVN Trunk Upgrade

2012 July 30
Comments Off
Posted by shirker2006

1. Backup existing system:

1.1 Run this for a 1-server system or server with database on it:
(this may take hours on large system)

/usr/share/astguiclient/ADMIN_backup.pl --debugX

1.2 Run this on dialer/Asterisk-only servers:
(do not run this if you only have one server):

/usr/share/astguiclient/ADMIN_backup.pl --debugX --without-db --without-web

2. Test backup:

Create a new (any name) database on any mysql server, apply the backup data to it, and verify a new lead from TODAY is actually in there.

3. On ALL servers: (Database, web, telephony)

cd /usr/src/astguiclient

Download Vicidial trunk on ALL servers

svn checkout svn://svn.eflo.net:3690/agc_2-X/trunk

4. On ONLY database server:

Going into mysql and executing the upgrade sql file:
mysql (alternatively use mysql -u root -p)
use asterisk

\. /usr/src/astguiclient/trunk/extras/upgrade_2.4.sql

quit

(When you do an update on the Database side by issuing a
“\. /usr/src/astguiclient/trunk/extras/upgrade_2.4.sql” from mysql prompt you also need to ‘run’:
“\. /usr/src/astguiclient/trunk/extras/upgrade_2.6.sql”

The 2.6 upgrade will add 3 columns to the vicidial_campaigns table ” in_group_dial | in_group_dial_select | safe_harbor_audio_field”. If you don’t do the 2.6 upgrade SQL you will have problems…)

5. On ALL servers: (Database, web, telephony)

cd /usr/src/astguiclient/trunk
perl ./install.pl

Your original settings should still be the same so you really just have to double check the settings and hit enter through all the options.

NOTES: If you have customized any scripts in the bin or agi folders,
then make sure you back them up before running the install.pl script.
This script will replace existing files in the astguiclient installation.

6. For each of your ViciDial servers:

go to the Admin -> Servers -> Modify Server
page and set each one to “Rebuild conf files = Y” and click submit.
This will rebuild the conf files to ensure any changes are updated.

7. On one server only, update your phone codes data:

/usr/share/astguiclient/ADMIN_area_code_populate.pl --purge-table –debug

George Carlin – Life is worth losing

2012 July 29
Comments Off
Posted by shirker2006

Life is worth losing

from http://georgecarlinscripts.blogspot.com/
I’m a modern man, a man for the millennium. Digital and smoke-free. A diversified multi-cultural, post-modern deconstructionist; politically, anatomically and ecologically incorrect. I’ve been uplinked and downloaded, I’ve been inputted and outsourced, I know the upside of downsizing, I know the downside of upgrading. I’m a high-tech low-life. A cutting edge, state-of-the-art bicoastal multitasker and I can give you a gigabyte in a nanosecond!
I’m new wave, but I’m old school and my inner child is outward bound. I’m a hot-wired, heat seeking, warm-hearted cool customer, voice activated and bio-degradable. I interface with my database, my database is in cyberspace, so I’m interactive, I’m hyperactive and from time to time I’m radioactive.
Behind the eight ball, ahead of the curve, riding the wave, dodging the bullet and pushing the envelope. I’m on-point, on-task, on-message and off drugs. I’ve got no need for coke and speed. I’ve got no urge to binge and purge. I’m in-the-moment, on-the-edge, over-the-top but under-the-radar. A high-concept, low-profile, medium-range ballistic missionary. A street-wise smart bomb. A top-gun bottom feeder. I wear power ties, I tell power lies, I take power naps and run victory laps. I’m a totally ongoing big-foot, slam-dunk, rainmaker with a pro-active outreach. A raging workaholic. A working rageaholic. Out of rehab and in denial!
I’ve got a personal trainer, a personal shopper, a personal assistant and a personal agenda. You can’t shut me up. You can’t dumb me down because I’m tireless and I’m wireless. I’m an alpha male on beta-blockers.
I’m a non-believer and an over-achiever, laid-back but fashion-forward. Up-front, down-home, low-rent, high-maintenance. Super-sized, long-lasting, high-definition, fast-acting, oven-ready and built-to-last! I’m a hands-on, foot-loose, knee-jerk head case, pre-maturely post-traumatic and I’ve got a love-child that sends me hate mail.
But, I’m feeling, I’m caring, I’m healing, I’m sharing – a supportive, bonding, nurturing primary care-giver. My output is down, but my income is up. I take a short position on the long bond and my revenue stream has its own cash-flow. I read junk mail, I eat junk food, I buy junk bonds and I watch trash sports! I’m gender specific, capital intensive, user-friendly and lactose intolerant.
I like rough sex. I like tough love. I use the “F” word in my emails and the software on my hard-drive is hardcore – no soft porn. I bought a microwave at a mini-mall; I bought a mini-van at a mega-store. I eat fast-food in the slow lane. I’m toll-free, bite-sized, ready-to-wear and I come in all sizes. A fully-equipped, factory-authorized, hospital-tested, clinically-proven, scientifically- formulated medical miracle. I’ve been pre-washed, pre-cooked, pre-heated, pre-screened, pre-approved, pre-packaged, post-dated, freeze-dried, double-wrapped, vacuum-packed and, I have an unlimited broadband capacity.
I’m a rude dude, but I’m the real deal. Lean and mean. Cocked, locked and ready-to-rock. Rough, tough and hard to bluff. I take it slow, I go with the flow, I ride with the tide. I’ve got glide in my stride. Driving and moving, sailing and spinning, jiving and grooving, wailing and winning. I don’t snooze, so I don’t lose. I keep the pedal to the metal and the rubber on the road. I party hearty and lunch time is crunch time. I’m hanging in, there ain’t no doubt and I’m hanging tough, over and out!
[stormy ovation; GC thanks the crowd]
I’ve got 341 days sober and next year is my 50th anniversary in show business. Let’s do a fucking show, huh?
[crowd applauding]
You know something people don’t talk about in public anymore? Pussy farts.
[extended aplause]
So, anyway… Now I said that on my last HBO show, and apparently some people don’t know what a pussy fart is, because I got some inquiries. Here’s the deal. A pussy fart is like when your making love to a woman who has a little extra air in her vagina, and every time you thrust forward, it’s kind of a…
[makes a whole bunch of nasty fart noises]
And the two of you are lying there, each wondering if the other one farted. And the man is usually thinking, “Maybe she farts when she cums. Maybe she took a shit. Man, I better stay out of that fuckin’ bar.“
Another word you don’t hear too often is ’dingleberries’. You know, you never hear it on Meet the Press. The dingleberry solution, the dingleberry gate. Nothing. I think it’s because “dingleberries” is one of those words you don’t say too much past your tenth birthday. It’s not a grown-up’s word; it’s a kid’s word. “Dingleberries!” It always sounded kind of Christmasy to me. Don’t you think it has a holiday ring to it? “Dingleberries.” John, you might want to hang some dingleberries over the front door. Then when Marianne comes over, she can kiss you under the dingleberries!“ It is to be devoutly wished . . . that she would kiss me . . . under the dingleberries.
Cornhole is another word you don’t hear enough. You don’t hear that nearly enough. You know. It’s a good word, it’s a solid word, it’s a tough word, it’s a man’s kind of word. It’s got a masculine sound. Like ‘shotgun’ and ‘ashcan’ and ‘toetruck’… ‘Cornhole!’ Everything’s been sanitized now and cleaned up. First with these fucking Christians, you start with them. Let’s not leave out these PC capitalist liberal assholes – I mean they’re just as fucking bad, just from a different direction. But everything’s different. Everything’s been polished up now. It’s anal intercourse, anal rape… Bullshit, CORNHOLE! I’m a big fan of the prime time crime shows, I like all of them pretty much. I like law and order and all the spin-offs of that, I like CSI and all of those spin-offs. Because, they’re forensics shows. And I’m just waiting for one night to be sitting watching one of them shows and the chief medical examiner turns to the lead detective and says: „Steve, looks to me like after they killed this guy, the perpetrators rolled him over and cornholed him about twenty or thirty fucking times.That there is a posthumous multiple cornhole entry wound!“ In prison it’s a social activity. It’s right up there on the bulletin board. Checkers, handball, cornholing.
Now, just to change the subject a little bit. Do you realise, do you realise that right this second, right now, somewhere around the world, some guy is getting ready to kill himself. Isn’t that great? Isn’t that great? Do you ever stop and think about that kind of shit? I do. It’s fun. And it’s interesting and it’s true! Right this second, some guy is getting ready to bite the big bazooka. Because statistics show that every year a million people commit suicide. A million. Thats 2800 a day. That’s one every thirty seconds.
[checks his watch]
There goes another guy! And I say guy, because men are four times more likely than women to commit suicide, even though women attempt it more. So men are better at it. That’s something else you gals want to be working on. Well if you wanna be truly equal you’re gonna have to start taking your own lives in greater numbers.
But I just think it’s interesting to know. Interesting – that’s a big word in this show for me. Interesting to know that at any moment the odds are good that some guy is dragging a chair across the garage floor, trying to get it right underneath the ceiling beam. Don’t want to be too far off center, if it’s worth doing, it’s worth doing right. Somewhere else another guy is going over and getting a gun out of a dresser drawer. Somebody else is opening up a brand new package of razor blades. Maybe struggling with the cellophane a little bit. Ah shit, it’s always something. God damn it!
I just think that’s interesting as hell. That’s probably the most interesting thing you can do with your life – end it! I think I couldn’t do it though, could you? I couldn’t commit suicide if my life depended on it. But I understand it, I think I do. I don’t wonder about it, I don’t wonder why did he do that or what was going through his mind. You know what I wonder? Where do you find the fucking time? Who’s got time to be commiting suicide, aren’t you busy? I got shit to do. Suicide would be way down on my list. Probably dpwn past lighting my own house on fire. I might want to try a little self-mutilation first, take a couple of hunks out of my arm, see if I like the general idea. Because you have got to have priorities. You have got to have a plan too, you have got to plan that shit. People don’t just run out a house and jump off a bridge. There are things you have to decide. Timing is important. When you are going to do it? Well, let me see now. Wednesday is out – gotta take Timmy to the circus. Survival’s on on Thursday. Friday I’ve got my colon cleansing. Folks are coming over on Sunday. Sunday… My god that would be just a thing, maybe Mumma will find my body, will serve her right for fucking me up the way she did.
Then you have to pick a method. How are you going to do it? Well, let me see now, afraid of heights – that’s no good, can’t swallow pills, don’t like the sight of blood, fucking oven’s electric, I’d lie down in front of a train except the damn thing hasn’t come through here in thirty god-damn years. Maybe I’ll just take a gun and shoot myself in the mouth. Suppose I miss. People would be laughing at me. Suppose I live – I have big fucking hole in my head. I have to wear some kind of a dumb-ass hat. Well… I guess I can always hang myself, that would good. Have to get a rope, shit, it’s always something. I’ve got a rope in the garage… Nah, it has got a lot of grease and paint on it, don’t want to get that stuff on my neck. Walmart is having a special on ropes this weekend. No sense to spend a lot of money on killing myself. Then again I can always put it on my credit card and never going to have to pay the fucking thing. That’s it then, I’m hanging myself and Walmart’s paying for it.
What’s next? A note. Oh jesus. Have to express myself. Hell, if I could express myself, I wouldn’t be thinking on doing something like this. Where’s the pen? You never find a pen. Told the kids not to move the pen away from that telephone. God damn kids…Why don’t I just kill them too? Make it one of them family package deals. Ah, here’s a pen. Why don’t I just jam it in my fucking neck and get it over with? Let’s see now, where do you put the date? Upper left? I can never remember that. “To whom it may concern…” Ah, sounds kind of impersonal. “Dear Marcelle..”, ah, leaves out the kids. I know! “Hey guys, guess what! Keep on reading! How are you, I hope you are fine. I am not fine! As you can no doubt tell from me hanging down the ceiling fixture. You are the ones who drove me to this. I was doing just fine until you fuckers came along. I hope you’re happy now that I’m god-damn dead. Signed: the corpse in this room. PS: Fuck you people!”
That would be a good note. I don’t think a writer could ever commit suicide, do you? A writer would be too busy on working on the note the whole God damn year. Trying to get it just right. First draft, second draft, third revision, whole new ending, finally would turn into a book proposal and have a reason to live. That wouldn’t work.
I think about stuff like that. It’s interesting to be, like I said. Certain things are interesting. Suicide’s interesting. Life is filled with interesting things. That’s why I could never commit suicide – I’m having too much fun keeping an eye on you folks. Watching what you do.
Human behaviour – that’s what I like. Humans do some really interesting things. Like besides killing ourselves, we also kill eachother – murder. And we’re the only ones who do that, by the way. Humans are the only species on earth who deliberately kill members of a species for personal gain. Or pleasure. Sometimes it’s just fun. We’re also the only species who deliberately kill members of another species for personal gain. Or pleasure – that’s what hunters do. They kill for pleasure. That’s us, human beings – interesting folks. Murderers. Here’s an interesting form of murder we came up with – assassination. You know what’s interesting about assassination? Well, not only does it change those popularity polls in a big fucking hurry, but it’s also interesting to notice who it is who we assassinate. Do you ever stop to see who it is, who it is we kill? It’s always people who have told us to live together in harmony and try to love one another. Jesus, Gandhi, Lincoln, John Kennedy, Bobby Kennedy, Martin Luther King, Medgar Evers, Malcom X, John Lennon. They all said: try to live together peacefully. BAM! Right in the fucking head. Apparently we’re not ready for that. That’s difficult behaviour for us. We’re too busy thinking around, sitting around, trying to think up ways to kill each other. Here’s one we came up with, it’s efficient too. Genocide. You know. Kill large numbers of people just because they don’t look like you, they don’t talk like you and they don’t have the same kind of hats you do. You ever notice that any time there’s two groups of people who really hate each other, chances are good they are wearing different kind of hats. Keep an eye on that, it might be important.
But any time there’s a genocide there are always mass graves. Every time we kill some dictator and go marching into his country we always find mass graves. Thousands and thousands of dead bodies of people that the dictator killed. And everybody over here gets horrified: Oh, mass graves, mass graves! Well, shit, what’s a guy supposed to do with a couple thousand people he just killed? Dig sepparate holes? Fuck that shit. It’s labour intensive, get real! The whole idea of killing a large number of people at one time in one place is convenience. The efficiency. Throw them in the fucking hole.
Look at it this way. At least the dictator had the decency to throw a little dirt on them. Give the guy some credit. Dictator’s a busy man. Got a lot on his mind. Like trying to figure out who’s planning to kill *him*. So he can pick them up, put them in prison and *torture* them. Here’s another one of our interesting heart-warming behaviours we’ve come up with somewhere along the way – TORTURING each other.
You want to hear a really cool torture that the Romans invented? They also used it as a form of capital punishment, it’s *really* creative. They would take the guy in question, stuff him in a burlap sack, seal the sack up real tight and throw it in the river. But, and here’s the creative part, inside the sack, with the guy, they would put a dog, a monkey, and a snake. Okay? A dog, a monkey, and a snake. That’s fucking creative! Imagine being inside a burlap sack, underwater, in the dark, sitting next to a drowning monkey. Think he’d be moving around a little bit? The dog would be going apeshit, we know that. And the snake? Well, he’d probably be getting curious about what all the activity was inside the sack. He might do anything. Whatever he did would probably involve venom and his teeth. You know what you’d be doing? You’d be praying to God that the snake bit the monkey and the dog ate the snake. Praying.
Then it would be just you and the dog, man and his best friend, drowning together. Maybe before you die, you can teach him a few tricks. Roll over and play dead wouldn’t be too difficult, would it? Just a thought, just a playful thought.
I assume you’re noticing that all these activities I’m mentioning: murder, torture, genocide – these are all things human beings do. Not animals, those creatures we feel superior to. This is us.
Here’s another one of our spiritually uplifting activities. We don’t do this one much anymore, but it used to be really big. Human sacrifice. I miss that. The Aztecs loved human sacrifice and they were good at it. Well they got a lot of practice. For instance, around the year 1500 the Aztecs sacrificed 80 000 people in one ceremony. Okay? 80 000 people in one ceremony. You know what the occasion was? They were opening a new temple. Nothing like religion for a little entertainment, huh? . Especially that old time religion. Do you know how the Aztechs went about their sacrificing? Here’s how they would do it. They would do it right in public, right in front of everybody. Big town, beautiful city square. Twenty-thirty thousand people looking on. They would take the guy, lay him on an altar, cut his chest open, pull his heart out, hold it up in the air while it was still beating. Got that? Cut his chest open, pull his heart out, hold it up in the air while it was still beating. You know what you call that? Theatre. That is fucking theatre. And although the procedure may have been a little too crude to be considered the first by-pass surgery, it could easily be seen as an early form of organ donor program.
The Aztecs, human beings, just like us. Not too long ago, five hundred years. Kolumbus had already landed. This was just south of here – Mexico. And by the way those hearts didn’t go to waste. Did not go to waste. Because right after the ceremony, the royal family, naturally, would enjoy another one of our amusing acitivities – cannibalism. Imagine that – chowing down on another human being. You have got to be all out of beef jerky. You have got to be really fucking hungry. But it happens, doesn’t it. Still happens to this day. Bunch of people, stranded in the wilderness, run out of Pop Tarts, got to eat something. Might as well be Steve. And how do you decide who to eat first? How do you decide who’s first on the barbeque rack? Do you pick on the little guy, because he’s skinny and he can’t fight back or do you all gang up on the body-builder because he’s got a lot of steaks and chops on him? These are things human beings have to consider.
One more of these charming diversions of ours – necrophilia. Now there’s a hobby for you. Fucking a corpse. Takes a special kind of guy, don’t you think. But it happens, it happens. More than you might think. It happens among humans, animals don’t do that. Animals don’t fuck their dead. A rat will do a lot of gross things but it will not fuck a dead rat. It wouldn’t even occur to him. Only a human being would *think* to fuck someone who just died. We have got to be the most interesting creatures on the planet. And then we wonder why a UFO doesn’t just land and say hello.
You know the best thing about necrophilia? You don’t have to bring flowers. Ususally they’re already there. Isn’t that nice? It’s nice. It’s convenient.
Human beings will do anything, anything. I am convinced. That’s why, when all those beheadings started in Iraq, it didn’t bother me. A lot of people here were horrified, “Whaaaa, beheadings!” What, are you fucking surprised? Just one more form of extreme human behaviour. Besides, who cares about some mercenary civilian contractor from Oklahoma who gets his head cut off? Fuck them. Hey Jack, you don’t want to get your head cut off? Stay the fuck in Oklahoma. They aren’t cutting off heads in Oklahoma, as far as I know. But I do know this: you strap on a gun and go strutting around some other mens’ country you’d better be ready for some action, Jack. You’d better be ready for some action. People are touchy about that sort of thing. And let me ask you this while I have you good clean Americans here. This is a moral question, not rhetorical, I am looking for the answer: what is the moral difference between cutting off one guy’s head, or two, or three, of five or ten – and dropping a big bomb on a hospital and killing a whole bunch of sick kids? Has anybody in authority given you an explanation of the difference? I have not got an email on this, haven’t got a post card, no fucking instant messange, nothing. Now, in case you’re wondering why I have a certain interest, or fascination lets call it, with torture and beheadings and all of these things I’ve mentioned, is because each of these items reminds me in life, every time one of them occurs, reminds me over and over again what beasts we human beings really are. When you get right down to it, when you get right *down* to it, human beings are nothing more than ordinary jungle beasts. Savages. No different from the Cro Magnon people who lived twenty five thousand years ago in the plasticine forests eating crubs off rotten logs. No different. Our DNA hasn’t changed substantially in a houndred thousand years. We’re still operating out of the lower brain. The reptilian brain. Fight of flight. Kill or be killed. We like to think we’ve evolved and advanced because we can build a computer, fly an airplane, travel underwater, we can write a sonet, paint a painting, compose an opera. But you know something? We’re barely out of the jungle on this planet. Barely out of the fucking jungle. What we are, is semi-civilized beasts, with baseball caps and automatic weapons.
And this civilization of ours that we’re so proud of, this civilization with its so-called civilized behaviour. Have you ever stop and realize how fragile all of this really is? How easily it could all break just down? Break just down. Wouldn’t take much. Would probably happen in less that two years. Wouldn’t take much. Would throw us right back into barbaric times. All you’d have to do is eliminate electricity. That’s all. But completely. Eliminate electricity. So, no electricity, no lights. You’re back to candles and lanterns, camp fires and bonfires. Batteries couldn’t be recharged, generators couldn’t be refueled, because fuel is pumped electrically, so is water, by the way. So no lights, no fuel, no water. No computers, and computers run everything. And among the many things computers run that operate on electricity, are all of these security systems in all of ours jails and prisons and nuthouses. So, suddenly, without electricity all across America, the gates and cell doors of penitentiaries and mental institutions would fly open. And out would come all of our old friends. The ones who’ve been away. At camp. Serial killers, mass murderers, felony rapists, armed robbers, car-jackers, home invaders, thieves, burglers, kid-nappers, sadists, pedophiles, sexual predators, pimps, pushers, pornographers, speed-freaks, crackheads, sick junkies, *all* the ethnic street gangs: black, Spanish and Asian gangs, Japanese Yakuza, Russian maffia, neo-nazis, white supremesists, the Sicilian hitmen, Italian mobsters, Jamaican and Columbian drug gangs. And those are just the ones we *caught*. Let’s not forget their counterparts still on the outside right now, waiting to hook up with their prison buddies, so they can start a new organization – The American Federation of Sociopaths. Just what the country needs. Another special interest group. Eight to ten million of them there would be, counting all the parolees and all the probationers and the ones that never been caught. Eight to ten million bitter, angry, violent, sexually hyperactive alpha-males with nothing to do. No hobbies, no medications, no scruples. Just a bunch of bad guys looking for a good time. Maybe tropping by your house. Hi, hope we’re not intruding. Got any beer. Oh good, I got about 1400 really thirsty guys here. How about women, got any women? Just your wife, huh? Well, I think we could make that work. Now boys, there’s a lady here, so I want you to mind your manners, and wait your turn. Police wouldn’t help you, they would be gone at the first sign of trouble. They would be home protecting their own families. So would the army and the National Guard. You’d be alone. You’d be on your own. You’d be SOL and JWF. Shit Out of Luck and Jolly Well Fucked. Shit Out of Luck and Jolly Well Fucked. After a couple of years living like that beheadings would be the least of your problems. People would be lining up to be beheaded.
So let’s get back to suicide which now seems like a reasonable alternative. Suicide is an interesting topic to me, because it’s an inherently interesting decision. To decide voluntarily not to exist anymore. It’s profound. You know what it is, it’s the ultimate makeover. That’s why I think it belongs on television. In this depraved culture we live in, with all of these reality shows, suicide and television would be a natural. I bet you could have an All-Suicide Channel on cable TV. I’ll bet you. Shit, they’ve got All-Golf. What the fuck? God damn. Jesus.
You ever watch golf? It’s like watching flies fuck. If you can get a bunch of brainless assholes’ assent on to waste their Sunday afternoon on that kind of shit, you *know* you can get some people watching some suicides. All day long, 24 hours a day, nothing but suicides. Must-Die TV. You would get a lot of people watching that shit. You would get a lot of people volunteering to be on there, too. So, just that their friends could see them on TV. People are fucking goofy. You would get a lot of volunteers. You would get all of them left-over assholes from „Let’s make a deal“. They would be lining around the block, pushing each other out the way, pushing on funny capes, caps and hamp hats, making up on calling themselves Captain Suicide. Guys would be competing for Most Unusual Method. People would be jumping off silos, lighting themselves on fire, putting rat poison on the taco, drinking moppin glow , sticking mothballs up their ass. You would probably have some weird fuck show up who would figure on trying to kill himself with dental flauce and a Stinger missle. People are fucking goofy.
I bet you can find you a married couple. In this country, shit, I’ll bet you. You can find a married couple in one of them trailor parks or something, who would be perfectly willing to sit in a love seat and blow each others heads off with shotguns, while a love song is playing. People are fucking nuts. This country is full of nitwits and assholes, did you ever notice that? Nitwits, assholes, fuck-ups, scumbags, jerk-offs and dipshits. And they all vote. They all vote and, in fact, sometimes you get the impression they’re the *only* ones who vote. You can usually tell who’s been doing the voting by looking at the fucking electoral returns. I sure wouldn’t be going out and wasting my time with a meaningless activity like that. You know all those people on the Jerry Springer show? Those are the average Americans. Believe me, below average can’t get on the show. Can’t get on. Below average are sitting home watching that shit on TV. Getting ready to go out and vote. Filling out their sample ballot. People are fucking dumb.
You can say what you want about this country and I love this place. I love the freedoms we used to have. I love that. I love it when it didn’t take a fucking catastrophy to get us to care for one another. I love the fact that we’re on camera all the time, from all angles. But you know, you can say what you want about America and I say I love this place. I wouldn’t have it any other way, live in any other time in history or any other place. BUT! Say what you want about America, land of the free, home of the brave, we’ve got some dumb-ass motherfuckers floating around in this country. *Dumb-ass motherfuckers*.
Now, obviously that doesn’t include this audience. I understand that. You seem intelligent and perceptive. But the rest of them, holy jumping fucking shit balls. Dumber than a second coat of paint. And this isn’t just ranting and raving. This isn’t just blowing off steam. I’ve got a little evidence to support my claim. It just seems to me, *seems* to me, that only a really low IQ population could have taken this beautiful continent, this magnificent American landscape that we inherited. Well actually we stole it from the Mexicans and the Indians, but hey, it was nice when we stole it. Looked pretty good, it was pristine. Paradise. Have you seen it lately? Have you taken a good look at it lately? It’s fucking embarrasing. Only a nation of unenlightened half-wits could have taken this beautiful place and turned it into what it is today – a shopping mall. A big fucking shopping mall. You know that, that’s all you’ve got here, folks. Mile after mile after mile of malls after malls. Many, many malls. Major malls and mini malls. They put the mini malls in between the major malls, and in between the mini malls, they put the mini marts. And in between the mini marts, you got the car lots, gas stations, muffler shops, laundry mats, cheap motels, fast food joints, strip clubs and dirty bookstores. America the beautiful. One big transcontinental commercial cesspool. And how do the people feel about all this? How do people feel about living in a coast to coast shopping mall? Well they think it’s JUST FUCKING DANDY!
They think it is as cool as can be, because Americans love the mall. That’s where they get to satisfy their two most prominent addictions, at the same time – shopping and eating. Millions of semi-conscious Americans, day after day, shuffling through the malls, shopping and eating. Especially eating. Americans *love* to eat. They are fatally attracted to the slow death of fast food. Hot dogs, corn dogs, triple-baconed cheese-burgers, deep fried butter-dipped pork, fat and cheese-whiz mayonnaise, soak-barbequed mozarella patty mouths. Americans will eat anything. Anything! If you were selling sortayed raccoon’s assholes on a stick, Americans would buy them and eat them. Especially if you dipped them in butter and put a little salt on them. This country is big time pig-time. Forget the bald eagle. You know what the national emblem of this country ought to be? A big bowl of macaroni and cheese. A big bowl, because everything in this country is king-sized, extra-large and super-jumbo.
Especially the fucking people. Have you seen some of the people of this country? Have you taken a good look at some of these big fat motherfuckers walking around, big fat motherfuckers. Oh my god, huge piles of redundant protoplasm, lumbering through the malls, like a fleet of interstate buses. The people in this country are immense. Massive bellies. Monstreous thighs. And big fat fucking asses. And if you stand there a minute and look at one of them, you begin to wonder: how does this woman take shit. How does she shit? And even more frightening: how does she wipe her ass? Can she even locate her asshole? She must require assistance. Are paramedics trained in this field? And standing right next to her, of course, with a plate full of nachos, a mouth full of pies, her clueless fucking husband Joe Sixpack, with his montreous swallen beer belly hanging dangerously out over his beer belt buckle. This guy hasn’t seen his dick since the Nixon administration. And if you stand there and look at the two of them you begin to wonder to yourself: do these people fuck? Is this man actually capable of fucking this woman? It doesn’t seem structurally possible that these two people could achieve penetration. Maybe they’re in that Cirque du Soleil or something.
I’m telling you, the people in this country, every one of them, is fifty pounds over-weight. They are gargantuan. And in the summer time, God help us, in the summer time they all want to wear short pants. Jesus Lord, protector of all that is good and holy, deliver me from fat people their short pants. They’ve all got short pants, big bellies, fat thighs and dumb kids. Short pants, big bellies, fat thighs and dumb kids. Every one of them has two dumb ass kids with them. And the whole family is wearing T-shirts, and every one of them has got the same T-shirt: „I’m with stupid“. Apparently, in this country, the Stupids are an extended family. And besides wearing them T-shirts, every one of them families have got on a backpack, strapped to their back, so that they could carry around lots of stupid shit. And the reason they need to carry their stupid shit strapped to their backs is because their hands must remain free at all times to hold food. And to get that food up to the mouth where it gets shoveled in with all the rest of the disgusting shit they ate that day. And another reason for the backpacks is these people are going to buy even more stupid shit. They haven’t got enough stupid shit at home, they just had a stupid shit sale and they are going to buy more.They are going to go out in the parking lot and stuff this stuff into their big fat ugly oversized SUV, that’s got plenty of room in it for stupid shit and lots of room left over for these big fat ugly motherfuckers to get them home. Stopping of course for jelly roll and fried dough.
These people. These people are efficient professional compulsive consumers. They think of that as their national pride. It’s their civic duty. Consumption. It’s the new national pasttime. Fuck baseball, it’s consumption. The only true lasting American value that’s left. Buying things. People spending money they don’t have on things they don’t need. Money they don’t have on things they don’t need. So they can max out their credit cards and spend the rest of their lives paying 18% on something that only costs 12.50. And they didn’t like it when they got it home, anyway. Not too bright, folks, not too fucking bright.
But if you talk to one of them about this, if you isolate one of them, you sit him down, rationally, you talk to him about the low IQ’s and the dumb behaviour and the bad decisions, right away they start talking about education. That’s the big answer to everything. Education. They say we need more money for education, we need more books, more teachers, more classrooms, more schools, we need more testing for the kids. You say to one of them: well, you know, we’ve tried all of that and the kids still can’t pass the tests. Ah don’t you worry about that, we’re going to lower the passing grades. And that’s what they do in a lot of these schools, they lower the passing grades, so more kids can pass. More kids pass, the school looks good, everybody is happy, the IQ of the country slips another two or three points and pretty soon all you need to get into college is a fucking pencil. Got a pencil, get the fuck in there, it’s physics. Then everyone wonders why 17 other countries graduate more scientists than we do. Education! Politicians know that word. They use it on you. Politicians have traditionally hidden behind three things: the Flag, the Bible and Children. No child left behind! No child left behind! Oh really? It wasn’t long ago that you were talking about giving kids a head start. Head start? Left behind? Someone’s losing fucking ground here.
But there’s a reason. There’s a reason for this. There’s a reason education sucks and it’s the same reason why it will never ever ever ever be fixed. It’s never going to get any better, don’t look for it. Be happy with what you got. Because the owners of this country don’t want that. I’m talking about the real owners now. The big wealthy business interests that control things and make all the important decisions.
Forget the politicians. They are irrelevant. The politicians are put there to give you the idea that you have freedom of choice. You don’t. You have no choice. You have owners. They own you. They own everything. They own all the important land. They own, and control the corporations. They’ve long since bought, and paid for the Senate, the Congress, the state houses, the city halls, they got the judges in their back pockets and they own all the big media companies, so they control just about all of the news and information you get to hear. They’ve got you by the balls. They spend billions of dollars every year lobbying. Lobbying, to get what they want. Well, we know what they want. They want more for themselves and less for everybody else, but I’ll tell you what they don’t want. They don’t want a population of citizens capable of critical thinking. They don’t want well-informed, well-educated people capable of critical thinking. They’re not interested in that. That doesn’t help them. That’s against their interests. That’s right. They don’t want people who are smart enough to sit around a kitchen table and think about how badly they’re getting fucked by a system that threw them overboard 30 fucking years ago. They don’t want that. You know what they want? They want obedient workers . Obedient workers, people who are just smart enough to run the machines and do the paperwork. And just dumb enough to passively accept all these increasingly shittier jobs with the lower pay, the longer hours, the reduced benefits, the end of overtime and the vanishing pension that disappears the minute you go to collect it, and now they’re coming for your Social Security money. They want your fucking retirement money. They want it back so they can give it to their criminal friends on Wall Street, and you know something? They’ll get it. They’ll get it all from you sooner or later, because they own this fucking place. It’s a big club and you aren’t in it. You and I are not in The Big Club. By the way, it’s the same big club they use to beat you over the head with all day long when they tell you what to believe. All day long beating you over the head with their media telling you what to believe, what to think and what to buy. The table is tilted, folks. The game is rigged and nobody seems to notice. Nobody seems to care. Good honest hard-working people – white collar, blue collar – it doesn’t matter what colour shirt you have on – good honest hard-working people continue – these are people of modest means – continue to elect these rich cocksuckers who don’t give a fuck about them. They don’t give a fuck about you. They don’t give a fuck about you. They don’t care about you at all. At all. At all. And nobody seems to notice. Nobody seems to care. That’s what the owners count on. The fact that Americans will probably remain willfully ignorant of the big red, white and blue dick that’s being jammed up their assholes every day, because the owners of this country know the truth. It’s called the American Dream because you have to be asleep to believe it.
But say what you want about America, folks. You can say what you want about Americans, you can call them smart, dumb, ignorant, innocent, naive, gullible, easily mislead, whatever you want, you’re going to have to deal with them, because you’re in the television business now. You’ve got the All-Suicide Channel on cable TV. You need these people as viewers. You need people looking in. You have got to worry about your ratings, you are going to have to be thinking about sweeps months. Most folks know what sweeps months are, now those are the more important months of the year, when they put on all of their biggest attractions, their hottest stars, trying to pump the ratings up a little bit, try to get the lower stations to adjust their advertising rates. You are going to have to compete with the mentality of network television. And I think, on an All-Suicide Channel, during sweeps months, you are going to have to go with mass suicides. Big public events where hundreds of people kill themselves all at the same time, right on live TV. I’ve been wrestling with the way to do this. I’ve been trying to figure this out, now this is the truth. I swear, I’ve been trying to figure this part of it out for six months now, and I only recently have and I’m going to tell you about it. Now, we’re going to have to get lots and lots of people to kill themselves on demand. How are we going to do this? Asked that question. How are we going to get large numbers of people to commit suicide at a time and place of our choosing? And I mean *large* numbers, because don’t forget besides sweeps, we’re going to be have to be thinking about twenty four hour a day programming. So to make this work, we need organization, we need assistance. Can’t just sit around the studio all day long and wait for people to drop by and commit suicide. What we have to do is build up a large pool of hopeless people. Suicide volunteers, people with no hope, people whom society has given up on, fate has given up on or who have given up on themselves.
Rock bottom, dead-end, totally fucked up people with no hope and no reason to live. Now we’ve got our share of them, folks. Think of it as a pyramid. That will give you a visual fix on it. Think of it as a pyramid, the Pyramid of the Hopeless. We’re going to populate, we’re going to create this pool, like I say, to send volunteers over to the Suicide Channel. We are going to start building this pyramid in the very base, naturally. And the bottom layer is going to be homeless people. God knows, we’ve got plenty of them. Nobody gives a fuck about them, nobody has got a plan, nobody has got any money, nobody has got a program, nobody gives a fuck about homeless people. We don’t know how many we have even. We know 500 000 of them are veterans because we’re so good to the veterans in this country and we know about 1 400 000 of them are children. So we’ve got a million and a half children. And God knows how many more we’ve got. Totally fucking hopeless – [fart sound] – in the pyramid they go!
Now the next group we’re going to put in here, are the people in prison with these long sentences they’ve been given. Many of them deserved, I’ll grant you that, I’m sure half the people in prison are in there for things they really did. That’s not a bad average, one out of two. But, nobody gives a shit about these people, nobody is going to hire them if they do get out. They are never going to get out, rehabilitation doesn’t work and the judges give them these fucking draconian sentences 40-50-60-70-80-90-100-year-sentences, life-term, double-life. One guy, about a month ago, was given three consecutive life-terms plus two death penalties. How the fuck do you serve that? Even David Copperfield can’t do that shit. In order to do that, you would have to be a Hindu. Then you’ve got the people on death row, they aren’t going anywere. [fart sound] – In the fucking pyramid they go!
Now the next layer, this group is self-selected. And a bit controversial to some years, I guess. These are these people who claim to be depressed. Okay? Apparently in this land of plenty, this richest nation in the history of world, we’re so proud of saying that, some supermarkets have a 100 000 items in them, we have 90 000 000 Americans claiming to be depressed. And some of them take medicine for it. Sometimes medicine makes one of them commit suicide and that depresses the shit out of the rest of them. Then you have these people who only think they’re depressed. They think they’re depressed because they saw the commercial on TV and the doctor looked like a good guy, the music sounded kind of peppy, and what the fuck, these pills will probably pick me right up. Totally fucking hopeless mindset – [fart sound] – in the fucking pyramid!
Up at the very top we’re going to put the people who are truly sick. The terminally ill, unfortunately no hope for a lot of them, hundreds of thousands of them. There’s no cure for what they have. There’s no cure because nobody is looking for one, there isn’t enough people sick with it so they haven’t got enough money for the fucking cure. Then there’s people for whom there’s a cure but they haven’t got the money for it. There are the other ones for whom there’s a cure they are too far gone. There are the others ones for whom there’s a cure but there’s no social means to get to it. So these people aren’t going anywhere. They should be allowed to commit suicide. Boom, in the fucking pyramid they go!
Now, think of what you’ve got here, folks. Think of yourself as the execute vice president of programming at the All-Suicide Channel. Think of what you have to work with in the Pyramid of the Hopeless. You have homeless, imprisoned, condemned, depressed and terminally ill people, and I’m going to bet you anything, in this depraved culture of ours, I’ll bet you anything, with the reality show mentality we have, on the All-Suicide Channel, *you could* get five hundred of these hopeless people to hold hands and jump into the Grand Canyon. I’ll fucking bet you. I’ll fucking bet you, you can get that done in this country right this now. I’ll bet you. For money, for money, for money. You have got to give them something. Oh shit, they’re Americans, they’re for sale, give them a little something. Americans will do anything, but you’ll have to give them a toaster, don’t you? Give them a little prize of some kind. Everyone wants a gizmo, give them a gizmo. Give them a cell-phone, give them a laptop. Give them a cell-phone that takes a picture of a laptop. Give them a laptop that takes a picture of the cellphone. Give them one of those three-wheeled vehicles. Give them an all-terrain vehicle. Give them riding lawn-mowers. Give them a snow-blower. Give them an out-door barbeque or a jet-ski. Give them one of those things they buy for themselves when they try to take their minds off of how badly they are getting fucked by the system. I know what you do, just before these people jump, you give them a hat with a camera in it. And you tell them it’s jump-cam. Tell them you’ll send the video home to the family. T-shirt! Who doesn’t want a T-shirt? Everybody does, give them a nice T-shirt. I committed suicide and all I got was this stupid T-shirt.
If you want to really raise the profile of this promotion, get some of those evangelical Christians to volunteer for it and you can call it: Jump For Jesus. Jump For Jesus. They would bite, they would go for it. Hey, you have got to be fair, got to be fair about these Christians. They come in for a lot of abuse these days. You do have to be fair, all the Christian really wants out of life, is to die and go see Jesus. Give them a helping hand. Do the Christian thing. Tell them it’s a shortcut to Heaven. Mention the word martyr, works on Muslims, works on the Catholics, it might work with these folks. You never know. Hey, I know, give them a little encouragement: “Go on, you fanatical fuck, his down there. His down there. His down there. His at the bottom of the canyon. Look for the man with the glowing head.“ Oh you’re going to have a lot of fun with a channel like that.
But you know what, folks, maybe you don’t want to be on cable. Maybe you don’t want to be on cable – it’s a limited audience. You might want to widen out and get more people looking and you’re going to have to go to the broadcast networks. One of the big broadcast networks. And I don’t know about you but when I think about suicide and broadcast network televison, I’m thinking FOX. If the people at FOX aren’t sitting around having meetings on an idea like this, they aren’t doing their god damn jobs over there. You put this thing on television and put it on FOX. And if you do, get Budweiser to sponsor it. Budweiser and a whole bunch of car companies. So people would be thinking about drinking and driving at the same time. Isn’t that fun? Isn’t it fun to watch the commercials in between the sporting events on American Television? Drink this! Drive that! Fuck you! They don’t care. They don’t give a shit about you. And then every now and then they qualify the whole message: „Drink responsibly!“
[long fart sound]
So you put this thing on FOX, and if you do, or any broadcast network, you’re going to have to bring in that younger audience. Everybody knows that. That’s what the advertisers are looking for, these 18-24-year-olds. You’re going to have to get young people interested in this. You know how you get young people interested in suicide? You don’t call it ’suicide’. You call it ’Extreme Living’! They would go for it. Listen, young people are attracted to suicide in the first place. Did you know suicide is the third leading cause of death between 15 and 24? It’s third. Ninth in the general population. That will give you an idea on how popular this after-school activity has become among our teenage folks. Especially these young boys, these adolescent males. A lot of them, you know. A lot of them.
They kill themselves while jerking off. They don’t mean to, it just happens. You know about that? Some of you know, I can tell. Lot of people don’t know about it, lot of people have never heard about it, it’s just one of those things Americans can’t handle. We cannot handle that, we don’t talk about that, it’s not on Larry King Live, it isn’t on Barbara Walters, I don’t see it in People magazine. But it’s out there, folks, it’s out there. And it’s extremely common. You just ask any teenage boy you know who trusts you. Ask him what he knows about or what he’s heard about cutting off your air supply just at the moment you’re about to have a sexual release. He’ll tell you an interesting story or two. The kids call it scarfing, because some of them use scarves to do it. Or scre the kids, just get on the Internet, do it yourself. Google in the words: ’Auto Erotic Aesphyxia’. It’s the practise of cutting off the oxygen to the brain at the last moment during masturbation in order to heighten the orgasm. And when I say common, a thousand kids a year die this kind of way. Okay? A thousand of them die. So think how many of them are trying to pull this off, if you pardon a little pun I’ve thrown in there. Just to lighten the mood. But here’s the way it works. Apparently, I never tried it, it sounded risky to me… Well, jerking off is all I need, you know what I mean, folks? I’m not trying to double my money, fuck that shit. I just jerk off, wipe off my chest, get up and go to work. Nothing fancy. Nothing fancy at our house, we’re simple folk. But here’s the way it’s *supposed* to work and this is why it’s such a big attraction in the first place. Apparently it is true, medically, physiologially speaking, that if you can cut off your air supply, the oxygen to your brain, just at the moment you’re about to have an orgasm, the orgasm is about, I don’t know, let’s say 500 times better, something like that. It’s incredibly intense. So what you’ve got to do is step on a chair or a bucket or some kind of thing. You put a rope around your neck and you start jerking off.
[vigorous imitative masturbation movements]
And while you’re pulling your pud, while you’re pulling your pud, you’ll have to arrange to almost strangle yourself just before you have an orgasm. And by the way, while all this activity is going on, you have to maintain a hard-on. Which isn’t easy, because you might just happen to be ready to buy the farm, so you better be fantasizing about someone you really like or some thing you really like, I don’t know what it might be, maybe you like to get fucked in the ass by the game warden, who knows, I’m not here to judge, we’re all different to each’s own.
So let’s recap. Stand on a chair, rope around your neck, Peter in your hand. Now you have to time it just right, so that just before you come, you almost die. And sometimes you miscalculate. You don’t know if you’re coming or going.
And the parents of these kids are too embarrassed to tell the police, so they put the kids dick away and say he had poor grades. His girlfriend left him. Oh, wow, no wonder, lady, look at his freaking hobbies. Then they blame it on heavy metal. I don’t know if you remember that, but from that old incident, some years back, Judas Priest, one of the head-banging bands, somebody played a song, and after that they killed themselves, so they blame suicide on heavy metal. If it’s murder, they tend to blame rap these days. But, it’s never the parents. Ever notice that? Parents, apparently, play no part in the development and outcomes of these kids. Parents. They can raise a kid apparently 11-12-13-14-15 years if he turns out fucked up, well they had nothing to do with that. It’s because of the boys that the kid hangs around with in the parking lot.
Parents have got to be among the most full of shit people in the world. They always have been. Top to bottom, front to back. In fairness, it comes with the job. If you want to be a parent, you have to be full of shit, at least half the time. Look at it this way, they have it both ways, if the kid turns out to be a loser, they had nothing to do with that, but, boy, if he’s a winner, got a scholarship or something like that, they’re the first ones out there raising their hands trying to get all the credit. It’s a nice state of mind if you can talk yourself into believing it.
But these are the kind of things I think about when I sitting at home alone, during an electrical strorm, waiting for the parole officer to give me a call. And these ideas, these ideas come floating into my head. Just floating right in, unbidden. I’m not asking for these things. I’m a vessel. I’m a mere vessel. In come these thoughts. And some of them are a little off-beat. I’m goint to grant you that.
I was thinking about these younger women, who got buried today. Did you ever think about them? *Probably not*. But I was thinking about these younger women who died three or four days ago, got buried today. And some of them had a bad heart, some of them a bad kidney, but a lot of them had perfectly good pussies. Good pussies, nice tits, reasonably tight assholes, going to waste! In the ground! It just seems a shame to me, that some fine young pussy should be rotting away six feet under. Because you’d think, you *would think*, in this era, that if you can donate a heart to someone who needs one, there ought to be a way to recycle some of these pussies. And give them to people who need them. Some old guy living up in the mountains. Wow… Holy shit, look at this fucking thing, this is great! Thank you very much, sir, thank you, I appreciate it, thank you, God bless you, you’re doing God’s work, I hope you know that. Hey this is better than Publisher’s Clearing House. Listen here, buddy, you haven’t got a red-headed one of these, by any chance? Nah, I didn’t think so, never did run into one of those myself. Thank you very much. Now listen, this is the real thing, isn’t it? This isn’t one of them storeboard pussies from your old bookstore? Huh, what’s that? Oh, okay. Hold on for just a second.
[takes a hard sniff and growls]
Jesus Christ on the cracker, that’s the real fucking thing. I recognise that son of a bitch anywhere. That straightened out my nose hairs. I better get this sucker home and get it in the refrigerator as quick as I can.
To Save A Pussy Foundation. Give the gift that keeps on giving. Fuck the whales. Save the pussies. But you wouldn’t want to save all of them. Not all of them. Some of them are worn out. You wouldn’t want one of those big old rubbery things, that isn’t no good. What you want is, you want yourself something nice and tight but flexible, maybe you’d have an age limit. Or a mileage check. You figure out the average length of the average dick, the average number of thurst per event, the average number of events per life time, you’ve got that lady’s mileage. And you women, I don’t want you to think we’re going to leave you without fun, we’re going to get you a nice set of cock and balls, okay? Will get you something nice, just after rigor mortis has set in. Tell the truth ladies, wouldn’t you like a nice set of cock and balls without all the bullshit that comes with them? Fucking A. We’ll get you something nice, you’ll keep it on the night stand. It’s real easy to find in the dark. And if your mother comes over, put a hat on it. Well somebody has got to think of these things and apparently I’ve been appointed. I was dancing with a woman and she told me she a had a yeast infection. I said, well bake me a fucking loaf of bread. A couple of corn muffins, a jelly donor, I don’t give a shit, I’m always on the market for quality baked goods. You couldn’t squeeze a birthday cake out of that by any chance, now could you? No I didn’t think so, honey, no pressure, no pressure at all. Why don’t you just turn over and get me a nice pineapple upside down cake? And a dozen oatmeal cookies. Skip the raisins. It’s nay on the raisins, aye?
I think it’s certainly apparent by now that one of the things I enjoy in life is excess. I like things that are excessive. I like excessive behavior, excessive language, excessive violence. It’s fun. It’s interesting. It’s exciting. I like it when nature is excessive. That’s why I like natural disasters. All these natural disasters that’ve been going on, I fucking love them. I can’t get enough of them. Ah, when nature’s going crazy, throwing things around, scaring people and destroying property, I’m a happy fucking guy. I’m a happy fucking guy. I look at it this way… For centuries now, man has done everything he can to destroy, defile, and interfere with nature: clear-cutting forests, strip-mining mountains, poisoning the atmosphere, over-fishing the oceans, polluting the rivers and lakes, destroying wetlands and aquifers, so when nature strikes back, and smacks me in the head and kicks me in the nuts, I enjoy that. I have absolutely no sympathy for human beings whatsoever. None. And no matter what kind of problem humans are facing, whether it’s natural or man-made, I always hope it gets worse. Don’t you? Don’t you? Don’t you have a part of you, a part of you that secretly hopes everything gets worse? When you see a big fire on TV, don’t you hope it spreads? Don’t you hope it gets completely out of control and burns down six counties? You don’t root for the firemen do you? I mean I don’t want them to get hurt or nothing, but I don’t want them to put out my fire. That’s my fire – that’s nature showing off and having fun. I like fires. You know something else I like? Those spring floods in the Midwest! Aren’t they great? Like clockwork, spring floods in the Midwest. Now I’m starting to notice, I’m starting to catch on, that every year it’s the same story. Another flood, in the same place, with the same people, on the same river – SAME FUCKING PEOPLE! And these people do not move, they will not fucking move! They repaint, put down new carpeting and wallpaper and they move right back into the same fucking house on the flood plain, next to the river, and then they wonder why grandma’s floating downstream with the parakeet on her head! Fourth time, again, fourth fucking time. There’s no learning curve with these people. It’s very hard to feel sorry for them. Every year – same people, same rowboats! Out there paddling around, rescuing a chicken. What the fuck kind of a life is that? Well our kids love it here… Oh really, what do they got, gills? And while they’re showing all that action on the screen, the announcer’s saying to me: “It’s been raining steadily for three months now, the ground can’t any more water, the river is cresting higher than it has it two centuries, the levees have washed away…“ And I just hope it keeps raining and raining and raining and raining and raining and raining and raining and raining and raining and raining and raining and raining and raining, and it rains steadily for five years, and then after that, for ten years it’s cloudy. With occasional showers. And the river never returns to its natural banks. It becomes a completely new river, and the borders of three states have to be changed, and all the maps and atlases have to be redrawn and reprinted, and no one’s couch ever completely dries out. For years and years, every time they sit down there’s always that little “Squish…“ “Dan, Linda, come on in you guys, have a seat” – “Squish!” “Squish!” I like that. I’m an interesting guy.
I always hope that no matter how small the original problem is, it’s gonna grow into bigger and bigger proportions and get completely out of control, and I’ll give you a concrete example. Let’s say a water main breaks in downtown Los Angeles and it floods an electrical substation, knocking out all the traffic lights and tying up the entire city and emergency vehicles can’t get through. And at the same time, one of those month-long global warming heat waves comes along, but there’s no air-conditioning, there’s no water for sanitation, so cholera, smallpox and dysentery break out and thousands of people start dying in the streets. But before they die, parasites eat their brains, and they go completely fucking crazy, and they storm the hospital, but the hospital can’t handle all the casualties, so these people rape all the nurses and set the hospital on fire. And the flames drive them even crazier, so they start stabbing social workers and garbage men. And a big wind comes along, and the entire city goes up in flames. And the people who are still healthy, they get mad at the sick people, and they start crucifying them, nailing them to crosses, trying on their underwear, shit like that. Then everybody smokes crack and PCP, and they march on city hall, where they burn the mayor at the stake, they strangle his wife and take turns sodomizing the statue of Larry Flint.

And at this point it looks like pretty soon things are going to start to get out of control.

So everyone panics and tries to leave the city at the same time, and they trample each other to death in the streets by the thousands and wild dogs eat their corpses. And the wild dogs chase the rest of the people down the highway and one by one the dogs pick off the old fucks and the slow people, because they’re in the fast lane where they don’t belong. Get the fuck out of the fast lane if you’re an old fuck, if you’re a slow fuck, get over on the right, get over on the right. And the lucky ones, the lucky people who manage to make it all the way to the outside of town, they discover when they get there, that big sparks from the city have lit the suburbs on fire. And the suburbs burn uncontrollably. And thousands of identical homes have identical fires with identical smoke, killing all the identical soccer mums and their identical kids named Jason and Jennifer. And now, the fire spreads to the farmlands and the farmlands burn intensely, at 425 degrees, creating millions of baked potatoes. As the farmlands burn, thousands of barns and farmhouses begin to explode from all the hidden methamphetamine labs. And the meth chemicals run downhill into the rivers and streams, where wild animals drink the water and get completely geeked on speed. So bears and wolves amped up on crack start roaming the countryside looking for people to eat, even though they’re not really hungry.

And the fire spreads to the forests and the forests burn furiously. And hundreds of elves and trolls and fairies come running out of the woods screaming, “Bambie is dead! Bambie is dead!”
And he is, he is, finally that fucking little cunt, Bambie is dead. Dead.
Now hundreds of regional fires come together into one huge interstate inferno. And all 12 of the Western United States are burning out of control, except Utah where the Mormons don’t allow fires. And the fire spreads across the Great Plains, toasting the wheat and cooking the cattle, producing hamburgers, actually. Then it leaps to Mississippi, and races through the south, blowing up stills, interrupting lynchings and killing millions of inbred people. And then it turns north-east and it heads to Washington DC, where George Bush can’t decide if it’s an emergency or not. He can’t decide because Dick Cheney is in prison. So, instead he takes a nap, he puts his empty fucking brainless head down on the little pillow that his mother gave him at Christmas time, and he takes a nap. So the fire moves to Philadelphia, but it’s a weekend, and Philadelphia’s closed on the weekends. So the fire moves to New York City and the people in New York tell the fire to go fuck itself. And it does, so instead it burns down Long Island and Connecticut, killing all the rich white assholes and completely destroying their evil faggoty golf courses. And while all this is going on, Canada burns to the ground, but nobody notices.
And now the entire North American continent is on fire, producing a huge thermal updraft, and creating an inseminary cyclonic macrosystem that forms a hemispheric mega-storm, breaking down the molecular structure of the atmosphere and actually changing the laws of nature. Fire and water combine, burning clouds of flaming rain fall upward, gamma rays and solar winds ignite the ionosphere, creating huge clouds of ionized plasma, bolts of lighting twenty million miles long begin shooting out of the north pole, and the sky fills up with *green* shit. And then suddenly, the entire fabric of space-time splits in two, a huge crack in the universe opens. And all the dead people from the past begin falling through. Babe Ruth, Groucho Marks, Davy Crocket, Tiny Tim, Porky Pig, Hitler, Janis Joplin, Allan Langer, my uncle Dave, your uncle Dave, everybody’s uncle Dave, an endless stream of dead uncle Daves falling through the crack.
And all the dead Uncle Daves gather around a heavenly kitchen table, they light up cigarettes and begin to talk. They talk about they never got a break, how their parents didn’t love them and their children were ungrateful. They talk about how their government screwed them out of money and they just missed out on a big job. They say the Jews own everything and the blacks get special treatment. And all the hatred and bitterness drips out of these people, and forms a big pool of liquid hate. And the pool of liquid hate begins to spin, round and round it spins, faster and faster, and the faster it spins the bigger it gets, faster and faster, bigger and bigger, until the whirling pool of hate is bigger than the entire universe. And then suddenly it *explodes* into trillions of tiny stars, and every star has a trillion planets, and every planet has a trillion uncle Daves. And all the uncle Daves have good jobs, perfect eyesight and shoes that fit. They have great sex lives and free healthcare. They understand the Internet, their kids think they’re cool, and they all love their neighbours. And every week, without fail, uncle Dave wins the lottery, forever and ever until the end of time every single uncle Dave has a winning ticket. And uncle Dave is finally happy.
Now do you see why I like it when nature gets even with humans? Thanks for coming in here tonight! Thank you, see you later!

vicidial remove recordings older then 30 days

2012 July 25
Comments Off
Posted by shirker2006
find /var/spool/asterisk/monitorDONE/MP3 -type f -mtime +30 -exec rm {} \;

how to add php5 module to apache2 (SUSE )

2012 July 20
Comments Off
Posted by shirker2006

go to yast and install apache2, php5, php5 module for apache2

type :  httpd2 -M

vicibox-us:~ # httpd2 -M
Loaded Modules:
 core_module (static)
 mpm_prefork_module (static)
 http_module (static)
 so_module (static)
 actions_module (shared)
 alias_module (shared)
 auth_basic_module (shared)
 authn_file_module (shared)
 authz_host_module (shared)
 authz_groupfile_module (shared)
 authz_default_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 cgi_module (shared)
 dir_module (shared)
 env_module (shared)
 expires_module (shared)
 include_module (shared)
 log_config_module (shared)
 mime_module (shared)
 negotiation_module (shared)
 setenvif_module (shared)
 ssl_module (shared)
 userdir_module (shared)
Syntax OK

haha!! where is installed recently php5??
the trick will do that command:

vicibox-us:~ # a2enmod php5

Or edit /etc/sysconfig/apache2 and add it to the list of modules to be loaded.

Now:

 ......
 userdir_module (shared)
 php5_module (shared)
Syntax OK

http://forums.opensuse.org/english/get-technical-help-here/applications/387631-php5-modules-not-loading-apache.html

load data -> the used command is not allowed with this mysql version

2012 July 12
Comments Off
Posted by shirker2006

to solve this use

mysql -uroot -p –local-infile=1

How to Setup a Software RAID on CentOS 5

2012 June 23
Comments Off
Posted by shirker2006

http://wiki.centos.org/HowTos/SoftwareRAIDonCentOS5
This article addresses the setting up of a software (mdraid) RAID1 at install time on systems without a true hardware RAID* controller. This implies controllers that expose the raw block devices directly to the operating system. It is also assumed that the devices involved are /dev/sda and /dev/sdb for the first two SATA or SCSI drives. Replace /dev/sda and /dev/sdb with /dev/hda and /dev/hdb (or possibly /dev/hdc for a secondary master) respectively for the first two parallel ATA drives. Adjust drive designations as required for other configurations. Be very careful to adjust commands for your situation and not simply blindly follow the procedure.

Booting will only work with /boot on non-RAID or RAID1 partitions. RAID0, RAID5 or other RAID types will not work for /boot and RAID0 (striping with no redundancy) is not recommended for critical partitions. With the /boot constraints satisfied, the root and other partitions may be RAID5 or another type; however, these options are not covered in this example.**

<img title="” src=”http://wiki.centos.org/wiki/modern-CentOS/img/attention.png” alt=”" width=”15″ height=”15″ /> The actions described in this write-up can damage an existing filesystem. Please experiment first on a test box and then only proceed after creating current & proven viable backups. Never blindly copy/paste commands, particularly as root, without a thorough understanding of their effects.

The “dd” commands and the installation procedure described below will destroy all information on the disks. If you have data on the drives that you need access to, please backup the drives first.

Section One

  1. Disable any fake RAID in the motherboard or RAID controller BIOS so that it acts as a normal controller – usually either ATA or SATA, possibly SCSI. It may be necessary to overwrite the partition tables if fake raid has previously been used on the disks. Do not load a RAID driver. The following commands may be performed on the 2nd virtual console (Ctrl-Alt-F2) during a graphical install before partitioning, or booted in rescue mode from installation media, or from a LiveCD. The partition tables of the devices will be zeroed out and all contents of the drives lost!
    • dd if=/dev/zero of=/dev/sda bs=512 count=64
      dd if=/dev/zero of=/dev/sdb bs=512 count=64
  2. Begin graphical installation of CentOS. May need to use “boot: linux nodmraid” or Press [Tab] at the initial installation selection menu and add nodmraid to the boot commands.
  3. Customize partitions and remove all partitions, including LVMs, for a fresh start
  4. Create an ~100MB software RAID partition on sda and sdb for /boot
  5. Create a software RAID partition on sda and sdb for swap. This partition size is based on the amount of RAM and personal preferences. The example uses 1GB. This is going to be RAIDed swap.***
  6. Create a software RAID partition on sda and sdb for / and fill to maximum allowable size
  7. Click the RAID button, create a RAID device
  8. Pick the two 100MB partitions, mount point /boot, filesystem type ext3, RAID1 (default RAID device should be md0), click OK
  9. Click the RAID button, create a RAID device
  10. Pick the two 1GB partitions, filesystem type swap, RAID1 (default RAID device should be md1), click OK
  11. Click the RAID button, create a RAID device
  12. Pick the two large partitions, mount point /, filesystem type ext3, RAID1 (default RAID device should be md2), click OK
  13. Your partitions are complete. Your screen should look similar to this:
    • RAID Devices
      /dev/md0 ext3 [check mark] 100
      /dev/md1 swap [check mark] 1024
      /dev/md2 ext3 [check mark] [lots of GBs]

      Hard Drives

      /dev/sda
         /dev/sda1 /dev/md0 software RAID [no check mark] 100
         /dev/sda2 /dev/md1 software RAID [no check mark] 1024
         /dev/sda3 /dev/md2 software RAID [no check mark] [lots of GBs]
      /dev/sdb
         /dev/sdb1 /dev/md0 software RAID [no check mark] 100
         /dev/sdb2 /dev/md1 software RAID [no check mark] 1024
         /dev/sdb3 /dev/md2 software RAID [no check mark] [lots of GBs]
  14. Click next to go to the GRUB bootloader screen.
  15. It should default to installing GRUB to /dev/sda, click Next
  16. Continue installing CentOS, selecting desired packages
  17. Proceed to Section Two after CentOS is installed and the system has been rebooted. Do not update CentOS, do not do anything else!

Section Two

This will assure that both members of the RAID1 /boot are bootable. Repeat after a disk failure/replacement.

Method 1 – in GRUB at boot

Stop at the GRUB menu and enter the “c” option, which gives you the GRUB prompt. Then:

  • grub> root (hd1,0)
    grub> setup (hd1)
    grub> root (hd0,0)
    grub> setup (hd0)

Hit the ESC key to get back to the GRUB menu, and boot normally. Perform steps 1 and 5-8 in Method 2.

Method 2 – in GRUB on the running system

  1. Make sure you’re root.
  2. Input the command “/sbin/grub”, hit Enter
  3. Enter the following commands in the GRUB shell:
    • grub> device (hd0) /dev/sda
      grub> device (hd1) /dev/sdb
      grub> root (hd0,0)
      grub> setup (hd0)
      grub> root (hd1,0)
      grub> setup (hd1)
      grub> quit
  4. Cross your fingers. Type in “reboot”, hit Enter.
  5. Once you’re booted up, do a system update.
  6. Reboot if the kernel or glibc was updated.
  7. Check that you’re actually running the updated kernel, if any, by typing “uname -a”, hit Enter
  8. Done!

  • This guide is based on information provided by TimVerhoeven of #centos on irc.freenode.net as quoted in a CentOS Forum thread and extensively edited with feedback from Forum users and centos-docs.
  • The above procedure assumes a graphical installation. Creating RAID-1 devices in text mode can be done, but is quite tedious and exacting. You first need to create each RAID member partition on each disk and specify only one disk for each. If you don’t specify a unique disk (either sda OR sdb) for each partition, then Disk Druid seems to want to mess around with the layout when you create the RAID devices. At the stage of creating the RAID devices be sure to only select the desired RAID partitions for each device and deselect others as the RAID devices are created.
  • It should be possible to apply a similar approach to / on RAID1 without a /boot. Here’s a link to a Fedora guide using that approach that should be largely applicable. The Fedora article also contains very good instructions on recovery using mdadm.
  • Additional RAID articles on the Wiki include How to Convert a CentOS 5 System to RAID1 Using a Rescue Disk and How to install CentOS 5 on a software partitionable RAID1.
  • General articles on software RAID:
  • Nice Linux Journal article on Recovery of RAID and LVM2 Volumes.
  • * Some controllers claim to be hardware RAID but require drivers to function, similar to winmodems. These controllers are often called “fake RAID” or “fraid” and are usually better used on CentOS with the RAID function disabled. This external article addresses the issues in some detail.
  • ** For a general explanation of RAID see the Wikipedia article or google for some of the other excellent descriptions available. See the Deployment Guide section Redundant Array of Independent Disks (RAID) or CentOS 5 FAQ entry “How do I install a software RAID on CentOS 5?” for more Enterprise Linux 5 specific information.
  • *** An alternative approach that might give somewhat better performance and twice the swap area for equivalent partition sizes, at the expense of redundancy, would be to use two non-RAID swap partitions. This should perform somewhat like striped RAID0, but will still survive the failure of a single drive, albeit with half the available swap.
  • Alternative B: Use the rest of the space for a single additional RAID1, then create an LVM volume on /dev/md1, create /, swap, and optionally /home or other filesystems, as Logical Volumes in LVM. Skip the rest of Section 1.

This page created and maintained by PhilSchaffner. Other Wiki contributors with edit rights are invited to make corrections or additions. Other readers with comments can find contact information on my Wiki page.

How to mount LVM

2012 June 23
Comments Off
Posted by shirker2006

http://www.linux-sxs.org/storage/fedora2ubuntu.html

  • Submitted by: Kurt Wall
  • Update by:
  • Date Submitted: 10 Apr 2007
  • Document Version: 1.0
  • Last Updated: 02/02/2008 17:46:54

A while back, I started experimenting with Ubuntu after playing with Fedora. I decided to jump to Ubuntu and needed to move data from the Fedora-managed logical volume to Ubuntu. Here’s what I did.

  1. Boot Ubuntu.
  2. Install lvm2:
    $ sudo apt-get install lvm2
  3. Load the necessary module(s):
    $ sudo modprobe dm-mod
  4. Scan your system for LVM volumes and identify in the output the volume group name that has your Fedora volume (mine proved to be VolGroup00):
    $ sudo vgscan
  5. Activate the volume:
    $ sudo vgchange -ay VolGroup00
  6. Find the logical volume that has your Fedora root filesystem (mine proved to be LogVol00):
    $ sudo lvs
  7. Create a mount point for that volume:
    $ sudo mkdir /mnt/fcroot
  8. Mount it:
    $ sudo mount /dev/VolGroup00/LogVol00 /mnt/fcroot -o ro,user
  9. Copied my files.

rdate server setup centos

2012 June 20
Comments Off
Posted by shirker2006

http://www.articlesbase.com/networks-articles/public-rdate-server-3288423.html

rdate is a Linux command and the network time protocol for immediate date and time setup from another machine. The clocks are synchronized by entering rdate with the -s switch (command without switch just checks the time but does not set anything).

rdate is the older standard that in many cases is now replaced by ntp/ntpd. Unlike ntp, rdate sets the new time instantly and is more suitable in situations like initial setup. Abrupt change of the clock settings may cause problems for some software (ntp changes time gradually). However ntp may not be available in some systems and during some initial setups is actually desired to set the correct time as soon as possible.

Under Linux, rdate does not have its own network service and is supported by the standard time service instead. It uses port 37 and can work via TCP or UDP (with -u switch).

This is tutorial How to public RDate Server.

Public RDate server need two packages:  xinet & ntp

Step 1:
On CentOS execute command:

#yum install xinet ntp

Step 2:
Enable time-stream in xinet by modify File /etc/xinetd.d/time-stream using command

#vi /etc/xinetd.d/time-stream

Search and replace with:

disable = no

#only_from = localhost

Step 3:
Start two services with commands:

#service ntpd start

#service xinetd start

Note: The service is a daemon listening on port 37 (TCP & UDP) on iptables using command:

#iptables -I INPUT -p tcp –dport 37 -j ACCEPT
#iptables -I INPUT -p udp –dport 37 -j ACCEPT

And after that restart iptables service with command:

#service iptables restart

Using RDate command sync to date system

#rdate -s [ip address]

Replacing A Failed Hard Drive In A Software RAID1 Array

2012 June 14
Comments Off
Posted by shirker2006

http://www.howtoforge.com/replacing_hard_disks_in_a_raid1_array

Version 1.0
Author: Falko Timme <ft [at] falkotimme [dot] com>
Last edited 01/21/2007

This guide shows how to remove a failed hard drive from a Linux RAID1 array (software RAID), and how to add a new hard disk to the RAID1 array without losing data.

I do not issue any guarantee that this will work for you!

1 Preliminary Note

In this example I have two hard drives, /dev/sda and /dev/sdb, with the partitions /dev/sda1 and /dev/sda2 as well as /dev/sdb1 and /dev/sdb2.

/dev/sda1 and /dev/sdb1 make up the RAID1 array /dev/md0.

/dev/sda2 and /dev/sdb2 make up the RAID1 array /dev/md1.

/dev/sda1 + /dev/sdb1 = /dev/md0

/dev/sda2 + /dev/sdb2 = /dev/md1

/dev/sdb has failed, and we want to replace it.

2 How Do I Tell If A Hard Disk Has Failed?

If a disk has failed, you will probably find a lot of error messages in the log files, e.g. /var/log/messages or /var/log/syslog.

You can also run

cat /proc/mdstat

and instead of the string [UU] you will see [U_] if you have a degraded RAID1 array.

3 Removing The Failed Disk

To remove /dev/sdb, we will mark /dev/sdb1 and /dev/sdb2 as failed and remove them from their respective RAID arrays (/dev/md0 and /dev/md1).

First we mark /dev/sdb1 as failed:

mdadm –manage /dev/md0 –fail /dev/sdb1

The output of

cat /proc/mdstat

should look like this:

server1:~# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0] sdb1[2](F)
24418688 blocks [2/1] [U_]

md1 : active raid1 sda2[0] sdb2[1]
24418688 blocks [2/2] [UU]

unused devices: <none>

Then we remove /dev/sdb1 from /dev/md0:

mdadm –manage /dev/md0 –remove /dev/sdb1

The output should be like this:

server1:~# mdadm –manage /dev/md0 –remove /dev/sdb1
mdadm: hot removed /dev/sdb1

And

cat /proc/mdstat

should show this:

server1:~# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0]
24418688 blocks [2/1] [U_]

md1 : active raid1 sda2[0] sdb2[1]
24418688 blocks [2/2] [UU]

unused devices: <none>

Now we do the same steps again for /dev/sdb2 (which is part of /dev/md1):

mdadm –manage /dev/md1 –fail /dev/sdb2

cat /proc/mdstat

server1:~# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0]
24418688 blocks [2/1] [U_]

md1 : active raid1 sda2[0] sdb2[2](F)
24418688 blocks [2/1] [U_]

unused devices: <none>

mdadm –manage /dev/md1 –remove /dev/sdb2

server1:~# mdadm –manage /dev/md1 –remove /dev/sdb2
mdadm: hot removed /dev/sdb2

cat /proc/mdstat

server1:~# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0]
24418688 blocks [2/1] [U_]

md1 : active raid1 sda2[0]
24418688 blocks [2/1] [U_]

unused devices: <none>

Then power down the system:

shutdown -h now

and replace the old /dev/sdb hard drive with a new one (it must have at least the same size as the old one – if it’s only a few MB smaller than the old one then rebuilding the arrays will fail).

4 Adding The New Hard Disk

After you have changed the hard disk /dev/sdb, boot the system.

The first thing we must do now is to create the exact same partitioning as on /dev/sda. We can do this with one simple command:

sfdisk -d /dev/sda | sfdisk /dev/sdb

You can run

fdisk -l

to check if both hard drives have the same partitioning now.

Next we add /dev/sdb1 to /dev/md0 and /dev/sdb2 to /dev/md1:

mdadm –manage /dev/md0 –add /dev/sdb1

server1:~# mdadm –manage /dev/md0 –add /dev/sdb1
mdadm: re-added /dev/sdb1

mdadm –manage /dev/md1 –add /dev/sdb2

server1:~# mdadm –manage /dev/md1 –add /dev/sdb2
mdadm: re-added /dev/sdb2

Now both arays (/dev/md0 and /dev/md1) will be synchronized. Run

cat /proc/mdstat

to see when it’s finished.

During the synchronization the output will look like this:

server1:~# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0] sdb1[1]
24418688 blocks [2/1] [U_]
[=>...................]  recovery =  9.9% (2423168/24418688) finish=2.8min speed=127535K/sec

md1 : active raid1 sda2[0] sdb2[1]
24418688 blocks [2/1] [U_]
[=>...................]  recovery =  6.4% (1572096/24418688) finish=1.9min speed=196512K/sec

unused devices: <none>

When the synchronization is finished, the output will look like this:

server1:~# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0] sdb1[1]
24418688 blocks [2/2] [UU]

md1 : active raid1 sda2[0] sdb2[1]
24418688 blocks [2/2] [UU]

unused devices: <none>

That’s it, you have successfully replaced /dev/sdb!

deleting a dead links

2012 May 18
Comments Off
Posted by shirker2006
set -A _Array1 `ls -1 | xargs`
set -A _Array2 `ls -1L 2>/dev/null | xargs`

for file in ${_Array1[@]}
do
        _dead=0
        for link in ${_Array2[@]}
        do
                if [[ $file = $link ]]
                then
                        _dead=1
                        break;
                fi
        done
        if [[ $_dead -ne 1 ]]
        then
                echo $file is a dead link.
                #/bin/rm -f $file
        fi
done

Англо-русский словарь автомобильных терминов

2012 May 11
Comments Off
Posted by shirker2006

0..9

2 WAY O/D – автоматическое отключение повышенной передачи

4WD – 4 Wheel Drive – полный привод (обычно “подключаемый полный привод”, т.е. подключаемый и отключаемый вручную)

4А/Т – четырехскоростная автоматическая коробка передач

A [вверх]

A – ampere(s) – ампер

A/F (air fuel ratio) – состав топливно-воздушной смеси

A/T – автоматическая трансмиссия

A|W alloy wheels – легкосплавные диски

ABS – Anti-Blocking System – антиблокировочная система (тормозов)

ACCEL (accelerator) – педаль газа

ACL (air cleaner) – воздухоочиститель

ADJ – ADJUST – регулировка

AIR BAG – [надувная] подушка безопасности

air duct – воздуховод

air filter (air cleaner) – воздушный фильтр

air flow meter – датчик расхода воздуха
Read more…

SIP flood. “No matching peer found” . Protect asterisk with iptables

2012 May 9
Comments Off
Posted by shirker2006
#!/bin/bash

for i in `tail -200 /var/log/asterisk/messages | grep -v "for '192.168.18" | grep "No matching peer found" | awk '{print $11}' | uniq | tr -d \'`; do
     VAR=`/sbin/iptables -nvL | grep $i | awk '{print $8}'| uniq`;
     #echo $VAR;
     #echo $i;
        if [ "$VAR" = "$i" ];
            then
                echo "This IP:$i is already in blacklist"
        else
            /sbin/iptables -A INPUT -s $i -j DROP
            /sbin/iptables -A OUTPUT -s $i -p ip -j DROP
            /sbin/iptables -A OUTPUT -s $i -p udp -j DROP
            echo "IP $i has been blocked"
        fi
done

Replace “192.168.18″ to your local network IP
then add to crontab every 2-5 min

kernel: e1000e 0000:09:00.0: eth0: Reset adapter

2012 April 4
Comments Off
Posted by shirker2006
Apr  3 00:33:32 asterisk21 kernel: e1000e 0000:09:00.0: eth0: Reset adapter
Apr  3 00:33:34 asterisk21 kernel: e1000e: eth0 NIC Link is Up 100 Mbps Full Dup                                                            lex, Flow Control: Rx/Tx
Apr  3 00:33:34 asterisk21 kernel: e1000e 0000:09:00.0: eth0: 10/100 speed: disa                                                            bling TSO
Apr  3 00:38:14 asterisk21 kernel: e1000e 0000:09:00.0: eth0: Reset adapter
Apr  3 00:38:16 asterisk21 kernel: e1000e: eth0 NIC Link is Up 100 Mbps Full Dup

Solution:
“Please try booting the kernel with the pcie_aspm=off kernel parameter.”
from http://serverfault.com/questions/193114/linux-e1000e-intel-networking-driver-problems-galore-where-do-i-start

As well look here: http://www.webhostingtalk.com/archive/index.php/t-1098986.html

how to fix php-mcrypt for centos6 x64 (ERROR on phpmyadmin)

2012 March 21
Comments Off
Posted by shirker2006
rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/libmcrypt-2.5.8-9.el6.x86_64.rpm

rpm -ivh --nodeps http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-1.el6.x86_64.rpm
service httpd restart
php -v

vicidial dialplan for manual dialing with recording

2012 February 25
Comments Off
Posted by shirker2006
exten => _91NXXNXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log)
exten => _91NXXNXXXXXX,2,Set(__RECORDING=${EXTEN:1}-${STRFTIME(,,%s)})
exten => _91NXXNXXXXXX,n,Authenticate(/etc/asterisk/passwords)
exten => _91NXXNXXXXXX,n,MixMonitor(${RECORDING}.wav)
exten => _91NXXNXXXXXX,n,Set(CDR(userfield)=${RECORDING}.wav)
exten => _91NXXNXXXXXX,n,Set(CALLERID(num)=YUOR_CALLER_ID)
exten => _91NXXNXXXXXX,n,NOOP(${CALLERIDNUM})
exten => _91NXXNXXXXXX,n,Goto(from-trunk-sip-outbound,${EXTEN:1},1) ;go to ur dialplan
exten => _91NXXNXXXXXX,n,Hangup

if leads were loaded twice (duplicate numbers)

2012 February 2
Comments Off
Posted by shirker2006

to check

mysql>select phone_number from `asterisk.vicidial_list` GROUP by phone_number HAVING count(*) > 1 where list_id=’YOUR_LIST_ID’;

to fix

mysql>alter ignore table  `asterisk.vicidial_list`  add unique index(phone_number);

if cisco keeps rebooting with SYSTEM INIT: INSUFFICIENT MEMORY TO BOOT THE IMAGE!

2012 January 29
Comments Off
Posted by shirker2006

Its happening after unsuccessful upgrading of IOS. To downgrade to another image do:
if you are using “minicom”, during the boot press <Ctrl>+”A” then “F”

rommon 1 > IP_ADDRESS=192.168.18.2
rommon 2 > IP_SUBNET_MASK=255.255.255.0
rommon 3 > DEFAULT_GATEWAY=192.168.18.1
rommon 4 > TFTP_SERVER=192.168.18.21
rommon 5 > TFTP_FILE=c2600-ipbase-mz.123-8.T.bin
rommon 6 > TFTP_CHECKSUM=0
rommon 10 > set
PS1=rommon ! >
RANDOM_NUM=655578172
BSI=0
BOOT=c2600-advsecurityk9-mz.124-9.t1.bin,1;
ROM_PERSISTENT_UTC=1015087047
RET_2_RTS=
RET_2_RCALTS=
CRASHINFO=flash:crashinfo_20020301-000043
IP_ADDRESS=192.168.18.2
IP_SUBNET_MASK=255.255.255.0
DEFAULT_GATEWAY=192.168.18.1
TFTP_SERVER=192.168.18.21
TFTP_FILE=c2600-ipbase-mz.123-8.T.bin
TFTP_CHECKSUM=0
?=0

tftpdnld

confreg 0x2101
reset

List of requirements to run IOS 12.4T for 26XX :


AISK9-AESK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-adventerprisek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 33758.23 KB (34568420 bytes)
Minimum Memory: DRAM:256MB   Flash:48MB	

IPV-AESK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-adventerprisek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 33758.23 KB (34568420 bytes)
Minimum Memory: DRAM:256MB   Flash:48MB	

ADVANCED ENTERPRISE SERVICES
c2600-adventerprisek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 33758.23 KB (34568420 bytes)
Minimum Memory: DRAM:256MB   Flash:48MB	

SPSK9-AESK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-adventerprisek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 33758.23 KB (34568420 bytes)
Minimum Memory: DRAM:256MB   Flash:48MB	

INT VOICE/VIDEO, IPIPGW, TDMIP GW AES
c2600-adventerprisek9_ivs-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 34113.15 KB (34931856 bytes)
Minimum Memory: DRAM:256MB   Flash:64MB	

ADVANCED ENTERPRISE SERVICES WITH SNA SWITCH
c2600-adventerprisek9_sna-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 34415.07 KB (35241028 bytes)
Minimum Memory: DRAM:256MB   Flash:48MB	

ADVANCED IP SERVICES
c2600-advipservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 32371.20 KB (33148108 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

IPV-AISK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-advipservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 32371.20 KB (33148108 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

SPSK9-AISK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-advipservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 32371.20 KB (33148108 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

ADVANCED SECURITY
c2600-advsecurityk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 19173.92 KB (19634088 bytes)
Minimum Memory: DRAM:128MB   Flash:32MB	

ENTERPRISE BASE W/O CRYPTO
c2600-entbase-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 17096.08 KB (17506384 bytes)
Minimum Memory: DRAM:128MB   Flash:32MB	

ENTERPRISE BASE
c2600-entbasek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 18066.15 KB (18499728 bytes)
Minimum Memory: DRAM:128MB   Flash:32MB	

ENTERPRISE SERVICES W/O CRYPTO
c2600-entservices-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 28782.06 KB (29472824 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

IPV-ESK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-entservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 29668.86 KB (30380912 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

ENTERPRISE SERVICES
c2600-entservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 29668.86 KB (30380912 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

SPSK9-ESK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-entservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 29668.86 KB (30380912 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

IP BASE W/O CRYPTO
c2600-ipbase-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 14377.56 KB (14722612 bytes)
Minimum Memory: DRAM:128MB   Flash:32MB	

IP BASE
c2600-ipbasek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 15347.24 KB (15715564 bytes)
Minimum Memory: DRAM:128MB   Flash:32MB	

IP VOICE W/O CRYPTO
c2600-ipvoice-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 25488.95 KB (26100684 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

INT VOICE/VIDEO, IPIP GW, TDMIP GW
c2600-ipvoice_ivs-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 25836.84 KB (26456920 bytes)
Minimum Memory: DRAM:256MB   Flash:64MB	

IP VOICE
c2600-ipvoicek9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 26452.72 KB (27087580 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

SP SERVICES
c2600-spservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 28137.81 KB (28813112 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

IPV-SPSK9 FEAT SET FACTORY UPG FOR BUNDLES
c2600-spservicesk9-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 28137.81 KB (28813112 bytes)
Minimum Memory: DRAM:192MB   Flash:48MB	

TELCO FEATURE SET
c2600-telco-mz.124-15.T12.bin
Release Date: 25/JAN/2010
Size: 14107.83 KB (14446408 bytes)
Minimum Memory: DRAM:128MB   Flash:32MB

how to fix Could not execute: Duplicate entry ’3′ for key ‘PRIMARY’

2012 January 23
Comments Off
Posted by shirker2006

http://www.softwareprojects.com/resources/programming/t-how-to-fix-mysql-duplicate-entry-for-key-primary-o-1844.html

We encountered an interesting error on a client database this past few days, where MySQL was issuing random errors, complaining about:

Duplicate entry ’1′ for key ‘PRIMARY’

These errors were coming up on various tables at different times in the day, but the crazy thing is – the duplicate key error is on an auto-increment field!

That’s not normal.

When you have a table defined as

CREATE TABLE test (id int auto_increment, somevalue int, primary key (id));

There’s no way you can generate a duplicate key error on the ‘id’ field, unless you manually pass the value of the auto_increment id field (which we were not)

Running a mysqlcheck reported all tables are OK. We proceeded to issue OPTIMIZE TABLEstatements (this rebuilds indexes) as well as manually running REPAIR TABLE for each table, but nothing helped.

The table indexes were obviously corrupted in some way, although MySQL tools reported all is well…

How to fix this problem

The only way we could fix it, is by rebuilding the entire database from scratch.

Dropping all tables and reloading them from a backup.

Step 1

Create a backup of the database by issuing:


mysqldump 
-uUSER -pPASSWORD DBNAME > /tmp/my_backup.sql

Replace USER with your MySQL username, PASSWORD with your MySQL password and DBNAME with the databasename you are looking to repair.

Step 2

Drop and recreate the database


drop database DBNAME
;
create database DBNAME;

Step 3

Reload the import


mysql 
-uUSER -pPASSWORD DBNAME < /tmp/my_backup.sql

Easy Guide for Successful Vtiger Integration in VicidialNOW

2012 January 23
Comments Off
Posted by shirker2006

http://www.eflo.net/VICIDIALforum/viewtopic.php?p=43348&sid=2e2c74556d141deacbd4888610cf9872

Hi All,

I have been a part of this community for a few months now. There are few common configuration problems for new user after successful install. Among those one is integration of VTIGER. I did this integration for quite a few times without any problem. I decided to share my guide with others. If admins like this guide they may decide to make this sticky for others.

There are three things in this guide
1-For MySQL
2-Installation of Vtigercrm 5.0.4
3-Integration with VICIDIALNOW VERSION: 2.0.5-173

Let we take these steps one by one.

1-For MySQL

Code:
#mysql -u root -p   (it will ask for root password default is vicidialnow)
mysql>GRANT ALL on vtigercrm504.* TO vtiger@’%’ IDENTIFIED BY ‘vtuser’;
mysql>GRANT ALL on vtigercrm504.* TO vtiger@localhost IDENTIFIED BY ‘vtuser’;
mysql>create database vtigercrm504;
mysql>quit

2-Installation of Vtigercrm 5.0.4

Code:
#cd /var/www/html
#rm -r -f vtigercrm
#wget http://voxel.dl.sourceforge.net/sourceforge/vtigercrm/vtigercrm-5.0.4.tar.gz
#gunzip vtigercrm-5.0.4.tar.gz
#tar xvf vtigercrm-5.0.4.tar
#chmod -R 0777 vtigercrm
#cd vtigercrm

* in browser go to the following URL: http://ip-address/vtigercrm/index.php
* enter contact info and click the START button at the bottom of the screen
* in system configuration set the database host to: <ip-address>
* database user/pass: vtiger/vtuser
* database name: vtigercrm504
* change default admin(vtadmin) and standarduser(vtuser) passwords
* click to install vtiger, then follow the on-screen instructions

After successful install it will ask for login into vtiger crm, you can login to test if everything is fine. Password for admin to login is “vtadmin”, we have choosen this in aboive step.

Now we have to patch this new install of vtiger to work with VICIDIALNOW
Note: Make sure to execute these commands in vtigercrm folder

Code:
#wget http://www.eflo.net/files/Vtiger504_vicidial.patch
#patch -p1 < ./Vtiger504_vicidial.patch

After this goto admin interface for integration and user synchronization
Admin->System Settings

3-Integration with VICIDIALNOW

Code:
Enable Vtiger Integration:  1
Vtiger DB Server IP: <your ip>
Vtiger DB Name: vtigercrm504
Vtiger DB Login: vtiger
Vtiger DB Password: vtuser
Vtiger URL: <yout ip>/vtigercrm

Submit setting and click “Click here to Synchronize users with Vtiger”

This will synchronize all users with VTIGER

Note: After synchronization your VTIGER admin password is replaced wih your VICIDIALNOW admin password.

I hope this will help for all beginners like me Very Happy

Best regards,

LDAP + Samba + phpldapadmin on Centos 6

2012 January 20
Posted by shirker2006

Nice article about it - http://www.server-world.info/en/note?os=CentOS_6&p=ldap&f=1

OpenLDAP

[1] Install OpenLDAP

[root@dir ~]#

yum -y install openldap-servers openldap-clients

[root@dir ~]#

vi /etc/sysconfig/ldap
# line 16: uncomment and change

SLAPD_LDAPI=

yes

[root@dir ~]#

vi /etc/openldap/slapd.conf
# create new
pidfile     /var/run/openldap/slapd.pid
argsfile    /var/run/openldap/slapd.args

[root@dir ~]#

rm -rf /etc/openldap/slapd.d/*

[root@dir ~]#

slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d

config file testing succeeded

[root@dir ~]#

vi /etc/openldap/slapd.d/cn=config/olcDatabase\={0}config.ldif
# line 4: change

olcAccess:

{0}to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break

[root@dir ~]#

vi /etc/openldap/slapd.d/cn=config/olcDatabase\={1}monitor.ldif
# create new
dn: olcDatabase={1}monitor
objectClass: olcDatabaseConfig
olcDatabase: {1}monitor
olcAccess: {1}to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break
olcAddContentAcl: FALSE
olcLastMod: TRUE
olcMaxDerefDepth: 15
olcReadOnly: FALSE
olcMonitoring: FALSE
structuralObjectClass: olcDatabaseConfig
creatorsName: cn=config
modifiersName: cn=config

[root@dir ~]#

chown -R ldap. /etc/openldap/slapd.d

[root@dir ~]#

chmod -R 700 /etc/openldap/slapd.d

[root@dir ~]#

/etc/rc.d/init.d/slapd start

Starting slapd: [ OK ]
[root@dir ~]#

chkconfig slapd on
[2] Initial Configuration
[root@dir ~]#

ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/core.ldif

SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry “cn=core,cn=schema,cn=config”

[root@dir ~]#

ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif

SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry “cn=cosine,cn=schema,cn=config”

[root@dir ~]#

ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif

SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry “cn=nis,cn=schema,cn=config”

[root@dir ~]#

ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif

SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry “cn=inetorgperson,cn=schema,cn=config”

[root@dir ~]#

slappasswd
# generate password

New password:

# input any one

Re-enter new password:
{SSHA}xxxxxxxxxxxxxxxxxxxxxxxx

[root@dir ~]#

vi backend.ldif
# create new
# replace the section “dc=***,dc=***” to your own suffix
# replace the section “olcRootPW: ***” to your own password generated by slappasswd above
dn: cn=module,cn=config
objectClass: olcModuleList
cn: module
olcModulepath: /usr/lib64/openldap
olcModuleload: back_hdb

dn: olcDatabase=hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {2}hdb
olcSuffix: dc=server,dc=world
olcDbDirectory: /var/lib/ldap
olcRootDN: cn=admin,dc=server,dc=world
olcRootPW: {SSHA}xxxxxxxxxxxxxxxxxxxxxxxx
olcDbConfig: set_cachesize 0 2097152 0
olcDbConfig: set_lk_max_objects 1500
olcDbConfig: set_lk_max_locks 1500
olcDbConfig: set_lk_max_lockers 1500
olcDbIndex: objectClass eq
olcLastMod: TRUE
olcMonitoring: TRUE
olcDbCheckpoint: 512 30
olcAccess: to attrs=userPassword by dn="cn=admin,dc=server,dc=world" write by anonymous auth by self write by * none
olcAccess: to attrs=shadowLastChange by self write by * read
olcAccess: to dn.base="" by * read
olcAccess: to * by dn="cn=admin,dc=server,dc=world" write by * read

[root@dir ~]#

ldapadd -Y EXTERNAL -H ldapi:/// -f backend.ldif

SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry “cn=module,cn=config”

adding new entry “olcDatabase=hdb,cn=config”

[root@dir ~]#

vi frontend.ldif
# create new
# replace the section “dc=***,dc=***” to your own suffix
# replace the section “userPassword: ***” to your own password generated by slappasswd above
dn: dc=server,dc=world
objectClass: top
objectClass: dcObject
objectclass: organization
o: Server World
dc: Server

dn: cn=admin,dc=server,dc=world
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
userPassword: {SSHA}xxxxxxxxxxxxxxxxxxxxxxxx

dn: ou=people,dc=server,dc=world
objectClass: organizationalUnit
ou: people

dn: ou=groups,dc=server,dc=world
objectClass: organizationalUnit
ou: groups

[root@dir ~]#

ldapadd -x -D cn=admin,dc=server,dc=world -W -f frontend.ldif

Enter LDAP Password:

# password you set
adding new entry "dc=server,dc=world"

adding new entry "cn=admin,dc=server,dc=world"

adding new entry "ou=people,dc=server,dc=world"

adding new entry "ou=groups,dc=server,dc=world"
[3] Add Existing local Users to LDAP Directory

[root@dir ~]#

vi ldapuser.sh
# extract local users who have 500-999 digit UID
# replace “SUFFIX=***” to your own suffix
# this is an example
#!/bin/bash

SUFFIX='dc=server,dc=world'
LDIF='ldapuser.ldif'

echo -n > $LDIF
for line in `grep "x:[5-9][0-9][0-9]:" /etc/passwd | sed -e "s/ /%/g"`
do
   UID1=`echo $line | cut -d: -f1`
   NAME=`echo $line | cut -d: -f5 | cut -d, -f1`
   if [ ! "$NAME" ]
   then
      NAME=$UID1
   else
      NAME=`echo $NAME | sed -e "s/%/ /g"`
   fi
   SN=`echo $NAME | awk '{print $2}'`
   if [ ! "$SN" ]
   then
      SN=$NAME
   fi
   GIVEN=`echo $NAME | awk '{print $1}'`
   UID2=`echo $line | cut -d: -f3`
   GID=`echo $line | cut -d: -f4`
   PASS=`grep $UID1: /etc/shadow | cut -d: -f2`
   SHELL=`echo $line | cut -d: -f7`
   HOME=`echo $line | cut -d: -f6`
   EXPIRE=`passwd -S $UID1 | awk '{print $7}'`
   FLAG=`grep $UID1: /etc/shadow | cut -d: -f9`
   if [ ! "$FLAG" ]
   then
      FLAG="0"
   fi
   WARN=`passwd -S $UID1 | awk '{print $6}'`
   MIN=`passwd -S $UID1 | awk '{print $4}'`
   MAX=`passwd -S $UID1 | awk '{print $5}'`
   LAST=`grep $UID1: /etc/shadow | cut -d: -f3`

   echo "dn: uid=$UID1,ou=people,$SUFFIX" >> $LDIF
   echo "objectClass: inetOrgPerson" >> $LDIF
   echo "objectClass: posixAccount" >> $LDIF
   echo "objectClass: shadowAccount" >> $LDIF
   echo "uid: $UID1" >> $LDIF
   echo "sn: $SN" >> $LDIF
   echo "givenName: $GIVEN" >> $LDIF
   echo "cn: $NAME" >> $LDIF
   echo "displayName: $NAME" >> $LDIF
   echo "uidNumber: $UID2" >> $LDIF
   echo "gidNumber: $GID" >> $LDIF
   echo "userPassword: {crypt}$PASS" >> $LDIF
   echo "gecos: $NAME" >> $LDIF
   echo "loginShell: $SHELL" >> $LDIF
   echo "homeDirectory: $HOME" >> $LDIF
   echo "shadowExpire: $EXPIRE" >> $LDIF
   echo "shadowFlag: $FLAG" >> $LDIF
   echo "shadowWarning: $WARN" >> $LDIF
   echo "shadowMin: $MIN" >> $LDIF
   echo "shadowMax: $MAX" >> $LDIF
   echo "shadowLastChange: $LAST" >> $LDIF
   echo >> $LDIF
done

[root@dir ~]#

sh ldapuser.sh

[root@dir ~]#

ldapadd -x -D cn=admin,dc=server,dc=world -W -f ldapuser.ldif

Enter LDAP Password:

# LDAP admin password
adding new entry "uid=cent,ou=people,dc=server,dc=world"

adding new entry "uid=fedora,ou=people,dc=server,dc=world"

adding new entry "uid=ubuntu,ou=people,dc=server,dc=world"

adding new entry "uid=debian,ou=people,dc=server,dc=world"

adding new entry "uid=fermi,ou=people,dc=server,dc=world"
[4] Add existing local groups to LDAP directory.

[root@dir ~]#

vi ldapgroup.sh
# extract local groups who have 500-999 digit UID
# replace “SUFFIX=***” to your own suffix
# this is an example
#!/bin/bash

SUFFIX='dc=server,dc=world'
LDIF='ldapgroup.ldif'

echo -n > $LDIF
for line in `grep "x:[5-9][0-9][0-9]:" /etc/group`
do
   CN=`echo $line | cut -d: -f1`
   GID=`echo $line | cut -d: -f3`
   echo "dn: cn=$CN,ou=groups,$SUFFIX" >> $LDIF
   echo "objectClass: posixGroup" >> $LDIF
   echo "cn: $CN" >> $LDIF
   echo "gidNumber: $GID" >> $LDIF
   users=`echo $line | cut -d: -f4 | sed "s/,/ /g"`
   for user in ${users} ; do
      echo "memberUid: ${user}" >> $LDIF
   done
   echo >> $LDIF
done

[root@dir ~]#

sh ldapgroup.sh

[root@dir ~]#

ldapadd -x -D cn=admin,dc=server,dc=world -W -f ldapgroup.ldif

Enter LDAP Password:

# LDAP admin password
adding new entry "cn=cent,ou=groups,dc=server,dc=world"

adding new entry "cn=fedora,ou=groups,dc=server,dc=world"

adding new entry "cn=ubuntu,ou=groups,dc=server,dc=world"

adding new entry "cn=debian,ou=groups,dc=server,dc=world"

adding new entry "cn=fermi,ou=groups,dc=server,dc=world"
[5] If you’d like to delete User or Group in LDAP, Do as below.
[root@dir ~]#

ldapdelete -x -W -D ‘cn=admin,dc=server,dc=world’ “uid=cent,ou=people,dc=server,dc=world”

Enter LDAP Password:
[root@dir ~]#

ldapdelete -x -W -D ‘cn=admin,dc=server,dc=world’ “cn=cent,ou=groups,dc=server,dc=world”

Enter LDAP Password:

Installing and configuring Samba

yum -y install samba smbldap-tools
vim /etc/samba/smb.conf

dont forget to change domain name:

[global]
workgroup = SIMPLEX
netbios name = SIMPLEX
passdb backend = ldapsam:ldap://simplex.local
username map = /etc/samba/smbusers
security = user

passwd program = /usr/sbin/smbldap-passwd %u
passwd chat = *New*password* %n\n *Retype*new*password* %n\n *all*authentication*tokens*updated*
add user script = /usr/sbin/smbldap-useradd -m "%u"
ldap delete dn = Yes
delete user script = /usr/sbin/smbldap-userdel "%u"
add machine script = /usr/sbin/smbldap-useradd -w "%u"
add group script = /usr/sbin/smbldap-groupadd -p "%g"
delete group script = /usr/sbin/smbldap-groupdel "%g"
add user to group script = /usr/sbin/smbldap-groupmod -m "%u" "%g"
delete user from group script = /usr/sbin/smbldap-groupmod -x "%u" "%g"
set primary group script = /usr/sbin/smbldap-usermod -g "%g" "%u"

#add user script = /usr/sbin/useradd -m %u
#delete user script = /usr/sbin/userdel -r %u
#add group script = /usr/sbin/groupadd %g
#delete group script = /usr/sbin/groupdel %g
#add user to group script = /usr/sbin/usermod -G %g %u
#add machine script = \
# /usr/sbin/useradd -s /bin/false -d /dev/null \
# -g machines %u

# The following specifies the default logon script
# Per user logon scripts can be specified in the
# user account using pdbedit
logon script = scripts\logon.bat
# This sets the default profile path.
# Set per user paths with pdbedit
logon path = \\%L\Profiles\%U
logon drive = H:
logon home = \\%L\%U
domain logons = Yes
os level = 35
preferred master = Yes
domain master = Yes
ldap suffix = dc=simplex,dc=local
ldap machine suffix = ou=People
ldap user suffix = ou=People
ldap group suffix = ou=Group
ldap idmap suffix = ou=People
ldap admin dn = cn=admin
ldap ssl = no
ldap passwd sync = yes
idmap uid = 15000-20000
idmap gid = 15000-20000

# Other resource shares

[homes]
   comment = Home Directories
   browseable = no
   writable = yes
   valid users = %S

[netlogon]
   comment = Network Logon Service
   path = /etc/samba/netlogon
   guest ok = yes
   writable = no
   share modes = no

Run smbldap-tools configuration:

chmod +x /usr/share/doc/smbldap-tools-0.9.6/configure.pl
/usr/share/doc/smbldap-tools-0.9.6/configure.pl
[root@asterisk21 ~]# cat /etc/smbldap-tools/smbldap.conf | grep -v "#"

SID="S-1-5-21-1149901229-438850559-190516975"

sambaDomain="SIMPLEX"

slaveLDAP="192.168.18.21"

slavePort="389"

masterLDAP="192.168.18.21"

masterPort="389"

ldapTLS="0"

verify=""

cafile=""

clientcert=""

clientkey=""

suffix="dc=simplex,dc=local"

usersdn="ou=People,${suffix}"

computersdn="ou=People,${suffix}"

groupsdn="ou=Group,${suffix}"

idmapdn="ou=People,${suffix}"

sambaUnixIdPooldn="sambaDomainName=${sambaDomain},${suffix}"

scope="sub"

hash_encrypt="SSHA"

crypt_salt_format=""

userLoginShell="/bin/bash"

userHome="/home/%U"

userHomeDirectoryMode="700"

userGecos="System User"

defaultUserGid="513"

defaultComputerGid="515"

skeletonDir="/etc/skel"

defaultMaxPasswordAge="70"

userSmbHome="\\%L\%U"

userProfile="\\%L\Profiles\%U"

userHomeDrive="/home"

userScript="scripts\logon.bat"

mailDomain="simplex-bpo.com"

with_smbpasswd="0"
smbpasswd="/usr/bin/smbpasswd"

with_slappasswd="0"
slappasswd="/usr/sbin/slappasswd"

conf file should be look like that:

[root@asterisk21 ~]# cat /etc/smbldap-tools/smbldap.conf | grep -v "#"

SID="S-1-5-21-1149901229-438850559-190516975"

sambaDomain="SIMPLEX"

slaveLDAP="192.168.18.21"

slavePort="389"

masterLDAP="192.168.18.21"

masterPort="389"

ldapTLS="0"

verify=""

cafile=""

clientcert=""

clientkey=""

suffix="dc=simplex,dc=local"

usersdn="ou=People,${suffix}"

computersdn="ou=People,${suffix}"

groupsdn="ou=Group,${suffix}"

idmapdn="ou=People,${suffix}"

sambaUnixIdPooldn="sambaDomainName=${sambaDomain},${suffix}"

scope="sub"

hash_encrypt="SSHA"

crypt_salt_format=""

userLoginShell="/bin/bash"

userHome="/home/%U"

userHomeDirectoryMode="700"

userGecos="System User"

defaultUserGid="513"

defaultComputerGid="515"

skeletonDir="/etc/skel"

defaultMaxPasswordAge="70"

userSmbHome="\\%L\%U"

userProfile="\\%L\Profiles\%U"

userHomeDrive="/home"

userScript="scripts\logon.bat"

mailDomain="simplex-bpo.com"

with_smbpasswd="0"
smbpasswd="/usr/bin/smbpasswd"

with_slappasswd="0"
slappasswd="/usr/sbin/slappasswd"

and smbldap_bind.conf:

[root@asterisk21 ~]# cat /etc/smbldap-tools/smbldap_bind.conf

############################
# Credential Configuration #
############################
# Note: you can specify two different configurations if you use a
# master ldap for writing access and a slave ldap server for reading access
# By default, we will use the same DN (so it will work for standard Samba
# release)
slaveDN="cn=admin,dc=simplex,dc=local"
slavePw="passwd"
masterDN="cn=admin,dc=simplex,dc=local"
masterPw="passwd"

Adding samba scheme to LDAP

make a new file:

[root@asterisk21 ~]# cat schema_convert.conf
include /etc/openldap/schema/core.schema
include /etc/openldap/schema/collective.schema
include /etc/openldap/schema/corba.schema
include /etc/openldap/schema/cosine.schema
include /etc/openldap/schema/duaconf.schema
include /etc/openldap/schema/dyngroup.schema
include /etc/openldap/schema/inetorgperson.schema
include /etc/openldap/schema/java.schema
include /etc/openldap/schema/misc.schema
include /etc/openldap/schema/nis.schema
include /etc/openldap/schema/openldap.schema
include /etc/openldap/schema/pmi.schema
include /etc/openldap/schema/ppolicy.schema
include /etc/openldap/schema/samba.schema
mkdir /tmp/ldif_output
slaptest -f schema_convert.conf -F /tmp/ldif_output

now edit two files in /tmp/ldif_output/cn=config/cn=schema/

  •  cn={13}samba.ldif
  • cn={8}misc.ldif

edit header of files:

[root@asterisk21 ~]# cat /tmp/ldif_output/cn=config/cn=schema/cn={13}samba.ldif
dn: cn=samba,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: samba
[root@asterisk21 ~]# cat /tmp/ldif_output/cn=config/cn=schema/cn={8}misc.ldif
dn: cn=misc,cn=schema,cn=config
objectClass: olcSchemaConfig
cn:misc

erase from bottom something like that:

structuralObjectClass: olcSchemaConfig
entryUUID: 10dae0ea-0760-102d-80d3-f9366b7f7757
creatorsName: cn=config
createTimestamp: 20080826021140Z
entryCSN: 20080826021140.791425Z#000000#000#000000
modifiersName: cn=config
modifyTimestamp: 20080826021140Z

then export them to LDAP:

ldapadd -Y EXTERNAL -H ldapi:/// -f /tmp/ldif_output/cn=config/cn=schema/cn={8}misc.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /tmp/ldif_output/cn=config/cn=schema/cn={13}samba.ldif

Now youll be able to run:

smbldap-populate

If it was OK, then your smbldap-tools were set properly. Now you can add new samba-LDAP users
I have a simple script to do it easy:

[root@asterisk21 ~]# cat ldapuser-add.sh
#!/bin/bash
# smbldap-useradd -a -m -A 1 -B 1 -N John -S Smith -T john.smith@724care.net (username)
# USAGE: ldapuser-add.sh
smbldap-useradd -a -m -A 1 -B 1 -N $2 -S $3 -T $4 $1
smbldap-passwd $1

phpldapadmin

  790  cd /usr/src/
  791  wget http://downloads.sourceforge.net/project/phpldapadmin/phpldapadmin-php5/1.2.2/phpldapadmin-1.2.2.tgz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fphpldapadmin%2Ffiles%2Fphpldapadmin-php5%2F1.2.2%2F&ts=1326997487&use_mirror=voxel
  792  ls
  793  tar -xzvf phpldapadmin-1.2.2.tgz
  794  cp -R phpldapadmin-1.2.2 /var/www/html/
  795  mv /var/www/html/phpldapadmin-1.2.2/config/config.php.example  /var/www/html/phpldapadmin-1.2.2/config/config.php
  796  cd /var/www/html/
  797  ls
  798  mv phpldapadmin-1.2.2 phpldapadmin

now go to http://SERVER_IP/phpldapadmin
and login as “cn=admin,dc=example,dc=com”

ssh without passwd

2012 January 19
Comments Off
Posted by shirker2006
  ssh-keygen
  ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.45.11
  ssh 192.168.45.11

echo test phone number

2012 January 15
Comments Off
Posted by shirker2006

do you wanna test your asterisk configuration? call this no

1 909 390 0003

squid + iptables examples

2012 January 11
Comments Off
Posted by shirker2006

squid.conf

#
# Recommended minimum configuration:
#
visible_hostname "poison squid"
acl manager proto cache_object
acl localhost src 127.0.0.1/32 ::1
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1
#
# Custom Settings for 724 Care
#
#acl localhost_google_66 src 192.168.66.0/24
#acl google_web_66 dstdomain .gmail.com .google.com .youtube.com
#http_access deny google_web_66 localhost_google_66

#acl localhost_google_11 src 192.168.11.0/24
#acl google_web_11 src 192.168.66.0/24
#http_access deny google_web_11 localhost_google_11

#acl facebook_web dstdomain .facebook.com .facebook.net .fb.com
#http_access deny facebook_web

acl server_station_f src 192.168.11.196
acl network_66 src 192.168.66.0/24
acl facebook_sites_dst dst "/etc/squid/conf.d/facebook_sites.conf"
#acl google_sites_dst dst "/etc/squid/conf.d/google_sites.conf"
acl allowed_sites dstdomain "/etc/squid/conf.d/allowed_sites.conf"
#acl limited_IP  src  "/etc/squid/conf.d/limited_IP.conf"
acl denied_sites  dstdomain "/etc/squid/conf.d/denied_ext.conf"
#
# Custom End for 724 Care
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8	# RFC1918 possible internal network
acl localnet src 172.16.0.0/12	# RFC1918 possible internal network
acl localnet src 192.168.0.0/16	# RFC1918 possible internal network
acl localnet src fc00::/7       # RFC 4193 local private network range
acl localnet src fe80::/10      # RFC 4291 link-local (directly plugged) machines

acl SSL_ports port 443
acl Safe_ports port 80		# http
acl Safe_ports port 21		# ftp
acl Safe_ports port 443		# https
acl Safe_ports port 70		# gopher
acl Safe_ports port 210		# wais
acl Safe_ports port 1025-65535	# unregistered ports
acl Safe_ports port 280		# http-mgmt
acl Safe_ports port 488		# gss-http
acl Safe_ports port 591		# filemaker
acl Safe_ports port 777		# multiling http
acl CONNECT method CONNECT

http_access allow manager localhost
http_access deny manager

http_access deny !Safe_ports

http_access deny CONNECT !SSL_ports

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access deny facebook_sites_dst
#http_access deny google_sites_dst network_66
http_access deny denied_sites
http_access allow allowed_sites
#http_access allow localnet
http_access allow localhost

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
# http_port 3128 intercept
http_port 3128 transparent
https_port 3129 transparent key=/etc/squid/ssl/squid.key cert=/etc/squid/ssl/squid.crt

# Uncomment and adjust the following to add a disk cache directory.
cache_dir ufs /var/spool/squid 4096 16 512

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

# Add any of your own refresh_pattern entries above these.
refresh_pattern ^ftp:		1440	20%	10080
refresh_pattern ^gopher:	1440	0%	1440
refresh_pattern -i (/cgi-bin/|\?) 0	0%	0
refresh_pattern .		0	20%	4320

/etc/sysconfig/iptables:

# Generated by iptables-save v1.4.7 on Wed Nov  9 13:37:50 2011
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [10363:2864591]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i eth+ -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -i lo -j ACCEPT
-A FORWARD -i eth+ -j ACCEPT
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Wed Nov  9 13:37:50 2011
# Generated by iptables-save v1.4.7 on Wed Nov  9 13:37:50 2011
*nat
:PREROUTING ACCEPT [4:650]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 3129
COMMIT
# Completed on Wed Nov  9 13:37:50 2011

Asterisk call transfer (RUS)

2011 December 28
Comments Off
Posted by shirker2006

Парковка вызова

http://www.xakep.ru/magazine/xa/109/148/1.asp

Парковка вызова (Call parking) является одним из несомненных удобств, предоставляемых Asterisk. Работает это так. Ты поднимаешь трубку и в процессе разговора понимаешь, что разбираться с проблемой должен другой сотрудник либо для выяснения всех обстоятельств необходимо перейти на другое рабочее место. Вместо того чтобы просить абонента перезвонить по другому телефону, ты, просто набирая комбинацию клавиш, помещаешь вызов во временный слот и, перейдя на новое место и набрав номер этого слота, продолжаешь разговор. Параметры парковки и комбинация для передачи вызова определяются в файле features.conf. После установки сервера в нем активированы следующие параметры:

$ sudo mcedit /etc/asterisk/features.conf

[general]

; Экстеншен для парковки

parkext => 700

; Слоты для парковки

parkpos => 701-720

; Контекст для парковки

context => parkedcalls

; Время парковки (в секундах), после которого будет произведен вызов по первому номеру

parkingtime => 45

; Время набора цифры при передаче вызова

transferdigittimeout => 3

; Оповещения

courtesytone = beep

xfersound = beep

xferfailsound = beeperr

; Отсылка информации на экраны ADSI-телефонов

adsipark = yes

[featuremap]

; Комбинация активации передачи звонка

blindxfer => #

; Разъединение

disconnect => *

И в диалплане тех пользователей, которым разрешена парковка, подключаем экстеншен parkedcalls:

include => parkedcalls

Теперь если во время разговора нажать клавишу <#>, а затем номер, указанный в parkext (в нашем примере 700), ты услышишь номер слота, к которому будет подключен абонент. Только набирать нужно быстро, иначе получишь сообщение о неудачной операции. Набрав на другом телефоне полученный номер слота, ты сможешь продолжить разговор.

Теперь несколько другая ситуация, также нередкая в любом офисе, – сотрудник, находящийся рядом, по некоторым причинам не может ответить на телефонный звонок. В таком случае можно подойти к звонящему телефону или просто набрать определенную комбинацию плюс номер звонящего телефона и перехватить вызов (Call Pickup). Реализуется это несколькими способами. Самый простой – добавить в описание каждого аккаунта параметры callgroup и pickupgroup. В этом случае нажатием «*8» можно перехватить звонок на любой номер в пределах группы. Комбинация цифр для перехвата определена в переменной pickupexten в файле features.conf. В остальных случаях надо использовать функцию Pickup:

Pickup(extension[@context][&extension2@context...])

[xxxxxx]

exten => *8,1,Pickup(1111@xxxxxx)

exten => 1111,1,Dial(1111,60,rtT)

Следует помнить, что перехват вызова работает только в пределах технологии SIP, IAX, Zapata и т.д. То есть, например, в схеме «SIP-телефон – SIP-телефон» Pickup работать будет, а перехватить входящий звонок с обычной телефонной линии с помощью SIP-телефона не получится.

asterisk centos iptables rules

2011 December 28
Comments Off
Posted by shirker2006

/etc/sysconfig/iptables

# Generated by iptables-save v1.3.5 on Tue Dec 27 18:49:44 2011
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [69:20484]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 5060 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 4569 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 5036 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 10000:20000 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 2727 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Tue Dec 27 18:49:44 2011

then service iptables start

fixing /dev/md5

2011 December 23
Comments Off
Posted by shirker2006
  542  mdadm --assemble /dev/md5 /dev/sdc1 /dev/sdd1 /dev/sde1 /dev/sdf1 /dev/sdg1
  543  cat /proc/mdstat
  544  mdadm --assemble --force /dev/sdc1 /dev/sdd1 /dev/sde1 /dev/sdf1 /dev/sdg1 /dev/sdh1
  545  mdadm --assemble --force /dev/sdc1 /dev/sdd1 /dev/sdf1 /dev/sdg1 /dev/sdh1
  546  mdadm --assemble --force /dev/sdc1 /dev/sdd1 /dev/sde1  /dev/sdf1 /dev/sdg1 /dev/sdh1
  547  mdadm --assemble /dev/sdc1 /dev/sdd1 /dev/sdf1 /dev/sdg1 /dev/sdh1
  548  mdadm --assemble /dev/sdc1 /dev/sdd1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  549  mdadm --assemble /dev/md5 /dev/sdc1 /dev/sdd1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  550  mdadm --assemble /dev/md5 /dev/sdc1 /dev/sdd1 /dev/sde1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  551  mdadm --assemble --force /dev/md5 /dev/sdc1 /dev/sdd1 /dev/sde1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  552  cat /etc/fstab
  553  cat /etc/mtab
  554  fdisk -l
  555  mdadm --assemble /dev/md5 /dev/sdc1 /dev/sdd1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  556  cat /proc/mdstat
  557  w
  558  cat /etc/fstab
  559  cat /etc/mtab
  560  w
  561  cat /proc.mdstat
  562  cat /proc/mdstat
  563  reboot
  564  cat /proc/mdstat
  565  mdadm -stop /dev/md127
  566  mdadm  /dev/md127 -stop
  567  df
  568  mdadm --assemble --force /dev/md5 /dev/sdc1 /dev/sdd1 /dev/sde1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  569  mdadm --assemble --force /dev/md5  /dev/sdd1 /dev/sde1 /dev/sdf1 /dev/sdg1 /dev/sdh1 /dev/sdh1
  570  mdadm  /dev/md127 --stop
  571  cat /proc/mdstat
  572  vi /etc/mdadm.conf

strace

2011 December 22
Comments Off
Posted by shirker2006

do you wanna know, what files are being used by some specific program?

 yum install -y strace.x86_64

strace <PROGRAM NAME>

Vim (Русский)

2011 December 18
Comments Off
Posted by shirker2006

https://wiki.archlinux.org/index.php/Vim_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)

Vim (VI iMproved, Улучшенный Vi) – текстовый редактор, происходящий от vi. Он печально известен своей сложностью в изучении и недружелюбностью к пользователю. Однако, благодаря своей эффективности, множеству плагинов и гибкости в настройке vim стал одним из наиболее популярных текстовых редакторов для программистов и пользователей *nix (вместе с Emacs). Доступна также графическая версия vim – gvim, которая предоставляет пользователю интерфейс на базе GTK2.

Contents

[hide]

Установка

  • vim зависит от vi, так что следует сначала установить его. Однако, поскольку последний является частью базового инсталляционного пакета, у большинства пользователей он уже должен быть. (прим. перев.: pacman -S устанавливает пакеты вместе с их зависимостями, так что достаточно команды, приведённой ниже)
pacman -S vim

Настройка

Конфигурационный файл vim находится в домашнем каталоге пользователя (~/) и называется .vimrc. Пример конфигурационного файла находится в /etc/vimrc.

"Sample .vimrc
set nocompatible
set showmatch
set incsearch
set ignorecase
set smartcase
set history=100
set backspace=eol,start,indent
set ruler
set tabstop=4
set shiftwidth=4
set expandtab
set virtualedit=all
set background=dark
set vb t_vg=
set mouse=v
set textwidth=79
set formatoptions=tcrq
  • Чтобы установить gvim (то же, что и vim, но с gtk2-интерфейсом и смотрит в /etc/gvimrc и в ~/.gvimrc), введите
pacman -S gvim
  • Существует также набор скриптов для vim, доступный через pacman
pacman -S vim-scripts

Быстрый старт

Запуск vim

  • Чтобы запустить vim и отредактировать файл (новый или существующий), введите:
vim filename
  • Чтобы запустить vim и открыть новый файл:
vim

(Можно ввести имя файла позже, при сохранении)

Ввод текста

vim – редактор с множеством режимов. Базовыми режимами являются:

  • Режим вставки, в котором всё, что вы напечатаете (за исключением некоторых специальных клавиш) появляется на экране и помещается в ваш файловый буфер
  • Командный режим (также известный как “нормальный режим”), в котором нажатия клавиш интерпретируются как команды.
  • Так называемый “режим последней строки”, из которого можно сохранить файл, открыть ещё один, найти что-либо в тексте и выполнить некоторые другие действия.

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

  • Переключение между режимами.

1. Из командного в режим вставки – клавишей <i>, из командного – в режим последней строки – клавишей <:>

2. Из режима вставки в командный – клавишей <Esc>

3. Из режима последней строки в командный режим – клавишей <Esc >

Перемещение курсора

Как в командном, так и в режиме вставки курсор перемещается стрелками, а в gvim можно задать положение курсора щелчком мыши. Однако, это не по-вимовски. Наиболее эффективный способ – переключиться в командный режим и использовать команды vim для перемещения курсора. Существует 4 базовых команды:

  • j - на одну строку ниже
  • k - на одну строку выше
  • h - на один символ влево
  • l - на один символ вправо

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

Некоторые другие команды:

  • 0 (нуль) или ^ - для перемещения к первому символу в строке
  • $ - для перемещения к последнему символу в строке
  • w - для перемещения к первой букве следующего слова
  • e - для перемещения к последнему символу следующего слова
  • ( - для перемещения к началу предыдущего предложения
  • ) - для перемещения к началу следующего предложения
  • { - для перемещения к началу текущего абзаца
  • } - для перемещения к началу следующего абзаца
  • <PgUp> или <Ctrl>+<F> – для перемещения на одну страницу вверх
  • <PgDn> или <Ctrl>+<B> – для перемещения на одну страницу вниз
  • <номер строки>-<G> – перемещение курсора на указанный номер строки.
  • <Shift>+<G> – перемещение курсора на последнюю строку файла.
  • <g>-<g> – перемещение курсора на первую строку файла.

Удаление текста

Прежде всего, стоит отметить, что клавиша <Delete> работает всегда, а <Backspace> – в режиме вставки. Однако, предполагается, что вы их использовать не будете. Вместо этого предполагается использование команд удаления vim.

1. Перейдите в командный режим

2. Наведите курсор на символ, который хотите удалить.

3. Нажмите <x>, символ исчезнет.

x - лишь одна из многих мощных команд удаления. Подробнее о них можно узнать, задействовав vimtutor (см. ниже).

Вставка текста

1. В командном режиме подведите курсор к нужному месту

2. Нажмите <i> и введите текст. Текст введётся перед выделенным символом

ИЛИ

2. Нажмите <a>. Текст введётся после выделенного символа.

2. Нажмите <Shift>+<a>. Текст введётся после последнего символа строки.

Cut, Copy, Paste

Если вы используете gvim, вы можете выполнять эти операции с помощью меню, как и в любом другом редакторе. Однако, этот способ не рекомендуется. Лучше действовать без мыши:

1. Войдите в командный режим

2. Подведите курсор к строке, которую вы хотите скопировать

3. Нажмите

yy

чтобы скопировать строку, или

dd

чтобы удалить строку и поместить в буфер.

4. Теперь переместите курсор к месту, где хотите вставить скопированный/вырезанный текст.

5. Нажмите

p

чтобы поместить строку из буфера после текущей строки, или

P

чтобы поместить её перед текущей строкой.

Чтобы скопировать несколько строк, поместите их количество перед командой yy, например

6yy

чтобы скопировать 6 строк. Разумеется, это лишь вершина айсберга, vimtutor знает гораздо больше команд.

Cut, Copy, Paste в визуальном режиме

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

Нажмите v, чтобы перейти в визуальный режим, затем выделите текст с помощью клавиш перемещения курсора. Также можно выделять текст мышью. (Если в командном режиме начать выделять мышью, vim автоматически перейдёт в визуальный режим)

Чтобы копировать текст, нажмите

y

Чтобы вырезать:

d

Чтобы вставить перед курсором:

p

или

P

чтобы вставить после него.

Отмена действий

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

u

отменит последнее действие. Повторное нажатие отменит следующее успешное действие.

А выполнить повторно последнее действие, если отменили слишком много:

.

Поиск слова

Предположим, вы хотите найти в тексте слово apple.

1. Перейдите в командный режим.

2. Наберите

/apple<Enter>

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

3. После того, как нашли первое вхождение apple, можно найти остальные, нажав

n

Что бы искать в обратном направлении

N

Замена текста

Прежде всего убедитесь, что вы в командном режиме нажатием клавиши <Esc>.

  • Чтобы заменить единственный символ, подведите к нему курсор и нажмите r, затем то, чем вы хотите его заменить.
  • Чтобы заменить первое вхождение строки old в текущей строке строкой new
:s/old/new
  • Чтобы заменить все вхождения old в текущей строке на new
:s/old/new/g
  • Чтобы заменить первое входжение old между строками n1 и n2 на new
:n1,n2s/old/new/
  • Чтобы заменить все вхождения old между строками n1 и n2 на new
:n1,n2s/old/new/g
  • Чтобы заменить все вхождения old во всём текстовом буфере на new с подтверждением
:%s/old/new/gc

или

:1,$s/old/new/gc

Выход из vim

  • Для того, чтобы сохраниться и выйти, в командном режиме наберите
:wq

или

:x

или

ZZ
  • Для того, чтобы сохранить работу под именем newnname, наберите:
:wq newname
  • Для выхода без сохранения, нажмите
:q
  • Форсированный выход

Если :q не работает, возможно, данные не были сохранены. Если хотите их сохранить, используйте :wq, если нет, введите

:q!

или

ZQ

Некоторые полезности режима последней строки

Будучи мощным текстовым редактором, vim поддерживает, кроме всего вышеперечисленного, также подсветку синтаксиса (в различных цветовых схемах) и конвертирование файлов из одной кодировки в другую.

  • Чтобы включить подсветку синтаксиса, в командном режиме наберите
:syn on
  • Чтобы изменить схему подсветки (какие элементы каким цветом подсвечивать), введите
:colorscheme name

где name - имя цветовой схемы

  • Чтобы перекодировать файл, введите
:e ++enc=from-enc

Файл будет отображён в кодировке вашего терминала.

  • Включение отображение номеров строк
:set number

Отключение отображение номеров строк

:set nonumber

Учебник по vim

Чтобы сделать свои первые шаги в vim, введите в командной строке

vimtutor

или

vimtutor ru

vim откроет файл интерактивного учебника.

Ссылки

install php4 on centos5

2011 December 16
Comments Off
Posted by shirker2006
cd /usr/src/php-4.4.9

yum install gd-devel flex bison httpd-devel libjpeg-devel libpng-devel libxml2-devel libxslt-devel -y

./configure --with-apxs2=/usr/sbin/apxs --prefix=/usr/local/php --with-mysql --enable-mbstring --with-config-file-path=/usr/local/etc --enable-ftp --enable-libxml --with-dom-xslt --with-libxml-dir=/usr/local --enable-reflection --enable-force-cgi-redirect --enable-fastcgi --with-iconv --with-regex=php --disable-ipv6 --mandir=/usr/local/man --infodir=/usr/local/info/ --with-gd=/usr --with-dom --enable-gd-native-ttf=/usr --with-jpeg-dir=/usr --with-png-dir=/usr --with-ttf --with-zlib-dir=/usr --disable-posix --enable-inline-optimization

make

make install

Add to httpd.conf:

LoadModule php4_module modules/libphp4.so

AddType application/x-httpd-php .php .phtml

additional info (RUS):

http://hottab.ru/linux/ustanovka-php4-na-centos-5-mod-apache-22/

.htaccess RewriteRule php URL to just simple url

2011 December 15
Comments Off
Posted by shirker2006

I need redirect “index.php?menu=pbxconfig” just to “admin”.
This is solution:

Options +FollowSymLinks
RewriteEngine on
#RewriteRule ^admin$ index.php?menu=pbxconfig [L,QSA]
RewriteCond %{QUERY_STRinG} pbxconfig
RewriteRule ^index\.php$ admin [L,QSA]

Elastix. Where is admin’s passwd?

2011 December 8
Comments Off
Posted by shirker2006

I dont wanna tell you, whats passwd for that, but i know the way how to reset it right away after installation:

/usr/bin/sqlite3 /var/www/db/acl.db "UPDATE acl_user SET md5_password = '`echo -n <NEW PASSWD>|md5sum|cut -d ' ' -f 1`' WHERE name = 'admin'"

What are the default passwords in Elastix CentOS

Interface Login Password
Elastix admin palosanto
freePBX admin admin
FOP admin eLaStIx.2oo7
A2Billing admin mypassword
MySQL root eLaStIx.2oo7
SugarCRM admin password
Avantfax admin password
asterisk admin elastix456
vTiger admin admin
Openfire admin Whatever set at install
ARI admin password

OSLEC echocanceller with Dahdi

2011 December 3
Comments Off
Posted by shirker2006

Installing OSLEC with DAHDI

http://www.rowetel.com/blog/?page_id=454

Paul Sinclair has posted some notes on how to install Oslec With DAHDI. These were first posted by Samy Antoun on the FreePBX forum. With Paul and Samy’s kind permission I have copied their instructions here:

    • Here we assume you have the dahdi source sitting in /usr/src/dahdi (that is, the makefile, readme and the few folders)
  • Just before you install this, make sure you stop asterisk and dahdi
    cd /usr/src
    wget http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.28.tar.bz2
    tar xjf linux-2.6.28.tar.bz2
    mkdir /usr/src/dahdi/drivers/staging
    cp -fR /usr/src/linux-2.6.28/drivers/staging/echo /usr/src/dahdi/drivers/staging
    sed -i "s|#obj-m += dahdi_echocan_oslec.o|obj-m += dahdi_echocan_oslec.o|" /usr/src/dahdi/drivers/dahdi/Kbuild
    sed -i "s|#obj-m += ../staging/echo/|obj-m += ../staging/echo/|" /usr/src/dahdi/drivers/dahdi/Kbuild
    echo 'obj-m += echo.o' > /usr/src/dahdi/drivers/staging/echo/Kbuild
    cd /usr/src/dahdi/
    make
    make install

so now you can use echocanceller /etc/dahdi/system.conf:


# Autogenerated by /usr/sbin/dahdi_genconf on Sat Feb 28 12:18:21 2009 -- do not hand edit
# Dahdi Configuration File
#
# This file is parsed by the Dahdi Configurator, dahdi_cfg
#
# Span 1: Tor2/0/1 "Tormenta 2 (PCI) Quad T1 Card 0 Span 1" (MASTER) B8ZS/ESF
loadzone        = us
defaultzone     = us

span=1,0,0,esf,b8zs
# termtype: te
fxols=1-24
echocanceller=oslec,1-24
#echocanceller=mg2,1-24

# Span 2: Tor2/0/2 "Tormenta 2 (PCI) Quad T1 Card 0 Span 2" B8ZS/ESF
span=2,0,0,esf,b8zs
# termtype: te
fxols=25-48
echocanceller=oslec,25-48
#echocanceller=mg2,25-48

# Span 3: Tor2/0/3 "Tormenta 2 (PCI) Quad T1 Card 0 Span 3" B8ZS/ESF
span=3,0,0,esf,b8zs
# termtype: te
fxols=49-72
echocanceller=oslec,49-72
#echocanceller=mg2,49-72

# Span 4: Tor2/0/4 "Tormenta 2 (PCI) Quad T1 Card 0 Span 4" B8ZS/ESF
span=4,0,0,esf,b8zs
# termtype: te
#loadzone=ph
#fxsls=73-80
loadzone=us
fxols=73-96
echocanceller=oslec,73-96
#echocanceller=mg2,73-96

# Global data

loadzone        = us
defaultzone     = us

transparent Squid with http and https (80 and 443 ports)

2011 November 27
Comments Off
Posted by shirker2006

Ill give note, how to setup transparent squid with SSL redirect.
after you installed squid (be sure 3.1.16 or above) you’ll do configurations of iptables:

/etc/sysconfig/iptables

# Generated by iptables-save v1.4.7 on Wed Nov  9 13:37:50 2011
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [10363:2864591]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i eth+ -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -i lo -j ACCEPT
-A FORWARD -i eth+ -j ACCEPT
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Wed Nov  9 13:37:50 2011
# Generated by iptables-save v1.4.7 on Wed Nov  9 13:37:50 2011
*nat
:PREROUTING ACCEPT [4:650]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 3129
COMMIT
# Completed on Wed Nov  9 13:37:50 2011
squid -version
Squid Cache: Version 3.1.16

Here is conf file

/etc/squid/squid.conf

#
# Recommended minimum configuration:
#
visible_hostname "poison squid"
acl manager proto cache_object
acl localhost src 127.0.0.1/32 ::1
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1
acl allowed_sites dstdomain "/etc/squid/conf.d/allowed_sites.conf"
#acl limited_IP  src  "/etc/squid/conf.d/limited_IP.conf"
acl denied_sites  dstdomain "/etc/squid/conf.d/denied_ext.conf"

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8	# RFC1918 possible internal network
acl localnet src 172.16.0.0/12	# RFC1918 possible internal network
acl localnet src 192.168.0.0/16	# RFC1918 possible internal network
acl localnet src fc00::/7       # RFC 4193 local private network range
acl localnet src fe80::/10      # RFC 4291 link-local (directly plugged) machines

acl SSL_ports port 443
acl Safe_ports port 80		# http
acl Safe_ports port 21		# ftp
acl Safe_ports port 443		# https
acl Safe_ports port 70		# gopher
acl Safe_ports port 210		# wais
acl Safe_ports port 1025-65535	# unregistered ports
acl Safe_ports port 280		# http-mgmt
acl Safe_ports port 488		# gss-http
acl Safe_ports port 591		# filemaker
acl Safe_ports port 777		# multiling http
acl CONNECT method CONNECT

http_access allow manager localhost
http_access deny manager

http_access deny !Safe_ports

http_access deny CONNECT !SSL_ports

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access  deny  denied_sites
http_access  allow  allowed_sites
#http_access allow localnet
http_access allow localhost

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
# http_port 3128 intercept
http_port 3128 transparent
https_port 3129 transparent key=/etc/squid/ssl/squid.key cert=/etc/squid/ssl/squid.crt

# Uncomment and adjust the following to add a disk cache directory.
cache_dir ufs /var/spool/squid 4096 16 512

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

# Add any of your own refresh_pattern entries above these.
refresh_pattern ^ftp:		1440	20%	10080
refresh_pattern ^gopher:	1440	0%	1440
refresh_pattern -i (/cgi-bin/|\?) 0	0%	0
refresh_pattern .		0	20%	4320

to /etc/squid/conf.d/allowed_sites.conf file you will add allowed sites. according to this configurations only sites from that file will be allowed. you can install webmin and there make an account, that will be able to only one operation – online editing as root /etc/squid/conf.d/allowed_sites.conf (others section). after saving  it should execute:

/etc/init.d/squid reload

How to generate ssl certificate here: http://shirker.blog.com/2011/11/10/generate-ssl-certificate-for-squid/

To ensure, thats squid is listening both ports type

lsof -n -i -P

PUTTY from command line

2011 November 23
Comments Off
Posted by shirker2006
 Full version: http://the.earth.li/~sgtatham/putty/0.61/puttydoc.txt

3.8.1 Starting a session from the command line

       These options allow you to bypass the configuration window and
       launch straight into a session.

       To start a connection to a server called `host':

         putty.exe [-ssh | -telnet | -rlogin | -raw] [user@]host

       If this syntax is used, settings are taken from the Default Settings
       (see section 4.1.2); `user' overrides these settings if supplied.
       Also, you can specify a protocol, which will override the default
       protocol (see section 3.8.3.2).

       For telnet sessions, the following alternative syntax is supported
       (this makes PuTTY suitable for use as a URL handler for telnet URLs
       in web browsers):

         putty.exe telnet://host[:port]/

       To start a connection to a serial port, e.g. COM1:

         putty.exe -serial com1

       In order to start an existing saved session called `sessionname',
       use the `-load' option (described in section 3.8.3.1).

         putty.exe -load "session name"

 3.8.2 `-cleanup'

       If invoked with the `-cleanup' option, rather than running as
       normal, PuTTY will remove its registry entries and random seed file
       from the local machine (after confirming with the user).

       Note that on multi-user systems, `-cleanup' only removes registry
       entries and files associated with the currently logged-in user.

 3.8.3 Standard command-line options

       PuTTY and its associated tools support a range of command-line
       options, most of which are consistent across all the tools. This
       section lists the available options in all tools. Options which are
       specific to a particular tool are covered in the chapter about that
       tool.

3.8.3.1 `-load': load a saved session

       The `-load' option causes PuTTY to load configuration details out
       of a saved session. If these details include a host name, then this
       option is all you need to make PuTTY start a session.

       You need double quotes around the session name if it contains
       spaces.

       If you want to create a Windows shortcut to start a PuTTY saved
       session, this is the option you should use: your shortcut should
       call something like

         d:\path\to\putty.exe -load "my session"

       (Note that PuTTY itself supports an alternative form of this option,
       for backwards compatibility. If you execute `putty @sessionname' it
       will have the same effect as `putty -load "sessionname"'. With the
       `@' form, no double quotes are required, and the `@' sign must be
       the very first thing on the command line. This form of the option is
       deprecated.)

3.8.3.2 Selecting a protocol: `-ssh', `-telnet', `-rlogin', `-raw' `-
       serial'

       To choose which protocol you want to connect with, you can use one
       of these options:

        -  `-ssh' selects the SSH protocol.

        -  `-telnet' selects the Telnet protocol.

        -  `-rlogin' selects the Rlogin protocol.

        -  `-raw' selects the raw protocol.

        -  `-serial' selects a serial connection.

       These options are not available in the file transfer tools PSCP and
       PSFTP (which only work with the SSH protocol).

       These options are equivalent to the protocol selection buttons
       in the Session panel of the PuTTY configuration box (see section
       4.1.1).

3.8.3.3 `-v': increase verbosity

       Most of the PuTTY tools can be made to tell you more about what they
       are doing by supplying the `-v' option. If you are having trouble
       when making a connection, or you're simply curious, you can turn
       this switch on and hope to find out more about what is happening.

3.8.3.4 `-l': specify a login name

       You can specify the user name to log in as on the remote server
       using the `-l' option. For example, `plink login.example.com -
       l fred'.

       These options are equivalent to the username selection box in
       the Connection panel of the PuTTY configuration box (see section
       4.14.1).

3.8.3.5 `-L', `-R' and `-D': set up port forwardings

       As well as setting up port forwardings in the PuTTY configuration
       (see section 4.24), you can also set up forwardings on the command
       line. The command-line options work just like the ones in Unix `ssh'
       programs.

       To forward a local port (say 5110) to a remote destination (say
       popserver.example.com port 110), you can write something like one of
       these:

         putty -L 5110:popserver.example.com:110 -load mysession
         plink mysession -L 5110:popserver.example.com:110

       To forward a remote port to a local destination, just use the `-R'
       option instead of `-L':

         putty -R 5023:mytelnetserver.myhouse.org:23 -load mysession
         plink mysession -R 5023:mytelnetserver.myhouse.org:23

       To specify an IP address for the listening end of the tunnel,
       prepend it to the argument:

         plink -L 127.0.0.5:23:localhost:23 myhost

       To set up SOCKS-based dynamic port forwarding on a local port, use
       the `-D' option. For this one you only have to pass the port number:

         putty -D 4096 -load mysession

       For general information on port forwarding, see section 3.5.

       These options are not available in the file transfer tools PSCP and
       PSFTP.

3.8.3.6 `-m': read a remote command or script from a file

       The `-m' option performs a similar function to the `Remote command'
       box in the SSH panel of the PuTTY configuration box (see section
       4.18.1). However, the `-m' option expects to be given a local file
       name, and it will read a command from that file.

       With some servers (particularly Unix systems), you can even put
       multiple lines in this file and execute more than one command in
       sequence, or a whole shell script; but this is arguably an abuse,
       and cannot be expected to work on all servers. In particular, it is
       known _not_ to work with certain `embedded' servers, such as Cisco
       routers.

       This option is not available in the file transfer tools PSCP and
       PSFTP.

3.8.3.7 `-P': specify a port number

       The `-P' option is used to specify the port number to connect to. If
       you have a Telnet server running on port 9696 of a machine instead
       of port 23, for example:

         putty -telnet -P 9696 host.name
         plink -telnet -P 9696 host.name

       (Note that this option is more useful in Plink than in PuTTY,
       because in PuTTY you can write `putty -telnet host.name 9696' in any
       case.)

       This option is equivalent to the port number control in the Session
       panel of the PuTTY configuration box (see section 4.1.1).

3.8.3.8 `-pw': specify a password

       A simple way to automate a remote login is to supply your password
       on the command line. This is _not recommended_ for reasons of
       security. If you possibly can, we recommend you set up public-key
       authentication instead. See chapter 8 for details.

       Note that the `-pw' option only works when you are using the SSH
       protocol. Due to fundamental limitations of Telnet and Rlogin, these
       protocols do not support automated password authentication.

3.8.3.9 `-agent' and `-noagent': control use of Pageant for authentication

       The `-agent' option turns on SSH authentication using Pageant, and
       `-noagent' turns it off. These options are only meaningful if you
       are using SSH.

       See chapter 9 for general information on Pageant.

       These options are equivalent to the agent authentication checkbox in
       the Auth panel of the PuTTY configuration box (see section 4.20.3).

3.8.3.10 `-A' and `-a': control agent forwarding

       The `-A' option turns on SSH agent forwarding, and `-a' turns it
       off. These options are only meaningful if you are using SSH.

       See chapter 9 for general information on Pageant, and section 9.4
       for information on agent forwarding. Note that there is a security
       risk involved with enabling this option; see section 9.5 for
       details.

       These options are equivalent to the agent forwarding checkbox in the
       Auth panel of the PuTTY configuration box (see section 4.20.6).

       These options are not available in the file transfer tools PSCP and
       PSFTP.

3.8.3.11 `-X' and `-x': control X11 forwarding

       The `-X' option turns on X11 forwarding in SSH, and `-x' turns it
       off. These options are only meaningful if you are using SSH.

       For information on X11 forwarding, see section 3.4.

       These options are equivalent to the X11 forwarding checkbox in the
       X11 panel of the PuTTY configuration box (see section 4.23).

       These options are not available in the file transfer tools PSCP and
       PSFTP.

3.8.3.12 `-t' and `-T': control pseudo-terminal allocation

       The `-t' option ensures PuTTY attempts to allocate a pseudo-terminal
       at the server, and `-T' stops it from allocating one. These options
       are only meaningful if you are using SSH.

       These options are equivalent to the `Don't allocate a pseudo-
       terminal' checkbox in the SSH panel of the PuTTY configuration box
       (see section 4.22.1).

       These options are not available in the file transfer tools PSCP and
       PSFTP.

3.8.3.13 `-N': suppress starting a shell or command

       The `-N' option prevents PuTTY from attempting to start a shell or
       command on the remote server. You might want to use this option if
       you are only using the SSH connection for port forwarding, and your
       user account on the server does not have the ability to run a shell.

       This feature is only available in SSH protocol version 2 (since the
       version 1 protocol assumes you will always want to run a shell).

       This option is equivalent to the `Don't start a shell or command at
       all' checkbox in the SSH panel of the PuTTY configuration box (see
       section 4.18.2).

       This option is not available in the file transfer tools PSCP and
       PSFTP.

3.8.3.14 `-nc': make a remote network connection in place of a remote shell
       or command

       The `-nc' option prevents Plink (or PuTTY) from attempting to start
       a shell or command on the remote server. Instead, it will instruct
       the remote server to open a network connection to a host name and
       port number specified by you, and treat that network connection as
       if it were the main session.

       You specify a host and port as an argument to the `-nc' option, with
       a colon separating the host name from the port number, like this:

         plink host1.example.com -nc host2.example.com:1234

       You might want to use this feature if you needed to make an SSH
       connection to a target host which you can only reach by going
       through a proxy host, and rather than using port forwarding you
       prefer to use the local proxy feature (see section 4.15.1 for more
       about local proxies). In this situation you might select `Local'
       proxy type, set your local proxy command to be `plink %proxyhost -
       nc %host:%port', enter the target host name on the Session panel,
       and enter the directly reachable proxy host name on the Proxy panel.

       This feature is only available in SSH protocol version 2 (since the
       version 1 protocol assumes you will always want to run a shell). It
       is not available in the file transfer tools PSCP and PSFTP. It is
       available in PuTTY itself, although it is unlikely to be very useful
       in any tool other than Plink. Also, `-nc' uses the same server
       functionality as port forwarding, so it will not work if your server
       administrator has disabled port forwarding.

       (The option is named `-nc' after the Unix program `nc', short for
       `netcat'. The command `plink host1 -nc host2:port' is very similar
       in functionality to `plink host1 nc host2 port', which invokes `nc'
       on the server and tells it to connect to the specified destination.
       However, Plink's built-in `-nc' option does not depend on the `nc'
       program being installed on the server.)

3.8.3.15 `-C': enable compression

       The `-C' option enables compression of the data sent across the
       network. This option is only meaningful if you are using SSH.

       This option is equivalent to the `Enable compression' checkbox in
       the SSH panel of the PuTTY configuration box (see section 4.18.3).

3.8.3.16 `-1' and `-2': specify an SSH protocol version

       The `-1' and `-2' options force PuTTY to use version 1 or version 2
       of the SSH protocol. These options are only meaningful if you are
       using SSH.

       These options are equivalent to selecting your preferred SSH
       protocol version as `1 only' or `2 only' in the SSH panel of the
       PuTTY configuration box (see section 4.18.4).

3.8.3.17 `-4' and `-6': specify an Internet protocol version

       The `-4' and `-6' options force PuTTY to use the older Internet
       protocol IPv4 or the newer IPv6 for most outgoing connections.

       These options are equivalent to selecting your preferred Internet
       protocol version as `IPv4' or `IPv6' in the Connection panel of the
       PuTTY configuration box (see section 4.13.4).

3.8.3.18 `-i': specify an SSH private key

       The `-i' option allows you to specify the name of a private key file
       in `*.PPK' format which PuTTY will use to authenticate with the
       server. This option is only meaningful if you are using SSH.

       For general information on public-key authentication, see chapter 8.

       This option is equivalent to the `Private key file for
       authentication' box in the Auth panel of the PuTTY configuration box
       (see section 4.20.8).

3.8.3.19 `-loghost': specify a logical host name

       This option overrides PuTTY's normal SSH host key caching policy by
       telling it the name of the host you expect your connection to end up
       at (in cases where this differs from the location PuTTY thinks it's
       connecting to). It can be a plain host name, or a host name followed
       by a colon and a port number. See section 4.13.5 for more detail on
       this.

3.8.3.20 `-pgpfp': display PGP key fingerprints

       This option causes the PuTTY tools not to run as normal, but instead
       to display the fingerprints of the PuTTY PGP Master Keys, in
       order to aid with verifying new versions. See appendix E for more
       information.

3.8.3.21 `-sercfg': specify serial port configuration

       This option specifies the configuration parameters for the serial
       port (baud rate, stop bits etc). Its argument is interpreted as
       a comma-separated list of configuration options, which can be as
       follows:

        -  Any single digit from 5 to 9 sets the number of data bits.

        -  `1', `1.5' or `2' sets the number of stop bits.

        -  Any other numeric string is interpreted as a baud rate.

        -  A single lower-case letter specifies the parity: `n' for none,
           `o' for odd, `e' for even, `m' for mark and `s' for space.

        -  A single upper-case letter specifies the flow control: `N' for
           none, `X' for XON/XOFF, `R' for RTS/CTS and `D' for DSR/DTR.

       For example, `-sercfg 19200,8,n,1,N' denotes a baud rate of 19200, 8
       data bits, no parity, 1 stop bit and no flow control.

a2billing install on CentOS (bash script)

2011 November 18
Comments Off
Posted by shirker2006
#!/bin/sh
#   Installation script for PiaF A2Billing, Jonathan Roper.
#   Copyright (C) <2009>  <Jonathan Roper>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.

#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#	 joe.roper@gmail.com

clear
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "This script assumes you have not changed the default root username For MySQL"
echo "If you have, e.g. if you use PBX-Management, press CTRL-C to exit"
echo "Then change the MySQL root password in the script to suit your installation."
echo " "
echo "If an earlier copy of A2Billing is already installed, then you should inspect"
echo "this script and modify it, or modify your installation before executing it."
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
read -p "Press any key to continue or ctrl-C to exit"

#Change passw0rd below for your MySQL root password if you have changed it from the default.
MYSQLROOTPASSWORD=passw0rd

echo "*************************************************************"
echo " Installing A2Billing - Downloading files from the internet"
echo ""
echo "                  Please be patient"
echo ""
echo "CAUTION, run this script only once - otherwise you will have"
echo "double entries in cron and extensions-a2billing.conf"
echo "*************************************************************"

mkdir /usr/src/a2billing
mkdir /var/www/html/a2billing

cd /usr/src/a2billing
wget http://www.asterisk2billing.org/downloads/A2Billing_1.4.1.tar.gz
tar zxfv A2Billing_1.4.1.tar.gz

cd /usr/src/a2billing/DataBase/mysql-5.x/

echo "GRANT ALL PRIVILEGES ON *.* TO 'a2billinguser'@'localhost' IDENTIFIED BY 'a2billing' WITH GRANT OPTION;" | mysql -p$MYSQLROOTPASSWORD
mysqladmin create mya2billing -u a2billinguser -pa2billing

echo ""
echo "Install A2Billing DataBase"
echo "Answer the questions appropriately with reference to /etc/a2billing.conf"
echo "-----------------------------"
echo ""

echo "Enter Database Name : "
read dbname

echo "Enter Hostname : "
read hostname

echo "Enter UserName : "
read username

echo "Enter Password : "
read password

echo mysql --user=$username --password=$password --host=$hostname $dbname

cat a2billing-schema-v1.4.0.sql UPDATE-a2billing-v1.4.0-to-v1.4.1.sql | mysql --user=$username --password=$password --host=$hostname $dbname

# cat a2billing-mysql-schema-v1.3.0.sql UPDATE-a2billing-v1.3.0-to-v1.3.1.sql UPDATE-a2billing-v1.3.3-to-v1.3.4.sql UPDATE-a2billing-v1.3.4-to-v1.4.0.sql a2billing-prefix-table-v1.4.0.sql UPDATE-a2billing-v1.4.0-to-v1.4.1.sql | mysql --user=$username --password=$password --host=$hostname $dbname

#Install some dependencies
yum -y install perl-DBD-Pg

cd /usr/src/a2billing

mv AGI/a2billing.php /var/lib/asterisk/agi-bin/.
cp -r common/lib /var/lib/asterisk/agi-bin

mv ./admin/ /var/www/html/a2billing/admin
mv ./customer/ /var/www/html/a2billing/customer
mv ./agent/ /var/www/html/a2billing/agent
mv ./common/ /var/www/html/a2billing/common
mv ./Cronjobs/ /var/lib/asterisk/agi-bin/lib/Cronjobs
mv a2billing.conf /etc/a2billing.conf

#Set up sounds
cd /usr/src/a2billing/addons/sounds

#Use this line for RPM based systems as Fedora, CentOS, etc
ast_sound=/var/lib/asterisk/sounds

#Use this line for Debian based systems
#ast_sound=/usr/share/asterisk/sounds

lang=en
echo
echo Install A2Billing Audio files : "$lang"
echo ---------------------------------------------------
echo creating relevant folders : $ast_sound/$lang
echo creating relevant folders : $ast_sound/$lang/digits

mkdir $ast_sound/$lang
mkdir $ast_sound/$lang/digits
echo Copy $lang files in the right folder ...

cp ./$lang/* $ast_sound/$lang/
cp ./global/* $ast_sound/$lang/

lang=es
echo
echo Install A2Billing Audio files : "$lang"
echo ---------------------------------------------------
echo creating relevant folders : $ast_sound/$lang
echo creating relevant folders : $ast_sound/$lang/digits

mkdir $ast_sound/$lang
mkdir $ast_sound/$lang/digits
echo Copy $lang files in the right folder ...

cp ./$lang/* $ast_sound/$lang/
cp ./global/* $ast_sound/$lang/

lang=fr
echo
echo Install A2Billing Audio files : "$lang"
echo ---------------------------------------------------
echo creating relevant folders : $ast_sound/$lang
echo creating relevant folders : $ast_sound/$lang/digits

mkdir $ast_sound/$lang
mkdir $ast_sound/$lang/digits
echo Copy $lang files in the right folder ...

cp ./$lang/* $ast_sound/$lang/
cp ./global/* $ast_sound/$lang/

lang=br
echo
echo Install A2Billing Audio files : "$lang"
echo ---------------------------------------------------
echo creating relevant folders : $ast_sound/$lang
echo creating relevant folders : $ast_sound/$lang/digits

mkdir $ast_sound/$lang
mkdir $ast_sound/$lang/digits
echo Copy $lang files in the right folder ...

cp ./$lang/* $ast_sound/$lang/
cp ./global/* $ast_sound/$lang/

lang=ru
echo
echo Install A2Billing Audio files : "$lang"
echo ---------------------------------------------------
echo creating relevant folders : $ast_sound/$lang
echo creating relevant folders : $ast_sound/$lang/digits

mkdir $ast_sound/$lang
mkdir $ast_sound/$lang/digits
echo Copy $lang files in the right folder ...

cp ./$lang/* $ast_sound/$lang/
echo Copy $lang digits files in the right folder ...
cp ./$lang/digits/* $ast_sound/$lang/digits/

cd /etc/asterisk/
touch additional_a2billing_iax.conf
touch additional_a2billing_sip.conf
touch extensions_a2billing.conf
touch iax_custom.conf

#set ownership and permissions

chown -R asterisk:asterisk /var/www/html
chown -R asterisk:asterisk /etc/asterisk
chown -R asterisk:asterisk /var/lib/asterisk/
chown -R asterisk:asterisk /var/www/html/a2billing/
chown -R asterisk:asterisk /var/lib/asterisk/sounds/
chown asterisk:asterisk /var/lib/asterisk/agi-bin/a2billing.php
chmod +x /var/lib/asterisk/agi-bin/a2billing.php

chmod 666 /etc/asterisk/additional_a2billing_iax.conf
chmod 666 /etc/asterisk/additional_a2billing_sip.conf
chmod 666 /etc/asterisk/extensions_a2billing.conf
chmod 666 /etc/a2billing.conf

#Fix the permissions of the templates_c folder in each of the UI

chmod 755 /var/www/html/a2billing/admin/templates_c
chmod 755 /var/www/html/a2billing/customer/templates_c
chmod 755 /var/www/html/a2billing/agent/templates_c
chown -R asterisk:asterisk /var/www/html/a2billing/admin/templates_c
chown -R asterisk:asterisk /var/www/html/a2billing/customer/templates_c
chown -R asterisk:asterisk /var/www/html/a2billing/agent/templates_c

#ensure all log files exist so we can set their permissions accordingly
touch /var/log/asterisk/a2billing-daemon-callback.log
touch /var/log/a2billing-daemon-callback.log
touch /var/log/cront_a2b_alarm.log
touch /var/log/cront_a2b_autorefill.log
touch /var/log/cront_a2b_batch_process.log
touch /var/log/cront_a2b_bill_diduse.log
touch /var/log/cront_a2b_subscription_fee.log
touch /var/log/cront_a2b_currency_update.log
touch /var/log/cront_a2b_invoice.log
touch /var/log/cront_a2b_check_account.log
touch /var/log/a2billing_paypal.log
touch /var/log/a2billing_epayment.log
touch /var/log/api_ecommerce_request.log
touch /var/log/api_callback_request.log
touch /var/log/a2billing_agi.log

echo "
#include additional_a2billing_sip.conf
" >> /etc/asterisk/sip_custom.conf
echo "
#include additional_a2billing_iax.conf
" >> /etc/asterisk/iax_custom.conf
echo "
#include extensions_a2billing.conf
" >> /etc/asterisk/extensions_custom.conf

echo '
[macro-dialout-trunk-predial-hook]
exten => s,1,GotoIf($["${OUT_${DIAL_TRUNK}:4:4}" = "A2B/"]?custom-freepbx-a2billing,${OUTNUM},1:2)
exten => s,2,MacroExit

[custom-freepbx-a2billing]
exten => _X.,1,DeadAGI(a2billing.php|${OUT_${DIAL_TRUNK}:8})
exten => _X.,n,Hangup()
' >> /etc/asterisk/extensions_custom.conf

#Create manager_custom.conf
echo "
[myasterisk]
secret = mycode
deny=0.0.0.0/0.0.0.0
permit=127.0.0.1/255.255.255.0
read = system,call,log,verbose,command,agent,user
write = system,call,log,verbose,command,agent,user
" >> /etc/asterisk/manager_custom.conf

#Add the A2Billing context

echo "
[a2billing]
exten => _X.,1,Answer
exten => _X.,n,Wait(1)
exten => _X.,n,deadAGI(a2billing.php|1)
exten => _X.,n,Hangup

[a2billing-callback]
exten => _X.,1,deadAGI(a2billing.php|1|callback)
exten => _X.,n,Hangup

[a2billing-cid-callback]
exten => _X.,1,deadAGI(a2billing.php|1|cid-callback|34) ;last #parameter is the callback area code
exten => _X.,n,Hangup

[a2billing-all-callback]
exten => _X.,1,deadAGI(a2billing.php|1|all-callback|34) ;last #parameter is the callback area code
exten => _X.,n,Hangup	

[a2billing-did]
exten => _X.,1,deadAGI(a2billing.php|1|did)
exten => _X.,2,Hangup

[a2billing-voucher]
exten => _X.,1,deadAGI(a2billing.php|1|voucher)
exten => _X.,n,Hangup

[custom-a2billing-did]
exten => _X.,1,deadAGI(a2billing.php|1|did)
exten => _X.,2,Hangup

[custom-a2billing]
exten => _X.,1,deadAGI(a2billing.php|1)
exten => _X.,n,Hangup

" >> /etc/asterisk/extensions_a2billing.conf

#Add some custom destinations to FreePBX
RESULT=`/usr/bin/mysql -uroot -p$MYSQLROOTPASSWORD <<SQL

use asterisk
INSERT INTO custom_destinations
	(custom_dest, description, notes)
	VALUES ('custom-a2billing,${EXTEN},1', 'A2Billing', '');
INSERT INTO custom_destinations
	(custom_dest, description, notes)
	VALUES ('custom-a2billing-did,${EXTEN},1', 'A2Billing-DID', '');
quit
SQL`

#set up crontabs for currency updates invoices and billing.
echo '0 1 * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/currencies_update_yahoo.php
0 6 1 * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_subscription_fee.php
0 12 * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_archive_data_cront.php
1 * * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_notify_account.php
0 6 * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_check_account.php
0 0 * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_bill_diduse.php
20 0 * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_batch_process.php
0 10 21 * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_autorefill.php
0 7 * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_invoice_cront.php
*/5 * * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_batch_autodialer.php
0 * * * * php /var/lib/asterisk/agi-bin/lib/Cronjobs/a2billing_alarm.php
' >> /var/spool/cron/asterisk

#Not required for PIAF, port already open
#Create fw rule to allow paypal to work
#iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

#save them
#service iptables save

#Set up callback
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "Now Installing Callback"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"

echo "Press any key to continue"
read any

LOAD_LOC=/usr/src/a2billing

yum -y install python-setuptools.noarch
yum -y install MySQL-python
easy_install sqlalchemy

cd $LOAD_LOC/CallBack/callback-daemon-py
cp callback_daemon/a2b-callback-daemon.rc /etc/init.d/a2b-callback-daemon
chmod +x /etc/init.d/a2b-callback-daemon

cp dist/callback_daemon-1.0.prod-r1528.tar.gz /tmp
cd /tmp
tar xvfz callback_daemon-1.0.prod-r1528.tar.gz
cd callback_daemon-1.0.prod-r1528

python setup.py build
python setup.py bdist_egg
easy_install dist/callback_daemon-1.0.prod_r1528-py2.4.egg

chkconfig --add a2b-callback-daemon
service a2b-callback-daemon start
chkconfig a2b-callback-daemon on

echo ""
echo ""
echo ""
echo ""
echo ""
echo "*******************************************************************"
echo "A2Billing is installed"
echo "-------------------------------------------------"
echo ""
echo "Please Reboot as soon as you are able"
echo ""
echo "*******************************************************************"
echo ""
echo "The default username is root"
echo "The default password is changepassword"
echo "Don't forget to configure /etc/a2billing.conf"
echo "*******************************************************************"

generate ssl certificate for squid

2011 November 10
Comments Off
Posted by shirker2006
mkdir /etc/squid/ssl
cd /etc/squid/ssl/
openssl genrsa -des3 -out squid.key 1024
openssl req -new -key squid.key -out squid.csr
cp squid.key squid.key.org
openssl rsa -in squid.key.org -out squid.key
openssl x509 -req -days 365 -in squid.csr -signkey squid.key -out squid.crt

edit squid.conf:

http_port 3128 transparent
https_port 3129 transparent key=/etc/squid/ssl/squid.key cert=/etc/squid/ssl/squid.crt
service squid restart

lsof (RUS)

2011 November 10
Comments Off
Posted by shirker2006

http://handynotes.ru/2010/01/unix-utility-lsof.html

Это третий пост из цикла статей о Unix и Linux утилитах о которых стоило бы знать. В этой статье я расскажу Вам о полезной утилите lsof. Если netcat был назван Швейцарским армейским ножем для сетевых соединений, то lsof можно назвать Швейцарским ножем для Unix отладки.

Lsof очень близко следует философии Unix. Он выполняет одну единственную задачу, но делает это превосходно — он предоставляет информацию о файлах открытых процессами. Открытый файл может быть обычным файлом, директорией, сетевым файлом NFS, специальным блоковым файлом, специальным символьным файлом, динамической библиотекой, обычным конвейером, именованным конвейером, символической ссылкой, потоковым сокетом, Интернет сокетом, сокетом UNIX домена, и многим другим. С тех пор как в Unix все что угодно – это файл, Вы можете себе представить насколько сподручным должен быть lsof!

Для того, что-бы проникнуться циклом статей о Unix утилитах, посмотрите первый пост о pipe viewer.

Как использовать lsof?

В этой статье я постараюсь преподнести функциональность lsof настолько, насколько позволяет мой опыт. Начнем с простого (что вероятно Вы уже знаете) и перейдем к сложному.

Список всех открытых файлов.

# lsof

Запустив lsof без каких-либо аргументов мы получим список всех открытых файлов всеми возможными процессами.

Посмотрим, кто использует файл.

# lsof /path/to/file

С файлом в качестве аргумента, lsof показывает все процессы, которые используют данный файл каким-либо образом.

Вы можете указать несколько файлов, и получите все процессы, которые используют данные файлы:

# lsof /path/to/file1 /path/to/file2

Рекурсивный поиск всех открытых файлов, начиная с указанной директории, выглядит вот так.

# lsof +D /usr/lib

С аргументом +D lsof ищет все файлы в указанной директории и всех поддиректориях.

Заметьте, что это будет работать медленнее чем с обычным grep:

# lsof | grep ‘/usr/lib’

Это медленнее потому что +D сперва ищет все файлы и только затем делает вывод.

Список всех файлов открытых пользователем.

# lsof -u pkrumins

Опция -u (думаю это user) ограничивает вывод файлов открытых пользователем pkrumins.

Вы можете использовать список разделенный запятой, если хотите узнать информацию сразу по нескольким пользователям:

# lsof -u rms,root

Этот пример покажет список файлов открытых пользователями rms и root.

По другому это можно сделать указав параметр -u дважды:

# lsof -u rms -u root

Найти все файлы открытые программой.

# lsof -c apache

Параметр -c выбирает список файлов принадлежащих процессу, чье имя начинается с apache.

Итак, вместо запуска:

# lsof | grep foo

Вы можете использовать более короткую версию:

# lsof -c foo

Как правило, Вы можете определить только начальные буквы имени процесса, который вы хотите обследовать:

# lsof -c apa

Эта команда выведет список всех файлов, открытых процессом начинающимся на apa.

Вы также можете указать несколько параметров -c для вывода файлов, открытых различными процессами:

# lsof -c apache -c python

Эта команда выведет список всех файлов, открытых процессами apache и python.

Список файлов открытых пользователем или процессом.

# lsof -u pkrumins -c apache

Опции Lsof могут комбинироваться. Действие по умолчанию между опциями определяется как ИЛИ. Это означает, что комбинация параметров -u pkrumins и -c apache выводит список файлов открытых пользователем pkrumins или процессом apache.
Список всех файлов открытых пользователем И процессом.

# lsof -a -u pkrumins -c bash

Параметр -a. Комбинирует опции с условием И. Выводится список файлов открытых bash, который запущен пользователем pkrumins.
Список всех файлов открытых всеми пользователями КРОМЕ root.

# lsof -u ^root

Заметьте, что символ ^ ставится до имени пользователя root. Этот трюк инвертирует совпадение для lsof на обратное, распечатывая все файлы пользователей отличных от root.
Список всех файлов открытых процессом с определенным PID.

# lsof -p 1

Параметр -p (думаю это PID) фильтрует вывод отображая список файлов открытых программой с указанным id.

Помните, что Вы можете выбрать разичные PID’ы используя либо список разделяемый запятой, либо используя несколько аргументов -p:

# lsof -p 450,980,333

Выбирает процессы с PID 450, 980 и 333.

Список всех открытых фалов за ИСКЛЮЧЕНИЕМ процесса с указанным PID.

# lsof -p ^1

Здесь снова используется инвертный оператор ^. Он инвертирует список и не включает в него процессы с PID 1.

Список всех сетевых соединений.

# lsof -i

Lsof с опцией -i выводит список всех Интернет сокетов (TCP и UDP).
Список всех TCP соединений.

# lsof -i tcp

Опция -i может иметь несколько различных параметров, один из них tcp. Опция tcp заставляет lsof выдавать список связанный только с TCP сокетами.

Список всех UDP соединений.

# lsof -i udp

Опция udp говорит lsof выводить список связанный только с UDP сокетами.

Кто использует этот порт.

# lsof -i :25

Опция :25 с -i заставляет lsof искать процессы использующие TCP или UDP с портом 25.

Вы также можете указать именованное название порта (смотрите /etc/services) вместо его номера:

# lsof -i :smtp

Найти, кто исопльзует данный UDP порт.

# lsof -i udp:53

Аналогично, найти, кто использует данный TCP порт:

# lsof -i tcp:80

Найти все сетевые действия пользователя.

# lsof -a -u hacker -i

Здесь опция -a комбинируется с -u и -i формируя список сетевых файлов используемых пользователем hacker.

Список всех файлов NFS (Network File System).

# lsof -N

Эту опцию легко запомнить, потому что -N это NFS.

Список всех файловых сокетов домена Unix.

# lsof -U

Эту опцию также легко запомнить, потому что -U это Unix.

Список всех файлов для процессов принадлежащих определенной группе id.

# lsof -g 1234

Групповые процессы используются для логической группировки процессов. Этот пример покажет список всех файлов открытых процессами принадлежащими к группе с PGID 1234.

Список всех файлов ассоциированных с указанным файловым дескриптором.

# lsof -d 2

Список всех файлов открытых файловым дескриптором с номером 2.

Вы можете задать интервал файловых дескрипторов:

# lsof -d 0-2

Список всех файлов с файловыми дескрипторами 0, 1 и 2.

Несколько специальных значений, таких как mem, которые работают с файлами отображаемыми в память:

# lsof -d mem

Или txt программ загруженных и выполняемых в памяти:

# lsof -d txt

Выводит PID’ы процессов использующих какие-то ресурсы.

# lsof -t -i

Опция -t выводит только PID’ы процессов. Используя совместно с -i это позволяет выводить PID’ы всех процессов с сетевыми соединениями. Так можно легко убить все процессы использующие сеть:

# kill -9 `lsof -t -i`

Повторяющийся листинг файлов.

# lsof -r 1

Аргумент -r заставляет lsof повторять список файлов, до тех пор пока он не будет остановлен. Аргумент 1 говорит, что необходимо повторять листинг через каждую секунду. Эту опцию лучше всего комбинировать с поисковым запросом, производящим мониторинг сетевой пользовательской активности:

# lsof -r 1 -u john -i -a

Как установить lsof?

Lsof уже предустановлена на большинстве Unix систем. Если в Вашей системе ее нет, попробуйте установить ее с исходных кодов.

BSD поддерживает собственную аналогичную утилиту, называемую fstat.

Полная документация для lsof содержится в man lsof, либо Вы можете вызвать lsof -h для получения небольшой шпаргалки.

Удачи в работе с lsof!

CentOS 5.2 and Asterisk 1.6.x installation (from voip-info.org)

2011 November 3
Comments Off
Posted by shirker2006

original here

cut and paste from here if you’re happy to install things you may or may not need.

yum -y install gcc gcc-c++ kernel-devel bison openssl openssl-devel perl perl-Net-SSLeay perl-Crypt-SSLeay libtermcap-devel ncurses-devel doxygen curl-devel newt-devel mlocate lynx tar wget nmap bzip2 mod_ssl crontabs vixie-cron speex speex-devel unixODBC unixODBC-devel libtool-ltdl libtool-ltdl-devel mysql-connector-odbc mysql mysql-devel mysql-server php-mysql php-mbstring php-mcrypt flex screen  libtiff-devel

Individual application specific dependencies

Asterisk

We’ve got to be able to compile it!

yum -y install gcc gcc-c++

Note that you may need to use the following if you are running a Xen enabled kernel:

yum -y install kernel-xen-devel

If you want the ‘zttool’ application, you’ll need to:

yum -y install newt-devel

Other things you may find useful (if they’re not already installed):

yum -y install mlocate lynx tar wget nmap bzip2 mod_ssl crontabs vixie-cron

Speex (optional)

Speex support depends on ‘speex_preprocess_ctl’ which is not available in the standard Speex packages. It may be possible to compile an older version of Speex if required.

ODBC stuff (optional)

Note that if you have already installed Asterisk, you will need to run ‘configure’, ‘make’ and ‘make install’ to detect ODBC and compile it in.

yum -y install unixODBC unixODBC-devel libtool-ltdl libtool-ltdl-devel

MySQL ODBC interface/connector (optional, but required if using ODBC and MySQL)

yum -y install mysql-connector-odbc

And then edit the file ‘/etc/odbcinst.ini’ (or ‘/usr/local/odbcinst.ini’) and replace ‘Driver = /usr/lib/libmyodbc.so’ with ‘Driver = /usr/lib/libmyodbc3.so’

MySQL (optional)

yum -y install mysql mysql-devel mysql-server
chkconfig mysqld on
service mysqld start

PHPMyAdmin (optional)

Download the latest version from http://www.phpmyadmin.net/, unzip/unbzip/untar into /var/www/htdocs/phpmyadmin (for the time being). Make sure Apache starts on boot.

yum -y install php-mysql php-mbstring php-mcrypt
chkconfig httpd on
service httpd start

Surf to https://i.p.address/phpmyadmin and check it works.

Webmin (optional)

If SSL is required, ensure that the correct bits are installed

yum -y install openssl openssl-devel perl perl-Net-SSLeay perl-Crypt-SSLeay

Download the latest version of the RPM from http://www.webmin.com/

rpm -i webmin-VERSION
chkconfig webmin on
service webmin start

Surf to https://i.p.address:10000 and check it works.

Download and install Asterisk and components

Download

Download the latest asterisk version /usr/src/asterisk and untar the files as follows:

mkdir -p /usr/src/asterisk
cd /usr/src/asterisk
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-1.6.1-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-addons-1.6.1-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz
wget http://soft-switch.org/downloads/spandsp/spandsp-0.0.6pre18.tgz (or most current version)
wget http://downloads.digium.com/pub/libpri/libpri-1.4-current.tar.gz
tar -zxf dahdi-linux-complete-current.tar.gz
tar -zxf asterisk-1.6.1-current.tar.gz
tar -zxf spandsp-0.0.6pre18.tgz
tar -zxf libpri-1.4-current.tar.gz
tar -zxf asterisk-addons-1.6.1-current.tar.gz

You’ll end up with five tar files and five directories in the directory ‘/usr/src/asterisk’.

SpanDSP (optional)

cd /usr/src/asterisk/spandsp-0.0.6
make clean
./configure
make
make install
cat > /etc/ld.so.conf.d/spandsp.conf << EOF
/usr/local
/usr/local/lib
EOF
ldconfig -v

Libpri (optional)

If you are using E1 cards you need to install LIBPRI. If you do want to use LIBPRI, make sure you compile and install it before you compile Asterisk. Replace ‘VERSION’ with the correct details.

cd /usr/src/asterisk/libpri-VERSION
make clean
make
make install

DAHDI

You’re pretty much going to need DAHDI. If not for any hardware then for the dummy timer anyway. Note that the stock CentOS kernels come with a 1000HZ timer and so don’t need recompiling (phew!). Replace ‘VERSION’ with the correct details.

cd /usr/src/asterisk/dahdi-linux-complete-VERSION
make all
make install
make config

Edit /etc/dahdi/modules, /etc/dahdi/system.conf and /etc/asterisk/chan_dahdi.conf for your site.
Set DAHDI to start automatically and then start it.

chkconfig dahdi on
service dahdi start

Asterisk

cd /usr/src/asterisk/asterisk-VERSION
make clean
./configure

Choose which options to install (audio files, voicemail storage, codecs etc.)

make menuselect
make
make install

Install sample files in /etc/asterisk, install docs/manpages and set to start on boot.

make samples
make progdocs
make config
chkconfig asterisk on

Check Asterisk starts properly:

asterisk -vvvvvvvvvvvvvvvvvvvc
stop now

If not, you’ve probably not been following these instructions carefully! Assuming it does start properly, you probably want to start it in the background:

service asterisk start

Asterisk-addons

cd /usr/src/asterisk/asterisk-addons-VERSION
make clean
./configure
make menuselect

Choose what you do and don’t want. Unless you really need oh323, deselect it as it can be the cause of compilation woes.

make
make install

Install sample files in /etc/asterisk

make samples

Edit /etc/asterisk/cdr_mysql.conf and add ‘loguniqueid=yes’ to the global section.

mISDN drivers for Digium B410P (optional)

Removed – have yet to test installation with DAHDI

Configure MySQL (optional)

The information below shows table definitions for all of the tables Asterisk can use with MySQL or ODBC.

Notes

The UniqueID field in the CDR table is not necessarily unique! Due to the very very dodgy way Asterisk handles unique IDs, if you set the field to be the primary key (as advised elsewhere), you will lose data.

SQL

Note that the SIP ‘qualify’ field has a default value set to ‘yes’. This is for two reasons. Firstly, I wrote these notes because it’s how I use and want to use Asterisk. Secondly, whether qualification is enabled or not in realtime is controlled by the ‘rtcachefriends’ setting in sip.conf – if it’s ‘no’, then whether ‘qualify’ is ‘yes’ or ‘no’ in the database is irrelevant. It makes sense therefore to enable it in the database and then turn it on or off with the ‘rtcachefriends’ setting.

SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;

    1. Database: `asterisk`

CREATE DATABASE `asterisk` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `asterisk`;

    1. Table structure for table `cdr`

CREATE TABLE IF NOT EXISTS `cdr` (
`recid` mediumint(8) unsigned NOT NULL auto_increment COMMENT ‘Record ID’,
`calldate` datetime NOT NULL default ’0000-00-00 00:00:00′,
`clid` varchar(80) NOT NULL default ”,
`src` varchar(80) NOT NULL default ”,
`dst` varchar(80) NOT NULL default ”,
`dcontext` varchar(80) NOT NULL default ”,
`channel` varchar(80) NOT NULL default ”,
`dstchannel` varchar(80) NOT NULL default ”,
`lastapp` varchar(80) NOT NULL default ”,
`lastdata` varchar(80) NOT NULL default ”,
`duration` int(11) NOT NULL default ’0′,
`billsec` int(11) NOT NULL default ’0′,
`disposition` varchar(45) NOT NULL default ”,
`amaflags` int(11) NOT NULL default ’0′,
`accountcode` varchar(20) NOT NULL default ”,
`uniqueid` varchar(32) NOT NULL default ”,
`userfield` varchar(255) NOT NULL default ”,
PRIMARY KEY (`recid`),
KEY `calldate` (`calldate`),
KEY `dst` (`dst`),
KEY `accountcode` (`accountcode`),
KEY `src` (`src`),
KEY `disposition` (`disposition`),
KEY `uniqueid` (`uniqueid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

    1. Table structure for table `queue_members`

CREATE TABLE IF NOT EXISTS `queue_members` (
`queue_name` varchar(128) NOT NULL default ”,
`interface` varchar(128) NOT NULL default ”,
`penalty` int(11) default NULL,
PRIMARY KEY (`queue_name`,`interface`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    1. Table structure for table `queues`

CREATE TABLE IF NOT EXISTS `queues` (
`name` varchar(128) NOT NULL,
`musiconhold` varchar(128) default ‘default’,
`announce` varchar(128) default NULL,
`context` varchar(128) default NULL,
`timeout` int(11) default ’60′,
`monitor_join` tinyint(1) default NULL,
`monitor_format` varchar(128) default NULL,
`queue_youarenext` varchar(128) default NULL,
`queue_thereare` varchar(128) default NULL,
`queue_callswaiting` varchar(128) default NULL,
`queue_holdtime` varchar(128) default NULL,
`queue_minutes` varchar(128) default NULL,
`queue_seconds` varchar(128) default NULL,
`queue_lessthan` varchar(128) default NULL,
`queue_thankyou` varchar(128) default NULL,
`queue_reporthold` varchar(128) default NULL,
`announce_frequency` int(11) default NULL,
`announce_round_seconds` int(11) default NULL,
`announce_holdtime` varchar(128) default NULL,
`periodic_announce` varchar(128) default NULL,
`periodic_announce_frequency` int(11) default NULL,

`retry` int(11) default ’5′,
`ringinuse` varchar(5) NOT NULL default ‘no’,
`autofill` varchar(5) NOT NULL default ‘yes’,
`autopause` varchar(5) NOT NULL default ‘no’,
`setinterfacevar` varchar(5) NOT NULL default ‘yes’,
`wrapuptime` int(11) default ’30′,
`maxlen` int(11) default NULL,
`servicelevel` int(11) default NULL,
`strategy` varchar(128) default ‘ringall’,
`joinempty` varchar(128) default ‘no’,
`leavewhenempty` varchar(128) default ‘yes’,
`eventmemberstatus` tinyint(1) default NULL,
`eventwhencalled` tinyint(1) default NULL,
`reportholdtime` tinyint(1) default NULL,
`memberdelay` int(11) default NULL,
`weight` int(11) default NULL,
`timeoutrestart` tinyint(1) default NULL,
PRIMARY KEY (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    1. Table structure for table `sip`

CREATE TABLE IF NOT EXISTS `sip` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(80) NOT NULL,
`host` varchar(31) NOT NULL default ‘dynamic’,
`nat` varchar(5) NOT NULL default ‘no’,
`type` enum(‘user’,'peer’,'friend’) NOT NULL default ‘friend’,
`accountcode` varchar(20) default ‘ACCOUNT’,
`amaflags` varchar(13) default NULL,
`callgroup` varchar(10) default NULL,
`callerid` varchar(80) default NULL,
`call-limit` varchar(6) NOT NULL default ’10′,
`cancallforward` char(3) default ‘yes’,
`canreinvite` char(3) default ‘no’,
`context` varchar(80) default ‘from-sip’,
`defaultip` varchar(15) default NULL,
`dtmfmode` varchar(7) default ‘rfc2833′,
`fromuser` varchar(80) default NULL,
`fromdomain` varchar(80) default NULL,
`insecure` varchar(4) default NULL,
`language` char(2) default ‘en’,
`mailbox` varchar(50) default NULL,
`md5secret` varchar(80) default NULL,
`deny` varchar(95) default ’0.0.0.0/0.0.0.0′,
`permit` varchar(95) default ’0.0.0.0/0.0.0.0′,
`mask` varchar(95) default NULL,
`musiconhold` varchar(100) default ‘default’,
`pickupgroup` varchar(10) default NULL,
`qualify` char(3) default ‘yes’,
`regexten` varchar(80) default NULL,
`restrictcid` char(3) default NULL,
`rtptimeout` char(3) default NULL,
`rtpholdtimeout` char(3) default NULL,
`secret` varchar(80) default ‘SECRET’,
`setvar` varchar(100) default NULL,
`disallow` varchar(100) default ‘all’,
`allow` varchar(100) default ‘alaw’,
`fullcontact` varchar(80) NOT NULL default ”,
`ipaddr` varchar(15) NOT NULL default ”,
`port` smallint(5) unsigned NOT NULL default ’0′,
`regserver` varchar(100) default NULL,
`regseconds` int(11) NOT NULL default ’0′,
`username` varchar(80) NOT NULL,
`defaultuser` varchar(80) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `name_2` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC AUTO_INCREMENT=301 ;

    1. Table structure for table `voicemail_messages`

CREATE TABLE IF NOT EXISTS `voicemail_messages` (
`id` int(11) NOT NULL auto_increment,
`msgnum` int(11) NOT NULL default ’0′,
`dir` varchar(80) default ”,
`context` varchar(80) default ”,
`macrocontext` varchar(80) default ”,
`callerid` varchar(40) default ”,
`origtime` varchar(40) default ”,
`duration` varchar(20) default ”,
`mailboxuser` varchar(80) default ”,
`mailboxcontext` varchar(80) default ”,
`recording` longblob,
PRIMARY KEY (`id`),
KEY `dir` (`dir`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1088 ;

    1. Table structure for table `voicemail_users`

CREATE TABLE IF NOT EXISTS `voicemail_users` (
`uniqueid` int(11) NOT NULL auto_increment,
`customer_id` varchar(11) NOT NULL default ’0′,

`context` varchar(50) NOT NULL default ‘default’,
`mailbox` varchar(11) NOT NULL default ’0′,
`password` varchar(5) NOT NULL default ’6666′,
`fullname` varchar(150) NOT NULL,
`email` varchar(50) NOT NULL,
`pager` varchar(50) NOT NULL,
`tz` varchar(10) NOT NULL default ‘en’,
`attach` varchar(4) NOT NULL default ‘yes’,
`saycid` varchar(4) NOT NULL default ‘yes’,
`dialout` varchar(10) NOT NULL,
`callback` varchar(10) NOT NULL,
`review` varchar(4) NOT NULL default ‘no’,
`operator` varchar(4) NOT NULL default ‘no’,
`envelope` varchar(4) NOT NULL default ‘no’,
`sayduration` varchar(4) NOT NULL default ‘no’,

`saydurationm` tinyint(4) NOT NULL default ’1′,
`sendvoicemail` varchar(4) NOT NULL default ‘no’,
`delete` varchar(4) NOT NULL default ‘no’,
`nextaftercmd` varchar(4) NOT NULL default ‘yes’,
`forcename` varchar(4) NOT NULL default ‘no’,
`forcegreetings` varchar(4) NOT NULL default ‘no’,
`hidefromdir` varchar(4) NOT NULL default ‘yes’,
`stamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`uniqueid`),
KEY `mailbox_context` (`mailbox`,`context`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=101 ;

    1. ########################################################
    1. Create realtime user with approximately the right privs.

CREATE USER ‘astrealtime’@'localhost’ IDENTIFIED BY ‘MYPASS’;
GRANT FILE ON * . * TO ‘astrealtime’@'localhost’ IDENTIFIED BY ‘MYPASS’ WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
GRANT INSERT ON `asterisk`.`cdr` TO ‘astrealtime’@'localhost’;
GRANT SELECT , INSERT , UPDATE , DELETE ON `asterisk`.`queue_members` TO ‘astrealtime’@'localhost’;
GRANT SELECT , UPDATE ON `asterisk`.`queues` TO ‘astrealtime’@'localhost’;
GRANT SELECT , UPDATE ON `asterisk`.`sip` TO ‘astrealtime’@'localhost’;
GRANT SELECT , UPDATE ON `asterisk`.`voicemail_users` TO ‘astrealtime’@'localhost’;
GRANT SELECT , UPDATE , INSERT , DELETE ON `asterisk`.`voicemail_messages` TO ‘astrealtime’@'localhost’;

Configure various files

Set up CDR to MySQL

Edit /etc/asterisk/cdr_mysql.conf
[global]
hostname=localhost
dbname=asterisk
table=cdr
password=MYPASS
user=astrealtime
port=3306
sock=/var/lib/mysql/mysql.sock
userfield=1

Set up realtime

Edit res_mysql.conf
[general]
dbhost = localhost
dbname = asterisk
dbuser = astrealtime
dbpass = MYPASS
dbport = 3306
dbsock = /var/lib/mysql/mysql.sock

If you are using version 1.6.0 or lower

Edit /etc/asterisk/extconfig.conf
[settings]
queues => mysql,asterisk,queues
queue_members => mysql,asterisk,queue_members
sippeers => mysql,asterisk,sip
sipusers => mysql,asterisk,sip
voicemail => mysql,asterisk,voicemail_users

If you are using version 1.6.1 or higher

Edit /etc/asterisk/extconfig.conf
[settings]
queues => mysql,asterisk,queues
queue_members => mysql,asterisk,queue_members
sippeers => mysql,asterisk,sip
sipusers => mysql,asterisk,sip
voicemail => mysql,asterisk,voicemail_users

If mysql db resides on a different host than asterisk, you will want to use “general” for the database parameter, instead of “asterisk” in extconfig.conf

Note – You may see documentation stating that whatever is in the [] section of res_mysql.conf is to be used for the “database” field in these extconfig parameters. For example
queues => mysql,general,queues … This seems to be false, at least in version 1.6.2.10, and you should in fact use the database name referenced in “dbname” in res_mysql.config

ODBC configuration (using settings from above)

/etc/odbcinst.ini

[MySQL]
Description = ODBC for MySQL
Driver = /usr/lib/libmyodbc3.so
;For x64 systems
;Driver = /usr/lib64/libmyodbc3.so
Setup = /usr/lib/libodbcmyS.so
FileUsage = 1
(Note the ’3′ which isn’t in the original sample file!)

/etc/odbc.ini

; DSN definitions
[astrealtime]
Description = Asterisk realtime and other FUNC_ODBC access
Driver = MySQL
Socket = /var/lib/mysql/mysql.sock
Server = localhost
User = astrealtime
Pass = MYPASS
Database = asterisk
Option = 3

/etc/asterisk/res_odbc.conf

; Environment variables
[ENV]

; Connections
[astrealtime]
enabled => yes
dsn => astrealtime
username => astrealtime
password => MYPASS
pre-connect => yes
idlecheck => 3600

/etc/asterisk/func_odbc.conf

This really depends on why you need database access from the dialplan!

Setting up Asterisk on a vserver

Removed – have yet to test installation with DAHDIn

Troubleshooting:

If sip phones are not registering to asterisk and you receive 408 request timeout, you may need to alter iptables.
iptables -I RH-Firewall-1-INPUT -p udp –dport 5060 -j ACCEPT
iptables -I RH-Firewall-1-INPUT -p udp –dport 10000:20000 -j ACCEPT
service iptables save

See Also

Centos 5. yum install asterisk from asterisk repo

2011 November 3
Comments Off
Posted by shirker2006
vim /etc/yum.repos.d/centos-asterisk.repo
[asterisk-tested]
name=CentOS-$releasever - Asterisk - Tested
baseurl=http://packages.asterisk.org/centos/$releasever/tested/$basearch/
enabled=0
gpgcheck=0
#gpgkey=http://packages.asterisk.org/RPM-GPG-KEY-Digium

[asterisk-current]
name=CentOS-$releasever - Asterisk - Current
baseurl=http://packages.asterisk.org/centos/$releasever/current/$basearch/
enabled=1
gpgcheck=0
#gpgkey=http://packages.asterisk.org/RPM-GPG-KEY-Digium
vim /etc/yum.repos.d/centos-digium.repo
[digium-tested]
name=CentOS-$releasever - Digium - Tested
baseurl=http://packages.digium.com/centos/$releasever/tested/$basearch/
enabled=0
gpgcheck=0
#gpgkey=http://packages.digium.com/RPM-GPG-KEY-Digium

[digium-current]
name=CentOS-$releasever - Digium - Current
baseurl=http://packages.digium.com/centos/$releasever/current/$basearch/
enabled=1
gpgcheck=0
#gpgkey=http://packages.digium.com/RPM-GPG-KEY-Digium

At this point your system has been updated to use the Asterisk and Digium repositories in addition to the base CentOS repositories. You are now ready to install Asterisk. To start the installation, execute the following at the Linux command line:

yum -y update
yum search asterisk
[root@localhost~]# yum install asterisk16 asterisk16-configs asterisk16-voicemail dahdi-linux
dahdi-tools libpri

Bash script for update data at dnsdynamic.org

2011 November 2
Comments Off
Posted by shirker2006

Put your Username and Password for dnsdynamic.org.

[root@asterisk-21 scripts]# cat /var/scripts/dnsdynamic.sh
#!/bin/bash
IP=`/usr/bin/GET https://myip.dnsdynamic.org`
USER="USER@gmail.com"
PASSWD="SECRET"
sleep 10
    for i in `cat /var/scripts/dnsdynamic.org.lst`;
        do /usr/bin/GET -C ${USER}:${PASSWD} https://www.dnsdynamic.org/api/?hostname=$i\&myip=${IP};
        echo "Update domain $i to IP address ${IP}";
        sleep 5;
    done;

put to /var/scripts/dnsdynamic.org.lst your domain names list. each one from new line:

echo "asterisk21.voip01.com" >> dnsdynamic.org.lst
echo "yourdomain.http01.com" >> dnsdynamic.org.lst

Настройка VPN (PPTP) Подключения CentOS

2011 October 28
Comments Off
Posted by shirker2006

Установка пакетов

  1. Подключите репозиторий EPEL;
  2. Установите пакет pptp.

Настройка подключения

/etc/ppp/chap-secrets

# client        server  secret                  IP addresses
USERNAME          *       PASSWORD                 *

/etc/ppp/options

lock

/etc/ppp/peers/PROVIDER_NAME

pty "/usr/sbin/pptp VPN_SERVER --nolaunchpppd"
debug
lock
lcp-echo-interval 30
lcp-echo-failure 4
noipdefault
defaultroute
usepeerdns
persist
refuse-eap
refuse-mschap

# Turn off compression protocols we know won't be used
nobsdcomp
nodeflate

# Require MPPE 128-bit encryption
#mppe required,stateless

# Удаляем шлюз по умолчанию вручную, чтобы заменить его шлюзом VPN-сервера
connect "/etc/ppp/scripts/ppp_remove_default_route.sh"

/etc/ppp/scripts/ppp_remove_default_route.sh

1. Создайте файл /etc/ppp/scripts/ppp_remove_default_route.sh:

logger -t 'ppp_remove_default_route.sh' 'executing...'
/sbin/ip r del default
exit 0

2. Исправьте права доступа:

# chmod 755 /etc/ppp/scripts/ppp_remove_default_route.sh

/etc/sysconfig/network-scripts/ifcfg-PROVIDER_NAME

DEVICE=ppp0
TYPE=Modem
BOOTPROTO=dialup
ONBOOT=no
USERCTL=yes
PEERDNS=no
PROVIDER=PROVIDER_NAME
DEFROUTE=yes
PERSIST=yes
PAPNAME=USERNAME
DEMAND=no

Настройка автоматического запуска при загрузке ОС

При загрузке ОС если не удается системе установить подключение к VPN-серверу в течение определенного времени – попытки подключения к VPN-серверу прекращаются и далее система автоматически не переподключается к VPN-серверу.

Если необходимо обязательно подключиться к VPN-серверу при запуске ОС – выполните следующие действия:

1. Создайте скрипт /etc/init.d/fireup_inet:

# Start fireup_inet script
#
# chkconfig:    14 14 00
# description:  Start fireup_inet script
#
# Source function library.
. /etc/rc.d/init.d/functions

fireup_start() {
   echo "Stopping PROVIDER_NAME..."
   /sbin/ifdown PROVIDER_NAME
   echo "Starting PROVIDER_NAME..."
   /sbin/ifup PROVIDER_NAME
}

case "$1" in
   start)
        action=run
        fireup_start
        action "" /bin/true
        exit 0
        ;;
   stop)
      ;;
   *)
        echo $"Usage: $0 {start}"
        exit 1
esac

2. Исправьте права доступа:

# chmod 755 /etc/init.d/fireup_inet

3. Настройте автоматический запуск скрипта при запуске ОС:

# chkconfig --level 35 fireup_inet on

Подключение к VPN-серверу

# /sbin/ifup PROVIDER_NAME

Отключение от VPN-сервера

# /sbin/ifdown PROVIDER_NAME

Просмотр журнальных файлов

$ egrep '(ppp|pptp)' /var/log/messages

Примечания

  • VPN_SERVER – доменное имя или IP-адрес VPN-сервера;
  • USERNAME – имя пользователя;
  • PASSWORD – пароль пользователя;
  • PROVIDER_NAME – название провайдера.

http://redhat-club.org/2011/%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0-vpn-pptp-%D0%BF%D0%BE%D0%B4%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%BD%D0%B8%D1%8F

php script. connect to website by SSL, and update IP address

2011 October 23
Comments Off
Posted by shirker2006

Of course, this script so far from professional, but its still working. So if u can improve it – always welcome

Im using dynamic IP, but for SONOVOIP they want you to set static IP. Before i had to everyday update it in control panel. Now i made this script to find my external IP, connect by ssl to their website and update information automatically. As well i have 25port blocked, so to send email im using google

<?php

require_once "Mail.php";
 $from = "<USERNAME>@gmail.com";
 $to = "<USERNAME>@gmail.com";
 $subject = "Sonovoip update filed!";
 $body = "SONOVOIP UPDATE UNSUCCESSFUL!!!";
 $host = "ssl://smtp.gmail.com";
 $port = "465";
 $username = "<USERNAME>@gmail.com";
 $password = "<PASSWD>";
 $successmsg = "<p><b>Message successfully sent to $to!</b></p>";

 $headers = array ('From' => $from,
                   'To' => $to,
                   'Subject' => $subject);
 $smtp = Mail::factory('smtp',
     array ('host' => $host,
            'port' => $port,
            'auth' => true,
            'username' => $username,
            'password' => $password));

$content = file_get_contents("http://www.ipaddrs.com/");

$start = strpos($content,"<h1>");
$end = strpos($content,"</h1>");
$start = $start+4;
$end = $end-$start;
$our_ip = substr($content,$start,$end);

echo $our_ip."<br>";

$num = "(25[0-5]|2[0-4]\d|[01]?\d\d|\d)" ; 

if ( !preg_match ( "/^$num\\.$num\\.$num\\.$num$/" , $our_ip )) {

$mail = $smtp->send($to, $headers, $body);

        if (PEAR::isError($mail)) {
          echo("<p>" . $mail->getMessage() . "</p>");
         } else {
          echo("$successmsg");
         }

die("Wrong IP Address") ; 

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
$postvars = array(

  "name" => "<SONOVOIPUSERNAME>",

  "pass" => "<SONOVOIPPASSWD>",

  "form_id" => "user_login",

  "op" => "Log+in"

);

$postdata = "";

foreach ( $postvars as $key => $value )

    $postdata .= "&".rawurlencode($key)."=".rawurlencode($value);

$postdata = substr( $postdata, 1 );

echo $postdata."<p>";

	if ($fp = fsockopen ("ssl://www.sonovoip.com", 443))
		{
			$request2 = "POST /user/login HTTP/1.1\r\n";
                     $request2.= "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel,
                                 application/vnd.ms-powerpoint, application/msword, application/xaml+xml,
                                 application/vnd.ms-xpsdocument, application/x-ms-application, application/x-shockwave-flash, */*\r\n";
                     $request2.= "Referer: https://www.sonovoip.com/user/login\r\n";
			$request2.= "Accept-Language: en_US\r\n";
			$request2.= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 GTB5 (.NET CLR 3.5.30729)\r\n";
			$request2.= "Content-Type: application/x-www-form-urlencoded\r\n";
                     $request2.= "Accept-Encoding: gzip,deflate\r\n";
			$request2.= "Host: www.sonovoip.com\r\n";
                     $request2.= "Content-Length: ".strlen($postdata)."\r\n";
                     $request2.= "Connection: Keep-Alive\r\n";
                     $request2.= "Cache-Control: no-cache\r\n\r\n";
                     $request2.= $postdata."\r\n\r\n";

		$response2 ='';

		fwrite($fp, $request2);
			while (!feof($fp)) {
			$response2.=fread($fp,4096);
			}

	    fclose($fp);
   }

echo $response2."<p>";

$start = strrpos($response2,"Set-Cookie:");
$end = strrpos($response2,"path=");
$start = $start+12;
$end = $end-$start;
$cookie = substr($response2,$start,$end);
echo $cookie;

////////////////////////////////////////////////////////////////////////

	if ($fp = fsockopen ("ssl://www.sonovoip.com", 443))
		{
			$request3 = "GET /member/services/edit/1 HTTP/1.1\r\n";
                     $request3.= "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel,
                                 application/vnd.ms-powerpoint, application/msword, application/xaml+xml,
                                 application/vnd.ms-xpsdocument, application/x-ms-application, application/x-shockwave-flash, */*\r\n";
                     $request3.= "Referer: https://www.sonovoip.com/member/services/edit/1\r\n";
			$request3.= "Accept-Language: en_US\r\n";
			$request3.= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3
                                 GTB5 (.NET CLR 3.5.30729)\r\n";
                     $request3.= "Content-Type: application/x-www-form-urlencoded\r\n";
			$request3.= "Host: www.sonovoip.com\r\n";

                     $request3.= "Connection: Keep-Alive\r\n";
                     $request3.= "Cache-Control: no-cache\r\n";
                     $request3.= "Cookie: ".$cookie."\r\n\r\n";

		$response3 ='';

		fwrite($fp, $request3);
			while (!feof($fp)) {
			$response3.=fread($fp,4096);
			}

	    fclose($fp);
   }

echo $request3."<p><p>";

$response_start = strpos($response3,"form_build_id");

$response_end = strpos($response3,"edit_service_form");

$response_end = $response_end-$response_start;
$response3 = substr($response3,$response_start,$response_end);

$start = strpos($response3,"value=");
$end = strpos($response3,"  />");
$start = $start+7;
$end = $end-$start-1;
$form_build_id = substr($response3,$start,$end);
echo "form_build_id = ".$form_build_id;
echo "<br><p>";

$start2 = strpos($response3,"token\" value=");
$end2 = strrpos($response3,"  />");
$start2 = $start2+14;
$end2 = $end2-$start2-1;
$form_token = substr($response3,$start2,$end2);
echo "form_token = ".$form_token;

////////////////////////////////////////////////////////////////////////
$postvars2 = array(

  "label" => "<COMPANYNAME>",

  "service_type_id" => "1",

  "signaling_ip" => $our_ip,

  "media_ip" => "",

  "manufacturer" => "Asterisk",

  "version" => "1.6",

  "protocol" => "2",

  "codec1_id" => "3",

  "op" => "Save",

  "form_build_id" => $form_build_id,

  "form_token" => $form_token,

  "form_id" => "edit_service_form"

);

$postdata2 = "";

foreach ( $postvars2 as $key => $value )

    $postdata2 .= "&".rawurlencode($key)."=".rawurlencode($value);

$postdata2 = substr( $postdata2, 1 );

echo $postdata2."<p>";

	if ($fp = fsockopen ("ssl://www.sonovoip.com", 443))
		{
			$request3 = "POST /member/services/edit/1 HTTP/1.1\r\n";
                     $request3.= "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel,
                                 application/vnd.ms-powerpoint, application/msword, application/xaml+xml,
                                 application/vnd.ms-xpsdocument, application/x-ms-application, application/x-shockwave-flash, */*\r\n";
                     $request3.= "Referer: https://www.sonovoip.com/member/services/edit/1\r\n";
			$request3.= "Accept-Language: en_US\r\n";
			$request3.= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3
                                 GTB5 (.NET CLR 3.5.30729)\r\n";
                     $request3.= "Content-Type: application/x-www-form-urlencoded\r\n";
			$request3.= "Host: www.sonovoip.com\r\n";
                     $request3.= "Content-Length: ".strlen($postdata2)."\r\n";
                     $request3.= "Connection: Keep-Alive\r\n";
                     $request3.= "Cache-Control: no-cache\r\n";
                     $request3.= "Cookie: ".$cookie."\r\n\r\n";
                     $request3.= $postdata2."\r\n\r\n";

		$response3 ='';

		fwrite($fp, $request3);
			while (!feof($fp)) {
			$response3.=fread($fp,4096);
			}

	    fclose($fp);
   }

echo $request3."<p><p>";
echo $response3;

$message = $postdata2."\r\n\r\n";
$message.= $request3."\r\n\r\n";
$message.= $response3."\r\n\r\n";

 $from = "<USERNAME>@gmail.com";
 $to = "<USERNAME>@gmail.com";
 $subject = "Update sonovoip to $our_ip";
 $body = $message;
 $host = "ssl://smtp.gmail.com";
 $port = "465";
 $username = "<USERNAME>@gmail.com";
 $password = "<PASSWD>";
 $successmsg = "<p><b>Message successfully sent to $to!</b></p>";

 $headers = array ('From' => $from,
                   'To' => $to,
                   'Subject' => $subject);
 $smtp = Mail::factory('smtp',
     array ('host' => $host,
            'port' => $port,
            'auth' => true,
            'username' => $username,
            'password' => $password));

$mail = $smtp->send($to, $headers, $body);

    if (PEAR::isError($mail)) {
          echo("<p>" . $mail->getMessage() . "</p>");
         } else {
          echo("$successmsg");
         }

?>

loading from csv file to MySQL table (variants)

2011 October 19
Comments Off
Posted by shirker2006
mysql> use 'LEADS';
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> load data local infile /tmp/bc-res.csv into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/tmp/bc-res.csv into table `Canada_Consumers_2008` fields terminated by ',' encl' at line 1
mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 65536 rows affected (0.24 sec)
Records: 65536  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1 row affected (0.32 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1 row affected (0.35 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1 row affected (0.39 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1 row affected (0.34 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1 row affected (0.34 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' lines terminated by '\r\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1 row affected (0.30 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> load data local infile '/tmp/bc-res.csv' into table `Canada_Consumers_2008` fields terminated by ',' lines terminated by '\n' (Last_Name, Address, city, state, zipcode, phone) ;
Query OK, 1196499 rows affected (4.29 sec)
Records: 1196499  Deleted: 0  Skipped: 0  Warnings: 0

smartmontools (RUS) howto check HDD in linux

2011 October 14
Comments Off
Posted by shirker2006

http://ru.gentoo-wiki.com/wiki/%D0%9C%D0%BE%D0%BD%D0%B8%D1%82%D0%BE%D1%80%D0%B8%D0%BD%D0%B3_%D0%B6%D0%B5%D1%81%D1%82%D0%BA%D0%B8%D1%85_%D0%B4%D0%B8%D1%81%D0%BA%D0%BE%D0%B2_(smartmontools)

Easy Guide for Successful Vtiger Integration in VicidialNOW

2011 October 13
Comments Off
Posted by shirker2006

Hi All,

I have been a part of this community for a few months now. There are few common configuration problems for new user after successful install. Among those one is integration of VTIGER. I did this integration for quite a few times without any problem. I decided to share my guide with others. If admins like this guide they may decide to make this sticky for others.

There are three things in this guide
1-For MySQL
2-Installation of Vtigercrm 5.0.4
3-Integration with VICIDIALNOW VERSION: 2.0.5-173

Let we take these steps one by one.

1-For MySQL

Code:
#mysql -u root -p   (it will ask for root password default is vicidialnow)
mysql>GRANT ALL on vtigercrm504.* TO vtiger@’%’ IDENTIFIED BY ‘vtuser’;
mysql>GRANT ALL on vtigercrm504.* TO vtiger@localhost IDENTIFIED BY ‘vtuser’;
mysql>create database vtigercrm504;
mysql>quit

2-Installation of Vtigercrm 5.0.4

Code:
#cd /var/www/html
#rm -r -f vtigercrm
#wget http://voxel.dl.sourceforge.net/sourceforge/vtigercrm/vtigercrm-5.0.4.tar.gz
#gunzip vtigercrm-5.0.4.tar.gz
#tar xvf vtigercrm-5.0.4.tar
#chmod -R 0777 vtigercrm
#cd vtigercrm

* in browser go to the following URL: http://ip-address/vtigercrm/index.php
* enter contact info and click the START button at the bottom of the screen
* in system configuration set the database host to: <ip-address>
* database user/pass: vtiger/vtuser
* database name: vtigercrm504
* change default admin(vtadmin) and standarduser(vtuser) passwords
* click to install vtiger, then follow the on-screen instructions

After successful install it will ask for login into vtiger crm, you can login to test if everything is fine. Password for admin to login is “vtadmin”, we have choosen this in aboive step.

Now we have to patch this new install of vtiger to work with VICIDIALNOW
Note: Make sure to execute these commands in vtigercrm folder

Code:
#wget http://www.eflo.net/files/Vtiger504_vicidial.patch
#patch -p1 < ./Vtiger504_vicidial.patch

After this goto admin interface for integration and user synchronization
Admin->System Settings

3-Integration with VICIDIALNOW

Code:
Enable Vtiger Integration:  1
Vtiger DB Server IP: <your ip>
Vtiger DB Name: vtigercrm504
Vtiger DB Login: vtiger
Vtiger DB Password: vtuser
Vtiger URL: <yout ip>/vtigercrm

Submit setting and click “Click here to Synchronize users with Vtiger”

This will synchronize all users with VTIGER

Note: After synchronization your VTIGER admin password is replaced wih your VICIDIALNOW admin password.

I hope this will help for all beginners like me

Best regards,

http://www.eflo.net/VICIDIALforum/viewtopic.php?t=8779&sid=5d4c7c34acc71c8aa56cf448114e561a

php hosting: disabled finctions

2011 October 8
Comments Off
Posted by shirker2006

Disable functions :exec, shell_exec, passthru, system, proc_open, proc_nice, proc_close, proc_get_status, proc_terminate, popen, pclose, posix, pcntl, expect, posix_ctermid, posix_errno, posix_get_last_error, posix_getcwd, posix_getegid, posix_geteuid, posix_getgid, posix_getgrgid, posix_getgrnam, posix_getgroups, posix_getlogin, posix_getpgid, posix_getpgrp, posix_getpid, posix_getppid, posix_getpwnam, posix_getpwuid, posix_getrlimit, posix_getsid, posix_getuid, posix_initgroups, posix_isatty, posix_kill, posix_mkfifo, posix_mknod, posix_setegid, posix_seteuid, posix_setgid, posix_setpgid, posix_setsid, posix_setuid, posix_strerror, posix_times, posix_ttyname, posix_uname
Free space : 0 B Total space: 0 B

Howto save iptables NAT rules to /etc/sysconfig/iptables

2011 October 6
Comments Off
Posted by shirker2006

Hi
How can I add the following in /etc/sysconfig/iptables ? The format of the file doesnt seem to allow this…

/sbin/iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
echo "1"> /proc/sys/net/ipv4/ip_forward

__________________

Hi
Code:

service iptables save

saves the output of iptables-save to /etc/sysconfig/iptables
Quote:

net.ipv4.ip_forward = 1

in the file /etc/sysctl.conf enables forwarding

http://forums.fedoraforum.org/showthread.php?t=181765

Useful cisco command (RUS)

2011 September 30
Comments Off
Posted by shirker2006

http://sysadminblog.ru/cisco/2010/03/30/poleznye-komandy-v-cisco-ios-1.html

Как смотреть трафик на интерфейсе, кто больше всех грузит интерфейс, что качается в данный момент?
Для этого на физическом интерфейсе нужно включить netflow

interface giga0/0  ip address 10.0.0.1 255.255.255.252  ip flow ingress  ip flow egress

теперь можно смотреть что происходит на интерфейсе командой sh ip cache flow

cisco#sh ip cache flow IP packet size distribution (608771 total packets):    1-32   64   96  128  160  192  224  256  288  320  352  384  416  448  480    .002 .406 .090 .012 .006 .006 .003 .003 .005 .005 .003 .012 .006 .004 .004     512  544  576 1024 1536 2048 2560 3072 3584 4096 4608    .003 .005 .392 .008 .014 .000 .000 .000 .000 .000 .000 IP Flow Switching Cache, 278544 bytes   145 active, 3951 inactive, 7083 added   187400 ager polls, 0 flow alloc failures   Active flows timeout in 30 minutes   Inactive flows timeout in 15 seconds IP Sub Flow Cache, 25800 bytes   0 active, 1024 inactive, 0 added, 0 added to flow   0 alloc failures, 0 force free   1 chunk, 1 chunk added   last clearing of statistics never Protocol         Total    Flows   Packets Bytes  Packets Active(Sec) Idle(Sec) --------         Flows     /Sec     /Flow  /Pkt     /Sec     /Flow     /Flow TCP-WWW           2372      0.0        98   388      0.5       4.1       3.2 TCP-other         3649      0.0        53   383      0.4      12.0      13.9 UDP-DNS             48      0.0         1    62      0.0       0.0      15.8 UDP-NTP              4      0.0         1    76      0.0       0.0      15.2 UDP-other          126      0.0        34    62      0.0       4.6      15.6 ICMP               745      0.0         1    33      0.0       0.3      15.5 Total:            6944      0.0        62   381      1.0       7.8      10.4 SrcIf         SrcIPaddress    DstIf         DstIPaddress    Pr SrcP DstP  Pkts Gi0/1         10.0.1.2        Vl40*         10.1.0.1        06 AE22 0CE3     1 Gi0/1         10.0.0.2        Vl40*         10.1.0.1        06 0DB3 0050   225 ... и т.д. 

Можно делать выборки из выдачи этой команды, например sh ip cache flow | i 10.0.1, чтобы не смотреть иногда тысячи строк, которые в данный момент не интересны.
Если интересно посмотреть посмотреть, кто же создает максимальный трафик, необходимо следующее

ip flow-top-talkers  top 10  sort-by bytes  cache-timeout 100

Теперь командой sh ip flow top-talkers можно смотреть качающие хосты.

Надеюсь к моему начинанию присоединятся другие админы, которым тоже есть чем помочь коллегам ;-)

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

Я буду использовать сокращения, которые можно также использовать и при настройке cisco, полную команду можно будет увидеть нажатием клавиши «tab» и можно посмотреть список возможных продолжений команды клавишей “?”.

1. sh run — показывает конфигурацию устройства, листать конфиг можно клавишой «пробел». Можно дополнять команду, конкретизируя, что вы хотите увидеть. Например только конфигурацию интерфейса

gw#sh run interface Loopback0 interface Loopback0  ip address 192.168.1.1 255.255.255.0  ip nat inside  ip virtual-reassembly end

2. sh int loop0 — посмотреть состояние интерфейса, в данном случае Loopback0

Loopback0 is up, line protocol is up   Hardware is Loopback   Internet address is 192.168.1.1/24   MTU 1514 bytes, BW 8000000 Kbit/sec, DLY 5000 usec,      reliability 255/255, txload 1/255, rxload 1/255   Encapsulation LOOPBACK, loopback not set   Last input 00:00:00, output never, output hang never   Last clearing of "show interface" counters never   Input queue: 0/75/0/0 (size/max/drops/flushes); Total output drops: 0   Queueing strategy: fifo   Output queue: 0/0 (size/max)   5 minute input rate 0 bits/sec, 0 packets/sec   5 minute output rate 3000 bits/sec, 2 packets/sec      0 packets input, 0 bytes, 0 no buffer      Received 0 broadcasts, 0 runts, 0 giants, 0 throttles      0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored, 0 abort      36398197 packets output, 2466511320 bytes, 0 underruns      0 output errors, 0 collisions, 0 interface resets      0 unknown protocol drops      0 output buffer failures, 0 output buffers swapped out

3. debug — отладка. Можно набрать «debug », потом tab и увидеть на что можно установиться отладчик. Например debug telnet, будет выдавать все подключение по телнету к данному устройству.
Для активации выдачи сообщений в телнет, нужно ввести «ter mon». Для остановки выдачи сообщений команда «ter no mon».

4. сonf t — конфигурирование устройства. Буква t в нашем примере означает terminal, иначе cisco спросит «Configuring from terminal, memory, or network [terminal]?»

5. do — команда нужна в режиме конфигурирования, когда нужно запустить команду которая из него не доступна. Например для запуска «sh run», нужно набрать «do sh run».

6. shutdown — команда выключения интерфейса, no shut включения. Применяется так:

interface Loopback0 shutdown

7. copy — копирование файлов. Самые нужные варианты это копирование конфига на компьютер по tftp (copy run tftp://192.168.1.2/run) и обновление прошивки копированием с tftp файла (router#copy flash: tftp://192.168.1.2/c1700-adventerprisek9-mz.123-6d.bin)

8. wr — сохранение конфига.

9. traceroute 192.168.1.1 — трассировка маршрута. Остановить трассировку как просит cisco «Type escape sequence to abort», так вот escape sequence — CTRL-SHIFT-6. Иногда требует в другие «долгих» командах. Например как в следующей.

10. ping 192.168.1.1 repeat 100 size 64 — послать сто запросов ping размеров пакетов 64 байта.

11. ip http server — активация HTTP-сервера.

12. username user1 password qwerty — создание пользователя и задание пароля.

13. service password-encryption — хранение паролей в виде хеша.

14. ip name-server <server-address> — добавления DNS-сервера.

15. reboot — перезагрузка маршрутизатора.

Не забывайте про write перед reboot :)

DHCP leseases: sh ip dhcp binding

63voip-2691-01#sh ip dhcp binding
Bindings from all pools not associated with VRF:
IP address          Client-ID/              Lease expiration        Type
                    Hardware address/
                    User name
192.168.0.132       0158.1faa.5d04.47       Infinite                Automatic
192.168.0.133       01e0.2a82.a96f.ca       Infinite                Automatic

Продолжу про полезные команды в Cisco, сегодняшний набор может пригодится начинающим. Предыдущие части можно почитать тут [1] и тут [2].

1. Перезагрузка cisco

Для перезагрузки наберите:

Router#reload

Для перезагрузки через некоторое время наберите

Router#reload in 5

Зачем это нужно? Нужно для того случая когда вы не уверены, что будет после следующего дествия. Например вы решили посмотреть, что будет если набрать debug all, а сходить перегрузить cisco руками у вас не получится (далеко, лень, нельзя и т.д.)

2. ARP таблицы в cisco
посмотреть таблицу

Router#show arp

отчистить таблицу

Router#clear arp

2. Состояние оперативной памяти в cisco
cisco по сути обычный компьютер, посмотреть загруженность памяти можно командой:

Router#show proc mem

в результатах отобразится примерно так:

Processor Pool Total:  361476348 Used:  122061480 Free:  239414868
      I/O Pool Total:   41942528 Used:   19117136 Free:   22825392

 PID TTY  Allocated      Freed    Holding    Getbufs    Retbufs Process
   0   0  273161652  148040624  115214436          0          0 *Init*
   0   0      12052 1233858836      12052          0          0 *Sched*
   0   0 2182777348 1136627068    2914968    3999332    3999332 *Dead*
и т.д.

3. Загрузка процессора в cisco
по аналогии с память загрузку процессора можно посмотреть командой:

Router#show proc cpu sort

в результатах отобразится примерно так:

CPU utilization for five seconds: 7%/3%; one minute: 7%; five minutes: 8%
 PID Runtime(ms)     Invoked      uSecs   5Sec   1Min   5Min TTY Process
  42    31242680     2602037      12007  1.19%  1.26%  1.27%   0 Per-Second Jobs
 121    39988848    93297126        428  0.71%  0.68%  0.58%   0 IP Input
 186      161808   636489506          0  0.31%  0.25%  0.24%   0 HQF Shaper Backg
  90      683328     9578823         71  0.31%  0.30%  0.31%   0 Skinny Msg Serve
  38     2191024     2180733       1004  0.23%  0.12%  0.12%   0 Net Background
 306      127316   214809806          0  0.15%  0.14%  0.15%   0 CH_GT96K Backgro
 348     1647088    21543512         76  0.07%  0.07%  0.06%   0 PDU DISPATCHER
 347     4989168    43620906        114  0.07%  0.21%  0.19%   0 IP SNMP
и т.д.

Параметр sort для сортировки загрузки процессора процессами по убыванию, для анализа процессов которые больше всех грузят процессор.

4. Просмотре версии прошивки в cisco ios
посмотреть можно командой:

Router#show version

в результатах отобразится примерно так:

Cisco IOS Software, 3800 Software (C3845-ADVENTERPRISEK9-M), Version 12.4(24), RELEASE SOFTWARE
inetgw uptime is 4 weeks, 2 days, 1 hour, 3 minutes
и т.д.

5. ?
Знак вопроса [?] самый полезный инструмент в cisco, особенно когда не знаете, что набирать дальше. С его помощью можно быстро обратиться за помощью в Cisco IOS. Тем не менее, система помощи Cisco IOS в корне отличается от других операционных систем, когда речь заходит об использовании знака вопроса. IOS представляет собой систему командной строки с тысячами возможных команд и параметров и использование [?] может сохранить много времени.
Вы можете использовать команду во многих случаях. Во-первых, использовать его, когда вы не знаете, какую-то команду. Наберите [?] в командной строке, чтобы получить список всех возможных команд. Вы также можете использовать [?] если не знаете, какой следующий параметр команды может быть. Например, можно ввестиsh ip ? Если маршрутизатор не требует никаких других параметров команды, маршрутизатор будет предлагать CR, как единственный вариант. И можно использовать [?], чтобы увидеть все команды, которые начинаются с определенной буквы. Например, c? вернет список команд, которые начинаются с буквы C.

6. Как сбросить настройки маршрутизатора к заводским
Набрать

write erase
reload
1. Удобный просмотр состояния интерфейсов:

#show ip int brief | excl unassigned
Interface                  IP-Address      OK? Method Status                Protocol
GigabitEthernet0/0         123.12.198.55   YES NVRAM  up                    up
GigabitEthernet0/1         172.18.48.10    YES NVRAM  up                    up
Vlan30                     172.18.88.90    YES NVRAM  up                    up
NVI0                       192.168.1.21    YES unset  up                    up
Loopback0                  192.168.1.21    YES NVRAM  up                    up

можно добавить алиас на эту команду, чтобы в дальнейшем вызывать ее как ipconfig

alias exec ipconfig show ip interface brief | exclude unassigned


2. Уменьшить время ожидания при открытии ssh/telnet сессии:
Бывает пытаешься открыть удаленный хост по ssh/telnet, а он не доступен. Тогда приходится ждать 30 секунд и никакие ctrl+shift+6 не спасают. Спастись можно если добавить в конфиг предварительно:

ip tcp synwait-time 5
Тогда время ожидания уменьшится до 5.
1. Сброс настроек интерфейса

Router(config)#default interface fa0/0
Building configuration...


2. Escape sequence
Пресловутый escape sequence с Ctrl+Shift+6 можно изменить на например Ctrl+W

Router#terminal escape-character 23          ! 23 = Ctrl+W
"^W" is the escape character 


3. Translating “...”
Иногда ошибаешься в команде и появляется Translating “наша недокоманда”. Можно отключить поиск в dns, чтобы этого не происходило.

Router(config)#no ip domain-lookup

Горячие клавиши

Полезные сочетания клавиш, чтобы лишний раз не пользоваться мышкой.

Ctrl+A — Передвинуть курсор на начало строки
Ctrl+E — Передвинуть курсор на конец строки
Up — Последняя команда из истории
Down — Следующая команда из истории
Ctrl+W — Стереть предыдущее слово
Ctrl+U — Стереть всю линию
Ctrl+C — Выход из режима конфигурирования
Ctrl+Z — Применить текущую команду и выйти из режима конфигурирования
Ctrl+Shift+6 — Остановка длительных процессов — тот самый «Type escape sequence to abort»

Параметры вывода

После основного текста команды через символ | можно указать модификаторы вывода, которые очень полезны. Ими можно фильтровать строки, секции, позицию вывода. Вот основные:
1. Begin
Выведет все начиная со строки в которой будет вхождение параметра, например «sh run | begin int» выведет все начиная со строки в которой встретится «int»

router#sh run | begin int
parser config cache interface
service tcp-keepalives-in
service tcp-keepalives-out


2. Section
Выведет указанные секции, например «sh run | section int» выведет все секции в названиях которых есть «int»

router#sh run | section int
parser config cache interface
interface Loopback0
 ip address 192.168.1.21 255.255.255.0
 ip nat inside
 ip virtual-reassembly in
 shutdown
interface Null0
 no ip unreachables


3. Exclude
Выведет строки в которых нет вхождения параметра, например «sh run | exclude int» выведет строки в которых нет «int»

4. Include
Выведет строки в которых есть вхождения параметра, например «sh run | include int» выведет строки в которых есть «int»

В параметре можно использовать регулярные выражения, например:

router#show run | inc ^interface|ip address
interface Loopback0
 ip address 192.168.1.1 255.255.255.0
interface Null0
interface GigabitEthernet0/0
 ip address 11.11.12.10 255.255.255.240
interface Serial0/2/0
 no ip address
interface Vlan1
 no ip address


и

router#sh ip int | inc line protocol|access list is [^ ]+$
GigabitEthernet0/0 is up, line protocol is up
  Outgoing access list is 100
  Inbound  access list is 200
GigabitEthernet0/1 is up, line protocol is up
  Outgoing access list is 101

How to Upgrade IOS on a Cisco Router

2011 September 30
Comments Off
Posted by shirker2006
from http://www.routergeek.net/index.php?option=com_content&task=view&id=33&Itemid=37&mosmsg=Thanks+for+your+vote%21
Written by Mohammed Alani
Wednesday, 04 April 2007
When would you need this: The upgrade is required when you plan to add more duties to the router or new hardware. The installation is required when the IOS image you have on the router is corrupted.

Special Requirements: The router’s flash size should be enough for the new IOS image.

Before starting the procedure of IOS upgrade or installation, you will need to install TFTP server software on a PC connected to the router Ethernet interface. There are many free downloadable TFTP servers’ software on the Internet, however, our recommendation is Free TFTP Server 6.0.

Afterwards, you make sure to direct the TFTP server to the folder containing the new IOS image that you have.

We will put down two procedures for two different type of routers; a procedure for routers having Internal Flash (ex: 2600), and a slightly different procedure for routers with PCMCIA flash cards (ex: 3600).

Upgrade Procedure for Cisco Routers with Internal Flash:

1. Create a console connection with the default settings (9600 baud, 8 databits, 0 parity bits, 1 stop bit, no flow control).

2. Verify the connectivity between the router and the TFTP server using ‘ping’. Make sure that the router interface and the TFTP server IP addresses are in the same range and the ping is responding well.

3. Although the upgrade will be happening in the flash and the configuration is saved in the NVRAM, make a backup of the configuration. This is recommended in case something goes wrong in the upgrade. Also, make a backup copy of the IOS you already have on the router. In case the new IOS image is corrupted, you will be on the safe side. For the backup process, please refer to theIOS backup procedure and configuration backup procedure.

4. Start the upgrade by the command:

Router#copy tftp flash

Now you will be prompted for the IP address of the TFTP server:

Address or name of remote host []? XXX.XXX.XXX.XXX

Afterwards, you will be asked for the name of the new IOS file being copied from the TFTP server:

Source filename []? cXXXX-X-XX.XXX-XX.bin

Please note that the file name is case sensitive, so be %100 sure of what you are writing.

Now you will be asked for the destination file name on your router,

Destination filename []? cXXXX-X-XX.XXX-XX.bin

It is preferred to keep it as the source file name, to be able to easily identify the files on the TFTP servers as compared to the ones on the routers.

Now you will be asked whether to erase the existing file(s) in the flash or not. If you have enough free space on the flash, don’t erase the old IOS image, you might need it.

Erase flash: before copying? [confirm]

Afterwards, the router starts copying the new IOS file to the router, or start erasing the flash and then copying.

Erasing the flash filesystem will remove all files! Continue? [confirm]y

Erasing device… eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

eeeeeeeeee …erased

Erase of flash: complete

Loading cXXXX-X-XX.XXX-XX.bin from XXX.XXX.XXX.XXX (via Ethernet0/0): !!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

[OK - xxxxx/yyyyyyy bytes]

 

Verifying checksum…  OK (0xAC8A)

xxxxxx bytes copied in xx.xx secs (yyyy bytes/sec)

The copying process takes several minutes; the time differs from network to network. During the copy process, messages are displayed to indicate which file has been accessed.

The exclamation point “!” indicates that the copy process is taking place. Each exclamation point indicates that ten packets have been transferred successfully. A checksum verification of the image occurs after the image is written to flash memory.

5. Before reloading the router, you need to make sure of two things. The first is that the configuration register value is 0×2102. You can check that wit the ‘show version’ command. If the configuration register’s value is not 0×2102, you will need to set it to that value with the following command:

Router(config)#config-register 0×2102

The second thing is needed to be checked if you did not erase the contents of the flash. You will need to setup the router to boot from the new IOS file with the following commands:

Router(config)#no boot system

Router(config)#boot system flash cXXXX-X-XX.XXX-XX.bin

6. If you type the reload command, the router asks you if you want to save the configuration. You should be very cautious here. The reason is that if the router is in boot mode for instance, it is a subset of the full Cisco IOS software which is running and there is no routing functionality. Therefore, all the routing configuration is gone in the running configuration and if you save the configuration at this time, then you erase the good startup-configuration in NVRAM and replace it by the incomplete running-configuration. Save the configuration only if you are sure that you have the full configuration in the output of show run. It is NOT necessary to save the configuration to take into account the new config-register if this one has been changed previously. That is done automatically.

Router#reload

System configuration has been modified. Save? [yes/no]: y 

Building configuration…

[OK]

Proceed with reload? [confirm]y

7. To verify that the new image is loaded after the ‘reload’, use ‘show version’ command.

00:22:25: %SYS-5-CONFIG_I: Configured from console by console

Cisco Internetwork Operating System Software 

IOS ™ CXXXX Software (CXXXX-X-X), Version XX.X(XX), RELEASE SOFTWARE (fc1)

Copyright (c) 1986-2002 by cisco Systems, Inc.

Compiled Mon 25-Mar-02 20:33 by xxxxx

Image text-base: 0×80008088, data-base: 0×80828788

 

ROM: System Bootstrap, Version xx.x(x)XA4, RELEASE SOFTWARE (fc1)

 

XXXX uptime is 22 minutes

System returned to ROM by reload

System image file is “flash: cXXXX-X-XX.XXX-XX.bin “     <<< Check it here

Note: In step 1 or after the upgrade, if the router boots into rommon mode or boot mode and you have one of the following case:

rommon 1 > dir flash: 

device does not contain a valid magic number 

dir: cannot open device “flash:” 

rommon 2 >

or

router(boot)>

device does not contain a valid magic number

boot: cannot open “flash:”

boot: cannot determine first file name on device “flash:”

This means that the flash is empty or the file system is corrupted. In this case, you have to consider using the procedure ofUpgrading or Installing the IOS from ROMmon mode .

Upgrade Procedure for Cisco Routers with PCMCIA Flash:

1. Create a console connection with the default settings (9600 baud, 8 databits, 0 parity bits, 1 stop bit, no flow control). If your router does not boot regularly, refer to the note above.

2. Check if you have enough space in the flash card for the new IOS file:

Router#dir slot1:

If you find that there is not enough space, you can delete one or more files from the flash:

Router#delete slot1: FILENAME.bin

If you delete on or more files from the flash DO NOT reload or powercycle the router until you finish this procedure. The flash image you are working on is currently loaded into RAM, so you can keep working properly until you reload or powercycle the router.

3. Verify the connectivity to the TFTP sever with the ‘ping’ command. And make sure that the TFTP server software is running and the working directory of the TFTP server contains the new IOS file. It is also adviced that you backup the configuration and old IOS file before proceeding. For this purpose, you can refer to IOS backup procedure and configuration backup procedure.

4. Copy the new IOS file from the TFTP server to the router:

Router#copy tftp slot1:

Address or name of remote host []? XXX.XXX.XXX.XXX

Source filename []? cXXXX-X-XX.XXX-XX.bin

Destination filename [cXXXX-X-XX.XXX-XX.bin]?

Accessing tftp://XXX.XXX.XXX.XXX/cXXXX-X-XX.XXX-XX.bin…

Erase slot1: before copying? [confirm]n     <<< You can say ‘no’ here because you have already emptied space for the new IOS file

Loading cXXXX-X-XX.XXX-XX.bin from XXX.XXX.XXX.XXX (via Ethernet1/0): 

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!!!!!!!!

[OK - xxxxxxx/yyyyyyy bytes]

 

Verifying checksum…  OK (0x13F0)

xxxxxxx bytes copied in 67.708 secs (zzzz bytes/sec)

Router#

5. Verify the new IOS file in the flash car:

Router#dir slot1:

6. Direct the router to load the new IOS file in the next boot:

Router(config)#no boot system

Router(config)#boot system flash slot1:cXXXX-X-XX.XXX-XX.bin

7. Make sure that the configuration register has the value of 0×2102. This is verified by the ‘show version’ command. If the configuration register has a value other than 0×2102, use the following command to change it:

Router(config)#config-register 0×2102

8. Save the configuration with one of the two following commands:

Router#write memory

Or

Router#copy run start

9. Reload the router with ‘reload’ command. And after the reload, verify the new IOS version with the ‘show version’ command. This command will also show you the name of the IOS file that has been loaded.

solid-state.org free billing panel

2011 September 25
Comments Off
Posted by shirker2006

looking for Solid-State?

http://en.sourceforge.jp/projects/sfnet_solidstate/releases/?file_id=2573297

Быстрая настройка squid + icq + ftp + ssl

2011 September 23
Comments Off
Posted by shirker2006

Быстрая настройка squid + icq + ftp + ssl

Цель данной статьи – описать как можно быструю и простую настройку прокси-сервера squid с работой через него протоколов ICQ, FTP, SSL.

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

И так начнем!..

Установка.

Для установки на debian-based(например ubuntu) дистрибутиве достаточно просто выполнить команду:

apt-get install squid

для rpm-based (CentOS, Fedora):

yum install squid

для Gentoo Linux:

emerge squid

Или можно воспользоватся стандартным способом – скачать последнюю версию исходников в архиве с официального сайта Squid.
Скачиваем последнюю стабильную версию (на момент написания статьи, апрель 2008, последняя стабильная версия – squid-3.0.STABLE4).

Установка из архива:

tar -xvjf squid-3.0.STABLE4.tar.bz2
cd squid-3.0.STABLE4
./configure
make all
make install

Команду make install надо выполнять с правами пользователя root.
На этом установка прокси-сервера squid завершена. Переходим к самой конфигурации сервера.

Редактируем главный конфигурационный файл, по умолчанию это файл /etc/squid/squid.conf:

vi /etc/squid/squid.conf

Вместо vi можно использовать любой другой текстовый редактор.
Символ # в начале строки обозначает комментарий.

#указываем какой порт должен слушать наш прокси-сервер
#мы укажем порт 3128, т.к. он считается стандартным для squid’а
http_port 3128

#определяем видимое имя прокси-сервера, например укажем имя tuxhost:
visible_hostname tuxhost

#создаем списки компьютеров, которым мы разрешим доступ
#списки создаются директивой acl, в виде:
#acl имя_списка src список

#разрешаем доступ пользователям с адресами 10.110.109.110 и 10.37.64.90
#(в данном случае мы разрешили доступ некоторым адресам, точно так же можно
#разрешать/запрещать доступ к сетям)
#назовем список allowed_hosts (это вовсе не правило! можно использовать любое имя)
acl allowed_hosts src 10.110.109.110/255.255.255.255
acl allowed_hosts src 10.37.64.90/255.255.255.255

#открываем доступ по localhost (если он нужен конечно же)
acl localhost src 127.0.0.1/255.255.255.255

#определяем остальных пользователей
acl all src 0.0.0.0/0.0.0.0

#открываем порты для icq, ssl
acl icq_ports port 443 563 5190

#открываем порты для работы с http, ftp
acl open_ports port 80 8000 # http
acl open_ports port 21 # открываем доступ по ftp

#разрешаем доступ для localhost
http_access allow localhost

#разрешаем доступ для компьютеров, которым мы ранее разрешили доступ
http_access allow allowed_hosts

#открываем порта для работы icq
http_access allow icq_ports

#открываем порта для http, ftp
http_access allow open_ports

#запрещаем всем остальным доступ к прокси-серверу
http_access deny all

Сохраняем файл и выходим. На этом настройка squid’а заканчивается.
Осталось создать swap-директории для squid’а:

squid -z

Запускаем наш прокси-сервер командой:

/etc/init.d/squid start

Вот собственно и все! Наш прокси-сервер готов.
И так мы описали быструю настройку с поддержкой протоколов ICQ, FTP, SSL.

Я надеюсь, что моя статья поможет новичкам и не только в быстрой (аля quick start!) настройки этого распространенного прокси-сервера.

Фролов Николай, aka linke
Специально для tuxnotes.ru

При использовании материалов сайта, ссылка обязательна.

howto upgrade centos from 5 to 6 (link)

2011 September 19
Comments Off
Posted by shirker2006

You can do it ONLY by reinstalling OS:

http://www.unixmen.com/linux-tutorials/1836-upgrading-from-centos-56-to-centos-6

Vicidial scratch install on asterisk

2011 September 19
Comments Off
Posted by shirker2006

How To install ViciDial/astGUIclient 2.2.1 With Asterisk 1.4.21.2 On CentOS 5.5

Required files can be found here:

http://downloads.vicidial.com/required-apps/ 

Introduction


VICIDIAL is an enterprise class, open source, call center suite in use by many large call centers around the world.
Asterisk is software that turns an ordinary computer into a voice communications server.
Together, you have a full featured predictive dialer. It can also function as an ACD for inbound calls, or closer calls coming from VICIDIAL outbound fronters. It is capable of inbound, outbound, and blended call handling. VICIDIAL even allows you to have agents logged in from remote locations.

Preliminary Notes


In this tutorial I will be installing this on a newly installed CentOS 5.5 64-bit dedicated server that I am leasing from a data center. It has no control panel (cPanel, Plesk, ISPconfig, etc..) because a control panel is not needed. Your should be comfortable using a command line terminal in Linux and know basic server administration. These same instructions apply to CentOS 5.5 32-bit except for one minor change when editing the php.ini for eAccelerator in which I pointed out in that part of the configuration.

This tutorial will not explain how to configure or use vicidial. For that, I recommend purchasing the Agent and Managers Manual fromwww.eflo.net. This is required reading. There is also a free version of the Agent and Manager’s Manual available for download that will help. You may also use the forums to ask specific questions.

This tutorial is a derivative of the original scratch install instructions found in the astguiclient source package. It has been adapted to CentOS.

From time to time this page will get updated.
You must login as root to install the following software.

Update the system


Make sure you update the system first, then reboot if you installed an updated kernel.

yum -y update
reboot
Install the following software

yum install gcc gcc-c++ php php-devel php-gd gd-devel php-mbstring php-mcrypt php-imap php-ldap php-mysql php-odbc php-pear php-xml php-xmlrpc curl curl-devel perl-libwww-perl ImageMagick libxml2 libxml2-devel httpd libpcap libpcap-devel ncurses ncurses-devel screen sox mysql-server mysql-devel ntp kernel-devel mutt

Setup MySQL


Setup default MySQL tables, start MySQL and configure root password
Replace “mypassword” with your real password.

mysql_install_db
/etc/init.d/mysqld start
/usr/bin/mysqladmin -u root password ‘mypassword’

Update the time zone


Configure the system time and update it. (I set the server time zone to Arizona, so this is how I did it)

rm /etc/localtime
ln -sf /usr/share/zoneinfo/US/Arizona /etc/localtime
rdate -s nist1-ny.ustiming.org

Changes take effect immediately after you run the rdate command.

Have a look inside /usr/share/zoneinfo/US/ for different time zones.

Turn off ntpd and remove it from bootup runlevels.

You will be running ntpdate from cron instead.

service ntpd stop
chkconfig ntpd off

Setup CPAN and install some modules


Run the following command

perl -MCPAN -e shell

You will then go through CPAN setup, just hit ENTER for most prompts except
for the mirrors list, you will want to select at least 4 mirrors

  • yes for manual configuration
  • enter for the next 18 prompts
  • for the “make install” option, it’s a good idea to add UNINST=1
  • enter for the next 4 prompts
  • select your continent and country
  • select a few cpan mirrors
  • enter for the next 2 prompts

Once you see the cpan> prompt you can begin installing modules.
This may take a while.

install MD5
install Digest::MD5
install Digest::SHA1
install readline
install Bundle::CPAN
reload cpan
install DBI
force install DBD::mysql
install Net::Telnet
install Time::HiRes
install Net::Server
install Switch
install Mail::Sendmail
install Unicode::Map
install Jcode
install Spreadsheet::WriteExcel
install OLE::Storage_Lite
install Proc::ProcessTable
install IO::Scalar
install Spreadsheet::ParseExcel
install Curses
install Getopt::Long
install Net::Domain
install Term::ReadKey
install Term::ANSIColor
quit

In the end, I usually run all these commands once again to make sure its all installed.

Installing the Asterisk-Perl module


NOTE: Do NOT use the 0.09 or any newer version, they do not work with ViciDial.

cd /usr/src
wget http://asterisk.gnuinter.net/files/asterisk-perl-0.08.tar.gz
tar -zxf asterisk-perl-0.08.tar.gz
cd asterisk-perl-0.08
perl Makefile.PL
make all
make install

Installing additional software from source (optional, but highly recommended)


Next, you will download, compile and install the following software.

  • lame
  • ttyload
  • iftop
  • mtop
  • mytop
  • sipsak
  • ploticus

LAME:
LAME is an MP3 encoder used to convert audio files from WAV to MP3. Some prefer GSM usually, but others have standardized on MP3 so you would need this utility to be loaded to use that option.

cd /usr/src
wget http://downloads.sourceforge.net/project/lame/lame/3.98.2/lame-398-2.tar.gz
tar -zxf lame-398-2.tar.gz
cd lame-398-2
./configure
make
make install
TTYLOAD:
ttyload is a simple terminal application that shows the processor load in a graphical time-based scrolling graph. I use it to view how loaded the system is and it visualizes load spikes very well.

cd /usr/src
wget http://www.daveltd.com/src/util/ttyload/ttyload-0.5.tar.gz
tar -zxf ttyload-0.5.tar.gz
cd ttyload-0.5
make
ln -s /usr/src/ttyload-0.5/ttyload /usr/bin/ttyload
IFTOP:
iftop is a good console bandwidth visualization tool that shows you active connections, where they are going to/from and how much of your precious bandwidth they are using.

cd /usr/src
wget http://www.ex-parrot.com/~pdw/iftop/download/iftop-0.17.tar.gz
tar -zxf iftop-0.17.tar.gz
cd iftop-0.17
./configure
make
make install
MTOP:
mtop is a great utility for real-time monitoring of mysql and the queries that are running in it.
Note: the root mysql password must be blank before installing this

mysql -u root -p
Enter your MySQL password, then the following MySQL command:

SET PASSWORD FOR root@localhost=PASSWORD(”);QUIT;

cd /usr/src
wget http://downloads.sourceforge.net/project/mtop/mtop/v0.6.6/mtop-0.6.6.tar.gz
tar -zxf mtop-0.6.6.tar.gz
cd mtop-0.6.6
perl Makefile.PL
make
make install
Enter the following MySQL command to put your root password back the way it was originally
Replace “mypassword” with your real password.

SET PASSWORD FOR root@localhost=PASSWORD(‘mypassword’);QUIT;
MYTOP:
mytop is is an optional utility for monitoring the threads and overall performance of mysql
Note: the root mysql password must be blank before installing this

mysql -u root -p
Enter your MySQL password, then the following MySQL command:

SET PASSWORD FOR root@localhost=PASSWORD(”);QUIT;

cd /usr/src
wget http://jeremy.zawodny.com/mysql/mytop/mytop-1.6.tar.gz
tar -zxf mytop-1.6.tar.gz
cd mytop-1.6
perl Makefile.PL
make
make test
make install
Enter the following MySQL command to put your root password back the way it was originally
Replace “mypassword” with your real password.

SET PASSWORD FOR root@localhost=PASSWORD(‘mypassword’);QUIT;
SIPSAK:
sipsak is an optional utility that VICIDIAL can use to send messages to an agent’s SIP-based phone(like the Snom 320) to display text on their LCD screen.

cd /usr/src
wget http://download.berlios.de/sipsak/sipsak-0.9.6-1.tar.gz
tar -zxf sipsak-0.9.6-1.tar.gz
cd sipsak-0.9.6
./configure
make
make install
/usr/local/bin/sipsak –version
PLOTICUS:
ploticus is a free graph creation package that allows you to create line graphs within PNG files simply by creating a config file and a data file. ViciDial uses this package to generate server performance graphs that can be displayed real-time within the ViciDial reports page.

cd /usr/src
wget http://downloads.sourceforge.net/project/ploticus/ploticus/2.41/pl241src.tar.gz
tar -zxf pl241src.tar.gz
cd pl241src/src/
make clean
make
make install
mkdir -p /var/www/html/vicidial/ploticus/
cp pl /var/www/html/vicidial/ploticus/

Installing eAccelerator for PHP


Install the php module

cd /usr/src
wget http://sourceforge.net/projects/eaccelerator/files/eaccelerator/eAccelerator 0.9.6.1/eaccelerator-0.9.6.1.zip/download
unzip eaccelerator-0.9.6.1.zip
cd eaccelerator-0.9.6.1
export PHP_PREFIX=”/usr”
$PHP_PREFIX/bin/phpize
./configure –enable-eaccelerator=shared –with-php-config=$PHP_PREFIX/bin/php-config
make
make install
Configure php.ini

nano /etc/php.ini

You will want to make sure NOTICE logging is turned off:

error_reporting  =  E_ALL & ~E_NOTICE
memory_limit = 48M
short_open_tag = On
max_execution_time = 330
max_input_time = 360
post_max_size = 48M
upload_max_filesize = 42M
default_socket_timeout = 360

Add the following lines to the dynamic extensions section of php.ini:

Note: For CentOS 32-bit, use this below: zend_extension=”/usr/lib/php/modules/eaccelerator.so”

zend_extension="/usr/lib64/php/modules/eaccelerator.so"
;For CentOS 32-bit: zend_extension="/usr/lib/php/modules/eaccelerator.so"
eaccelerator.shm_size="48"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

mkdir /tmp/eaccelerator
chmod 0777 /tmp/eaccelerator
php -v

You should see something like this:

PHP 5.1.6 (cli) (built: Jan 13 2010 17:09:42)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
with eAccelerator v0.9.6.1, Copyright (c) 2004-2010 eAccelerator, by eAccelerator

Editing the Apache config file


nano /etc/httpd/conf/httpd.conf
To disable logging, change:

CustomLog logs/access_log common

to this:

CustomLog /dev/null common

To enable web browsing of Recordings on Asterisk server, add this:

Alias /RECORDINGS/ "/var/spool/asterisk/monitorDONE/"

<Directory "/var/spool/asterisk/monitorDONE">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
        <files *.mp3>
            Forcetype application/forcedownload
        </files>
</Directory>

Restart the Apache web server to apply the changes

/etc/init.d/httpd restart

Installing Asterisk


At the time of this writing, you cannot install the latest version of Asterisk 1.6 or 1.8.
ViciDial 2.2.1 is currently compatible with Asterisk 1.4.21.2. This version of Asterisk also needs to be patched to work with vicidial correctly.

mkdir /usr/src/asterisk
cd /usr/src/asterisk
wget http://downloads.digium.com/pub/asterisk/old-releases/asterisk-1.4.21.2.tar.gz
wget http://downloads.digium.com/pub/zaptel/zaptel-1.4.12.1.tar.gz
wget http://downloads.asterisk.org/pub/telephony/libpri/old/libpri-1.4.9.tar.gz
tar -zxf asterisk-1.4.21.2.tar.gz
tar -zxf zaptel-1.4.12.1.tar.gz
tar -zxf libpri-1.4.9.tar.gz
cd libpri-1.4.9
make clean
make
make install
cd ../zaptel-1.4.12.1
./configure
make clean
make
make install
make config
cd ../asterisk-1.4.21.2
wget http://www.eflo.net/files/enter.h
wget http://www.eflo.net/files/leave.h
mv -f enter.h apps/enter.h
mv -f leave.h apps/leave.h
wget http://download.vicidial.com/asterisk-patches/1.4-gsm-gcc4.2.patch
patch -p1 ./codecs/gsm/Makefile 1.4-gsm-gcc4.2.patch
wget http://download.vicidial.com/conf/res_agi_defunct.patch
patch -p1 < res_agi_defunct.patch
File to patch: res/res_agi.c
cd apps/
rm -f app_waitforsilence.c
wget http://download.vicidial.com/conf/app_waitforsilence.c
cd ../channels/
rm chan_sip.c
wget http://download.vicidial.com/conf/chan_sip.c
cd ../
./configure
make clean
make
make install
make samples
modprobe zaptel
modprobe ztdummy

Add init.d script and add to bootup runlevels

cp /usr/src/asterisk/asterisk-1.4.21.2/contrib/init.d/rc.redhat.asterisk /etc/init.d/asterisk
chkconfig –add asterisk

Installing Sound files


Download the sound files

cd /usr/src
wget http://downloads.digium.com/pub/telephony/sounds/asterisk-core-sounds-en-ulaw-current.tar.gz
wget http://downloads.digium.com/pub/telephony/sounds/asterisk-core-sounds-en-wav-current.tar.gz
wget http://downloads.digium.com/pub/telephony/sounds/asterisk-core-sounds-en-gsm-current.tar.gz
wget http://downloads.digium.com/pub/telephony/sounds/asterisk-extra-sounds-en-ulaw-current.tar.gz
wget http://downloads.digium.com/pub/telephony/sounds/asterisk-extra-sounds-en-wav-current.tar.gz
wget http://downloads.digium.com/pub/telephony/sounds/asterisk-extra-sounds-en-gsm-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-moh-opsound-gsm-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-moh-opsound-ulaw-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-moh-opsound-wav-current.tar.gz

Set the sounds in place

cd /var/lib/asterisk/sounds
tar -zxf /usr/src/asterisk-core-sounds-en-gsm-current.tar.gz
tar -zxf /usr/src/asterisk-core-sounds-en-ulaw-current.tar.gz
tar -zxf /usr/src/asterisk-core-sounds-en-wav-current.tar.gz
tar -zxf /usr/src/asterisk-extra-sounds-en-gsm-current.tar.gz
tar -zxf /usr/src/asterisk-extra-sounds-en-ulaw-current.tar.gz
tar -zxf /usr/src/asterisk-extra-sounds-en-wav-current.tar.gz

mkdir /var/lib/asterisk/mohmp3
mkdir /var/lib/asterisk/quiet-mp3
mkdir /var/lib/asterisk/default
cd /var/lib/asterisk
ln -s mohmp3 default
ln -s moh mohmp3
cd mohmp3
tar -zxf /usr/src/asterisk-moh-opsound-gsm-current.tar.gz
tar -zxf /usr/src/asterisk-moh-opsound-ulaw-current.tar.gz
tar -zxf /usr/src/asterisk-moh-opsound-wav-current.tar.gz
rm CHANGES*
rm LICENSE*
rm CREDITS*
cd /var/lib/asterisk/moh
rm CHANGES*
rm LICENSE*
rm CREDITS*
cd /var/lib/asterisk/sounds
rm CHANGES*
rm LICENSE*
rm CREDITS*
cd /var/lib/asterisk/quiet-mp3

sox ../mohmp3/macroform-cold_day.wav macroform-cold_day.wav vol 0.25
sox ../mohmp3/macroform-cold_day.gsm macroform-cold_day.gsm vol 0.25
sox -t ul -r 8000 -c 1 ../mohmp3/macroform-cold_day.ulaw -t ul macroform-cold_day.ulaw vol 0.25
sox ../mohmp3/macroform-robot_dity.wav macroform-robot_dity.wav vol 0.25
sox ../mohmp3/macroform-robot_dity.gsm macroform-robot_dity.gsm vol 0.25
sox -t ul -r 8000 -c 1 ../mohmp3/macroform-robot_dity.ulaw -t ul macroform-robot_dity.ulaw vol 0.25
sox ../mohmp3/macroform-the_simplicity.wav macroform-the_simplicity.wav vol 0.25
sox ../mohmp3/macroform-the_simplicity.gsm macroform-the_simplicity.gsm vol 0.25
sox -t ul -r 8000 -c 1 ../mohmp3/macroform-the_simplicity.ulaw -t ul macroform-the_simplicity.ulaw vol 0.25
sox ../mohmp3/reno_project-system.wav reno_project-system.wav vol 0.25
sox ../mohmp3/reno_project-system.gsm reno_project-system.gsm vol 0.25
sox -t ul -r 8000 -c 1 ../mohmp3/reno_project-system.ulaw -t ul reno_project-system.ulaw vol 0.25
sox ../mohmp3/manolo_camp-morning_coffee.wav manolo_camp-morning_coffee.wav vol 0.25
sox ../mohmp3/manolo_camp-morning_coffee.gsm manolo_camp-morning_coffee.gsm vol 0.25
sox -t ul -r 8000 -c 1 ../mohmp3/manolo_camp-morning_coffee.ulaw -t ul manolo_camp-morning_coffee.ulaw vol 0.25

Installing Astguiclient


Installing Astguiclient 2.2.1.

Note: the installer will ask where your web root is located. I use /var/www/html as my web root. This is where the installer will put your web-facing files.

mkdir /usr/src/astguiclient
cd /usr/src/astguiclient
wget http://downloads.sourceforge.net/project/astguiclient/astguiclient_2.2.1.zip
unzip astguiclient_2.2.1.zip
perl install.pl
Download and copy a gsm file

cd /var/lib/asterisk/sounds
wget http://astguiclient.sf.net/conf.gsm
cp conf.gsm park.gsm

Create the database and import the sample data


First, login to mysql to run some commands

mysql -u root -p
Enter these MySQL commands:

CREATE DATABASE `asterisk` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
GRANT SELECT,INSERT,UPDATE,DELETE,LOCK TABLES on asterisk.* TO cron@’%’ IDENTIFIED BY ’1234′;
GRANT SELECT,INSERT,UPDATE,DELETE,LOCK TABLES on asterisk.* TO cron@localhost IDENTIFIED BY ’1234′;
GRANT RELOAD ON *.* TO cron@’%';
GRANT RELOAD ON *.* TO cron@localhost;

flush privileges;
SET GLOBAL connect_timeout=60;

use asterisk;

\. /usr/src/astguiclient/extras/MySQL_AST_CREATE_tables.sql
\. /usr/src/astguiclient/extras/sip-iax_phones.sql
\. /usr/src/astguiclient/extras/first_server_install.sql
quit
In the Linux terminal, enter these commands

/usr/share/astguiclient/ADMIN_area_code_populate.pl
cp /usr/src/astguiclient/extras/performance_test_leads.txt /usr/share/astguiclient/LEADS_IN/
/usr/share/astguiclient/VICIDIAL_IN_new_leads_file.pl –forcelistid=107 –forcephonecode=1
Make several entries in the rc.local of your system:

nano /etc/rc.d/rc.local

### sybsys local login
touch /var/lock/subsys/local

# OPTIONAL enable ip_relay(for same-machine trunking and blind monitoring)
# /usr/share/astguiclient/ip_relay/relay_control start  2>/dev/null 1>&2

# Disable console blanking and powersaving
/usr/bin/setterm -blank
/usr/bin/setterm -powersave off
/usr/bin/setterm -powerdown

### start up the MySQL server
/etc/init.d/mysqld start

### start up the apache web server
/etc/init.d/httpd start

### roll the Asterisk logs upon reboot
/usr/share/astguiclient/ADMIN_restart_roll_logs.pl

### clear the server-related records from the database
/usr/share/astguiclient/AST_reset_mysql_vars.pl

### load zaptel drivers
modprobe zaptel
modprobe ztdummy
/sbin/ztcfg -vvvvvvvvvvvv

### sleep for 20 seconds before launching Asterisk
sleep 20

### start up asterisk
/usr/share/astguiclient/start_asterisk_boot.pl

Make several entries in the crontab of your system:

crontab -e

### recording mixing/compressing/ftping scripts
0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57 * * * * /usr/share/astguiclient/AST_CRON_audio_1_move_mix.pl
#0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57 * * * * /usr/share/astguiclient/AST_CRON_audio_1_move_mix.pl --MIX
#0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57 * * * * /usr/share/astguiclient/AST_CRON_audio_1_move_VDonly.pl
1,4,7,10,13,16,19,22,25,28,31,34,37,40,43,46,49,52,55,58 * * * * /usr/share/astguiclient/AST_CRON_audio_2_compress.pl --GSM
#2,5,8,11,14,17,20,23,26,29,32,35,38,41,44,47,50,53,56,59 * * * * /usr/share/astguiclient/AST_CRON_audio_3_ftp.pl --GSM

### keepalive script for astguiclient processes
* * * * * /usr/share/astguiclient/ADMIN_keepalive_ALL.pl

### kill Hangup script for Asterisk updaters
* * * * * /usr/share/astguiclient/AST_manager_kill_hung_congested.pl

### updater for voicemail
* * * * * /usr/share/astguiclient/AST_vm_update.pl

### updater for conference validator
* * * * * /usr/share/astguiclient/AST_conf_update.pl

### flush queue DB table every hour for entries older than 1 hour
11 * * * * /usr/share/astguiclient/AST_flush_DBqueue.pl -q

### fix the vicidial_agent_log once every hour and the full day run at night
33 * * * * /usr/share/astguiclient/AST_cleanup_agent_log.pl
50 0 * * * /usr/share/astguiclient/AST_cleanup_agent_log.pl --last-24hours
## uncomment below if using QueueMetrics
#*/5 * * * * /usr/share/astguiclient/AST_cleanup_agent_log.pl --only-qm-live-call-check

## uncomment below if using Vtiger
#1 1 * * * /usr/share/astguiclient/Vtiger_optimize_all_tables.pl --quiet

### updater for VICIDIAL hopper
* * * * * /usr/share/astguiclient/AST_VDhopper.pl -q

### adjust the GMT offset for the leads in the vicidial_list table
1 1,7 * * * /usr/share/astguiclient/ADMIN_adjust_GMTnow_on_leads.pl --debug

### reset several temporary-info tables in the database
2 1 * * * /usr/share/astguiclient/AST_reset_mysql_vars.pl

### optimize the database tables within the asterisk database
3 1 * * * /usr/share/astguiclient/AST_DB_optimize.pl

## adjust time on the server with ntp
30 * * * * /usr/sbin/ntpdate -u pool.ntp.org 2>/dev/null 1>&2

### VICIDIAL agent time log weekly and daily summary report generation
2 0 * * 0 /usr/share/astguiclient/AST_agent_week.pl
22 0 * * * /usr/share/astguiclient/AST_agent_day.pl

### VICIDIAL campaign export scripts (OPTIONAL)
#32 0 * * * /usr/share/astguiclient/AST_VDsales_export.pl
#42 0 * * * /usr/share/astguiclient/AST_sourceID_summary_export.pl

### remove old recordings more than 7 days old
#24 0 * * * /usr/bin/find /var/spool/asterisk/monitorDONE -maxdepth 2 -type f -mtime +7 -print | xargs rm -f

### roll logs monthly on high-volume dialing systems
#30 1 1 * * /usr/share/astguiclient/ADMIN_archive_log_tables.pl

### remove old vicidial logs and asterisk logs more than 2 days old
28 0 * * * /usr/bin/find /var/log/astguiclient -maxdepth 1 -type f -mtime +2 -print | xargs rm -f
29 0 * * * /usr/bin/find /var/log/asterisk -maxdepth 3 -type f -mtime +2 -print | xargs rm -f
30 0 * * * /usr/bin/find / -maxdepth 1 -name "screenlog.0*" -mtime +4 -print | xargs rm -f

Final Adjustments


It is important to change the externip and localnet values in the sip.conf

The externip needs to be the public ip of your server.
The localnet will consist of the public ip/netmask of your server.

nano /etc/asterisk/sip.conf

externip = 75.75.75.75
localnet=75.75.75.75/255.255.255.248

Run this perl script to update the server_ip fields in the asterisk tables (copy the command as-is)

/usr/share/astguiclient/ADMIN_update_server_ip.pl –old-server_ip=10.10.10.15
Update music on hold configuration

nano /etc/asterisk/musiconhold.conf

;
; Music on Hold -- Sample Configuration
;

[default]
mode=files
directory=/var/lib/asterisk/mohmp3

[quiet]
mode=files
directory=/var/lib/asterisk/quiet-mp3

#include musiconhold-vicidial.conf

* There are other sample configration files in /usr/src/astguiclient/docs/conf_examples/ that you might want to look at and maybe copy from and customize.

Lastly, reboot the machine

reboot

Diagnostics


After reboot, check your logs for any errors, make sure asterisk is up and running. Be proactive and look for problems before you start configuring vicidial.

Run these commands to view log files:

  • tail -f -n 50 /var/log/asterisk/messages
  • tail -f -n 50 /var/log/messages
  • more /var/log/dmesg
  • tail -f -n 40 /etc/httpd/logs/error_log
  • tail -f -n 40 /var/log/maillog
  • tail -f -n 40 /var/log/cron

Run this command:

screen -ls

The output should look similar to this:

There are screens on:
    4090.asterisk   (Detached)
    4077.ASTfastlog (Detached)
    8325.ASTsend    (Detached)
    8322.ASTupdate  (Detached)
    4004.astshell20110228193500     (Detached)
    8334.ASTVDremote        (Detached)
    8328.ASTlisten  (Detached)
    12192.ASTVDadapt        (Detached)
    8331.ASTVDauto  (Detached)
    9 Sockets in /var/run/screen/S-root.

Start using vicidial


Login to vicidial and configure it.

Add users, campaigns, in-group, DID’s, server, etc….

Go to: http://youripaddress/vicidial/admin.php

The default username is: 6666 and the password is: 1234

A note about security


When you get vicidial configured and working, make sure to follow basic common sense server administration rules like setting up a firewall, changing default passwords, disallow remote mysql connections or limiting it, etc…

Dont forget to purchase the Agent and Managers Manual from www.eflo.net.

Last Updated: 09/07/2011

centos 6.0 yum install asterisk

2011 September 17
Comments Off
Posted by shirker2006

http://pkgs.org/search/?keyword=asterisk+1.6&search_on=name&distro=82&arch=64-bit

As you can see there two repositories: ATrpms and EPEL.  Asterisk/Digium repos support only El4/5

EPEL

CentOS 5.x 32-bit (x86/i386):

rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm

CentOS 5.x 64-bit (x64):

rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm

CentOS 6.x 32-bit (x86/i386):

rpm -Uvh http://download.fedora.redhat.com/pub/epel/6/i386/epel-release-6-5.noarch.rpm

CentOS 6.x 64-bit (x64):

rpm -Uvh http://download.fedora.redhat.com/pub/epel/6/x86_64/epel-release-6.5.noarch.rpm

ATrpms:

just download and install by same way as above ↑


http://pkgs.org/centos-6-rhel-6/atrpms-x86_64/atrpms-repo-6-4.el6.x86_64.rpm.html


Then try

# yum search asterisk

More repositories?

http://wiki.centos.org/AdditionalResources/Repositories/

examples:

Centos 6.0 x86_64:

   8  wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm
   9  rpm -ivh rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm
   13  rpm -Uvh http://download.fedora.redhat.com/pub/epel/6/x86_64/epel-release-6-5.noarch.rpm
   14  wget http://dl.atrpms.net/el6-x86_64/atrpms/stable/atrpms-repo-6-4.el6.x86_64.rpm
   15  rpm -Uvh atrpms-repo-6-4.el6.x86_64.rpm
   16  yum update

Centos 5.7  x86_64:

    8  wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
   10  rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
   11  rpm -K rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
   12  rpm -i rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
   13  rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
   14  rpm -Uvh http://dl.atrpms.net/el5-x86_64/atrpms/stable/atrpms-repo-5-4.el5.x86_64.rpm
   15  yum update


Сравниваем Мальдивы И Филиппины по ценам

2011 September 11
Comments Off
Posted by shirker2006

http://www.mytravelcost.com/Maldives/compare-with-Philippines/

yum – command not found

2011 September 10
Comments Off
Posted by shirker2006

if u erased python by accident, yum will gone too

Download the package(s) and type rpm -Uvh <packagenames> as root or sudo rpm -Uvh <packagenames> as normal user

I used rpm -qpR yum-3.2.27-14.el6.noarch.rpm to get a list of dependencies for yum, hope that gets all off them in one go:

Download all the packages with the following code block:

wget http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/python-2.6.5-3.el6.x86_64.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/python-libs-2.6.5-3.el6.x86_64.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/python-iniparse-0.3.1-2.1.el6.noarch.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/pygpgme-0.1-18.20090824bzr68.el6.x86_64.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/python-urlgrabber-3.9.1-7.el6.noarch.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/python-pycurl-7.19.0-5.el6.x86_64.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/rpm-python-4.8.0-12.el6.x86_64.rpm \
http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/yum-3.2.27-14.el6.noarch.rpm \

http://ftp2.scientificlinux.org/linux/scientific/6.0/x86_64/os/Packages/yum-metadata-parser-1.1.2-14.1.el6.x86_64.rpm

Install them as follows:

rpm -Uhv py*.rpm \
yum*.rpm \
rpm-py*.rpm


from http://serverfault.com/questions/297088/scientific-linux-how-to-install-yum-using-rpm

web interface for Bind DNS server (link)

2011 September 9
Comments Off
Posted by shirker2006

http://www.debianhelp.co.uk/bindweb.htm

PSD icons for web design (link)

2011 September 5
Comments Off
Posted by shirker2006

http://www.psdgraphics.com/category/icons/

xenserver from USB flash (RU) (LINK)

2011 September 4
Comments Off
Posted by shirker2006

http://habrahabr.ru/blogs/virtualization/123970/#habracut

check queue on asterisk and send email, if nobody logged in

2011 September 1
Comments Off
Posted by shirker2006
#!/bin/bash

VAR1=`asterisk -rx "show queue $1" | grep 'in use\|Busy\|pause' | grep -v Unavailable}|awk '{print $1}'|wc -l`
#echo $VAR1
if [ $VAR1 = "0" ]; then
echo "Nobody logged in to $1!!" | mail -s "Nobody logged in to $1!!" boss@company.net
else
echo "Everything is ok"
#echo $VAR1
fi

then add to cron:

* */5 * * * /root/check.sh CAMPAIGN-NAME

IPFILTER in freebsd

2011 August 31
Comments Off
Posted by shirker2006

http://odminblog.ru/nastroyka-programmnogo-firewall-na-baze-freebsd/#more-1458

Apache+nginx as gateway

2011 August 29
Comments Off
Posted by shirker2006

http://adw0rd.ru/2009/nginx-and-apache-install/

http://kubuntu.ru/node/6732

filter for gnudialer

2011 August 29
Comments Off
Posted by shirker2006

index.php:

<?php

include("./init.php");

$eq = "pass=".$pass."&mode=login";

	if ($fp = fsockopen ($server_ip, 80, $errno, $errstr, 20))
		{
			$request ="POST /cgi-bin/dialeradmin.cgi HTTP/1.1\r\n";
			$request.="Host: ".$server_ip."\r\n";
			$request.="User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 GTB5 (.NET CLR 3.5.30729)";
			$request.="Content-Type:application/x-www-form-urlencoded\r\n";
			$request.="Content-Length: ".strlen($eq)."\r\n";
			$request.="Connection: close\r\n\r\n";
                     //$request.="Connection: keep-alive\r\n\r\n";
			$request.=$eq."\r\n\r\n";

		$response ='';

		fwrite($fp, $request);
			while (!feof($fp)) {
			$response.=fread($fp,4096);
			}

	    fclose($fp);
   }

 //echo $response;

   $substr_count = substr_count($response,"GnuDialer Administration");
   //echo ($substr_count);
   if ( $substr_count >= 1){
   ?>

   <html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Set Filter</title>
 <style type="text/css">
.block1 {
    width: 300px;
    padding: 5px;
    padding-right: 20px;
    float: right;
   }
 </style>
</head>

<body>
<center>
<table height="140">
	<tr>
		<td><img border="0" src="http://192.168.11.11/agentflt/img/724carelogo.png" width="600" height="140"></td>
	</tr>
</table>

<table border="1" width="600" id="table1" height="180" style="border: 1px solid #008080" cellspacing="0" cellpadding="0" bordercolorlight="#008080" bordercolordark="#008080">
	<tr>
		<td align="center">
		<h2>Set your filter for <?php echo $company; ?> here:</h2>
		<form method="POST" action="request.php">

			<input type="text" name="flt1" value="" size="10" style="border: 1px solid #808080">&nbsp;&nbsp;&nbsp;
			<input type="text" name="flt2" value="" size="9" style="border: 1px solid #808080">&nbsp;&nbsp;&nbsp;

			<select size="1" name="ltype" style="border: 1px solid #808080">
			<option value="bus">Business</option>
			<option value="res">Residential</option>
			<option value="both">Both</option>
			</select>&nbsp;&nbsp;&nbsp;
                     Last updated:&nbsp;&nbsp; <input type="text" name="lastupdated" value="0" size="2" style="border: 1px solid #808080">
                    <br>

                     <div class="block1" >
                     <select size="1" name="id" style="border: 1px solid #808080">
			<option value="0">Use entire Database</option>
			<option value="id > 20000">id > 20000</option>
			<option value="id < 20000">id < 20000</option>
			</select>

                     <input type="submit" value="Submit" name="B1">
                     </div>
                    		</form>
		<p>&nbsp;</td>
	</tr>
</table>
<h2>
<?php echo $server_ip; ?>
</h2>

</center>
</body>

</html>
<?php
   }
   else{
   echo "<center><h1>Your password is wrong!</h1><br />";
   echo "<h2>check your setting!</h2></center>";
   }

?>

request.php

<?php

//error_reporting(E_ALL);

include("./init.php");

$flt1 = trim( $_POST['flt1'] );
$flt2 = trim( $_POST['flt2'] );
$ltype = trim( $_POST['ltype'] );
$lastupdated = trim( $_POST['lastupdated'] );
$id = $_POST['id'];

if ( !is_numeric( $lastupdated ))
   {
    $lastupdated = 0;
     }

$flt1 = htmlspecialchars(stripslashes($flt1));
$flt2 = htmlspecialchars(stripslashes($flt2));
$ltype = htmlspecialchars(stripslashes($ltype));

if (!empty( $flt1 )){
	$str1="listname+like+%27".$flt1."%25%27";
	}
	else{
	exit();
	}
if (!empty( $flt2 )){
    $str1="%28listname+like+%27".$flt1."%25%27+or+listname+like+%27".$flt2."%25%27%29";

}

switch($ltype)
{
	case "bus":
	$str2 = "+and+leadtype+like+%27Bus%25%27";
	  break;

	case "res":
    $str2 = "+and+leadtype+like+%27Res%25%27";
	  break;

	case "both":
    $str2 = "+and+%28leadtype+like+%27Bus%25%27+or+leadtype+like+%27Res%25%27%29";
	  break;
} 

$eq= "queue=".$company."&f_mode=none&filter=".$str1.$str2;
if ( $id != "0" ){
$eq.= urlencode( " AND $id" );
}
if ( $lastupdated != 0 ){
$eq.= urlencode(" and lastupdated < subdate(now(), $lastupdated)");
}
$eq.= "&filter0=".urlencode("(((disposition > -6 AND disposition < 6) AND disposition <> -3 AND disposition <> 3 AND disposition <> 0) AND attempts < 4)");
$eq.= "&filter1=".urlencode("(((disposition > -6 AND disposition < 6) AND disposition <> -3 AND disposition <> 3 AND disposition <> 0) AND (attempts > 3 AND attempts < 8) AND pickups > 0)");
$eq.= "&filter2=".urlencode("(((disposition > -6 AND disposition < 6) AND disposition <> -3 AND disposition <> 3 AND disposition <> 0) AND attempts > 7 AND pickups > 0)");
$eq.= "&filter3=".urlencode("(disposition = -3 OR disposition = 3)");
$eq.= "&filter4=".urlencode("(disposition = 0)");
//$eq.= "&filter5=".urlencode("(disposition = -7 AND attempts < 4)");
//$eq.= "&filter6=".urlencode("(disposition = -7 AND attempts > 3)");
//$eq.= "&filter7=".urlencode("");
//$eq.= "&filter8=".urlencode("");
//$eq.= "&filter9=".urlencode("");

$eq.= "&usetzfilter=false&skip=0&orderby=phone&mode=Save+Filter+Settings";

	if ($fp = fsockopen ($server_ip, 80, $errno, $errstr, 20))
		{
			$request ="POST /cgi-bin/dialeradmin.cgi HTTP/1.1\r\n";
			$request.="Host: ".$server_ip."\r\n";
			$request.="User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 GTB5 (.NET CLR 3.5.30729)";
			$request.="Content-Type:application/x-www-form-urlencoded\r\n";
			$request.="Content-Length: ".strlen($eq)."\r\n";
			$request.="Connection: keep-alive\r\n\r\n";
			$request.=$eq."\r\n\r\n";

                     $response ='';

		fwrite($fp, $request);
			while (!feof($fp)) {
			$response.=fread($fp,4096);
                       }
                     fclose($fp);
                  }

//echo $response;

?>

  <html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Your Request</title>
</head>

<body>
<center>
<table height="140">
	<tr>
		<td><img border="0" src="http://192.168.11.11/agentflt/img/724carelogo.png" width="600" height="140"></td>
	</tr>
</table>

<table border="1" width="600" id="table1" height="180" style="border: 1px solid #008080" cellspacing="0" cellpadding="0" bordercolorlight="#008080" bordercolordark="#008080">
	<tr>
		<td align="center">
		<h2>Your Request for <?php echo $company; ?>:</h2>

<?php
echo urldecode($str1.$str2);
?>
		<h2>is done!</h2>
		<a href="index.php">Go Back</a></td>
	</tr>
</table>
<h2>
<?php echo $server_ip; ?>
</h2>
</center>
</body>

</html>

init.php

<?php
$pass = "secret";
$server_ip = "192.168.0.12";
$company = "FirstCampaign";

?>

The list of ports and processes lsof -n -i -P

2011 August 28
Comments Off
Posted by shirker2006

The list of ports and processes using them can be obtained by running #lsof -n -i -P

add route to CentOS

2011 August 23
Comments Off
Posted by shirker2006

make new file /etc/sysconfig/network-scripts/route-eth1 or what device u have

add there

192.168.14.0/24 via 192.168.15.1

wget instead fetch

2011 August 21
Comments Off
Posted by shirker2006

/etc/make.conf :

FETCH_CMD=wget -c
DISABLE_SIZE=yes

pxe config clonezilla and esxi

2011 August 20
Comments Off
Posted by shirker2006

Chapter 2. Start from here

Clonezilla file

# Created by generate-pxe-menu! Do NOT edit unless you know what you are doing!
# Keep those comment "MENU DEFAULT" and "MENU HIDE"! Do NOT remove them.
# Note!!! If "serial" directive exists, it must be the first directive
default vesamenu.c32
timeout 300
prompt 0
noescape 1
MENU MARGIN 5
 MENU BACKGROUND ocswp.png
# Set the color for unselected menu item and timout message
 MENU COLOR UNSEL 7;32;41 #c0000090 #00000000
 MENU COLOR TIMEOUT_MSG 7;32;41 #c0000090 #00000000
 MENU COLOR TIMEOUT 7;32;41 #c0000090 #00000000
 MENU COLOR HELP 7;32;41 #c0000090 #00000000

# MENU MASTER PASSWD

say **********************************************************************
say Clonezilla, the OpenSource Clone System.
say NCHC Free Software Labs, Taiwan.
say clonezilla.org, clonezilla.nchc.org.tw
say THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY! USE AT YOUR OWN RISK!
say **********************************************************************

# Allow client to edit the parameters
ALLOWOPTIONS 1

# simple menu title
#MENU TITLE clonezilla.org, clonezilla.nchc.org.tw

#label Clonezilla Live
#MENU LABEL Clonezilla Live
#kernel images/clonezilla/i486/live/vmlinuz
#append initrd=images/clonezilla/i486/live/initrd.img boot=live live-config noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" vga=788 nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs
# Since no network setting in the squashfs image, therefore if ip=frommedia, the network is disabled. That's what we want.

label Clonezilla live
  MENU DEFAULT
  # MENU HIDE
  MENU LABEL Clonezilla live (Default settings, VGA 800x600)
  # MENU PASSWD
  kernel images/clonezilla/i486/live/vmlinuz
  append initrd=images/clonezilla/i486/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" vga=788 ip=frommedia  nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs

  TEXT HELP
  * Clonezilla live version: 1.2.9-19-i486. (C) 2003-2011, NCHC, Taiwan
  * Disclaimer: Clonezilla comes with ABSOLUTELY NO WARRANTY
  ENDTEXT

MENU BEGIN Other modes of Clonezilla live
label Clonezilla live 1024x768
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Clonezilla live (Default settings, VGA 1024x768)
  # MENU PASSWD
  kernel images/clonezilla/i486/live/vmlinuz
  append initrd=images/clonezilla/i486/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" vga=791 ip=frommedia  nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs

  TEXT HELP
  VGA mode 1024x768. OK for most of VGA cards.
  ENDTEXT

label Clonezilla live 640x480
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Clonezilla live (Default settings, VGA 640x480)
  # MENU PASSWD
  kernel images/clonezilla/i486/live/vmlinuz
  append initrd=images/clonezilla/i486/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" vga=785 ip=frommedia  nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs

  TEXT HELP
  VGA mode 640x480. OK for most of VGA cards.
  ENDTEXT

label Clonezilla live (To RAM)
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Clonezilla live (To RAM. Boot media can be removed later)
  # MENU PASSWD
  kernel images/clonezilla/i486/live/vmlinuz
  append initrd=images/clonezilla/i486/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" noprompt vga=788 toram=filesystem.squashfs ip=frommedia  nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs

  TEXT HELP
  All the programs will be copied to RAM, so you can
  remove boot media (CD or USB flash drive) later
  ENDTEXT

label Clonezilla live without framebuffer
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Clonezilla live (Safe graphic settings, vga=normal)
  # MENU PASSWD
  kernel images/clonezilla/i486/live/vmlinuz
  append initrd=images/clonezilla/i486/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" ip=frommedia nomodeset vga=normal nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs

  TEXT HELP
  Disable console frame buffer support
  ENDTEXT

label Clonezilla live failsafe mode
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Clonezilla live (Failsafe mode)
  # MENU PASSWD
  kernel images/clonezilla/i486/live/vmlinuz
  append initrd=images/clonezilla/i486/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" acpi=off irqpoll noapic noapm nodma nomce nolapic nosmp ip=frommedia nomodeset vga=normal nosplash fetch=tftp://192.168.11.11/images/clonezilla/i486/live/filesystem.squashfs

  TEXT HELP
  acpi=off irqpoll noapic noapm nodma nomce nolapic
  nosmp nomodeset vga=normal nosplash
  ENDTEXT

MENU END
label local
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Local operating system in harddrive (if available)
  # MENU PASSWD
  # 2 method to boot local device:
  # (1) For localboot 0, it is decided by boot order in BIOS, so uncomment the follow 1 line if you want this method:
  # localboot 0

  # (2) For chain.c32, you can assign the boot device.
  # Ref: extlinux.doc from syslinux
  # Syntax: APPEND [hd|fd]<number> [<partition>]
  # [<partition>] is optional.
  # Ex:
  # Second partition (2) on the first hard disk (hd0);
  # Linux would *typically* call this /dev/hda2 or /dev/sda2, then it's "APPEND hd0 2"
  #
  kernel chain.c32
  append hd0
  TEXT HELP
  Boot local OS from first hard disk if it's available
  ENDTEXT

MENU BEGIN Memtest & FreeDOS

# Note! *.bin is specially purpose for syslinux,
# Do NOT use memtest.bin, use memtest instead of memtest.bin
label memtest
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Memory test using Memtest86+
  # MENU PASSWD
  kernel images/clonezilla/i486/live/memtest
  TEXT HELP
  Run memory test using Memtest86+
  ENDTEXT

label FreeDOS
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL FreeDOS
  # MENU PASSWD
  kernel memdisk
  append initrd=images/clonezilla/i486/live/freedos.img
  TEXT HELP
  Run FreeDOS
  ENDTEXT

MENU END
label iPXE
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Network boot via iPXE
  # MENU PASSWD
  kernel images/clonezilla/i486/live/ipxe.lkn
  TEXT HELP
  Run iPXE to enable network (PXE) boot
  ENDTEXT

MENU END

esxi-64 file

default menu.c32
menu title VMware VMvisor Boot Menu
timeout 80

label ESXi Installer
menu label ^ESXi Installer
kernel images/esxi/4.1.0_x86_64/mboot.c32
append images/esxi/4.1.0_x86_64/vmkboot.gz ks=http://192.168.11.11/repo/vmware/esxi-ks.cfg --- images/esxi/4.1.0_x86_64/vmkernel.gz --- images/esxi/4.1.0_x86_64/sys.vgz --- images/esxi/4.1.0_x86_64/cim.vgz --- images/esxi/4.1.0_x86_64/ienviron.vgz --- images/esxi/4.1.0_x86_64/install.vgz
label ^Boot from local disk
menu label ^Boot from local disk
localboot 0x80

My esxi-ks.cfg file

#### /export/linux/vmware/esxi-ks.cfg ##############
accepteula
rootpw 724megacare
autopart --firstdisk --overwritevmfs

install url http://192.168.11.11/repo/vmware
#network --bootproto=static --ip=192.168.11.13 --gateway=192.168.11.1 --nameserver=192.168.11.1 --netmask=255.255.255.0 --hostname=nova --addvmportgroup=0
#reboot

Russin article about ESXi 4.1 PXE

from http://lib.ru/unixhelp/vmware.txt

Origin: http://communities.vmware.com/blogs/vmwareinsmb/2010/07/13/esxi-41-scripted-installation-via-pxe-and-kickstart
Иметь установленными: dhcpd, tftpd,  apache, syslinux, pxeboot

# Настройки приведены для openSUSE 11.3 - для других Linux надо
# делать очевидные замены, типа  zypper == >  apt-get, yum и т.д.

zypper install tftp dhcp-server syslinux qiwi-pxeboot apache2

#### /etc/dhcpd.conf #### задать инсталляционным адресам загрузчик pxelinux
option domain-name-servers 192.168.1.4;
default-lease-time 86400;
max-lease-time 604800;
authoritative;

subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.151 192.168.163.180;
filename "pxelinux.0";
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.1.255;
option routers 192.168.1.1;
}

# А еще лучше - индивидуально задать на mac-адрес хоста
host esxi02 {
  hardware ethernet 08:00:07:26:c0:a5;
  fixed-address 192.168.1.22;
filename "pxelinux.0";
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.1.255;
option routers 192.168.1.1;
}

################################

Смотрим в /etc/xinetd.d/tftp - где корневая директория tftp, например
         server_args         = -s /srv/tftpboot
меняем   disable             = yes
на       disable             = no
и перезапускаем xinetd
service xinetd restart

# Размещаем в ней загрузчик pxelinux
/srv/tftpboot/pxelinux.0
#  и его конфигуратор
# /srv/tftpboot/pxelinux.cfg/default :

DISPLAY boot.txt
DEFAULT ESX_4.1_install

LABEL ESX_4.1_install
kernel vmware/esx4.1/mboot.c32
append vmware/esx4.1/vmkboot.gz ks=http://192.168.1.4/linux/vmware/esxi-ks.cfg --- vmware/esx4.1/vmkernel.gz --- vmware/esx4.1/sys.vgz --- vmware/esx4.1/cim.vgz --- vmware/esx4.1/ienviron.vgz --- vmware/esx4.1/install.vgz

в подкаталог tftpd сервера монтируем инсталляционный CDROM ESXi

mkdir -p /srv/tftpboot/vmware/esx4.1
mount /dev/cdrom /srv/tftpboot/vmware/esx4.1
или
mount -o loop /export/vmware/ESXi4.1.iso /srv/tftpboot/vmware/esx4.1

# Ostalosx sdelatx kick-start-файл, и можно приступать

#### /export/linux/vmware/esxi-ks.cfg ##############
accepteula
rootpw supersecretpassword
autopart --firstdisk --overwritevmfs

install url http://192.168.1.4/linux/vmware
network --bootproto=static --ip=192.168.1.22 --gateway=192.168.1.1 --nameserver=192.168.1.4 --netmask=255.255.255.0 --hostname=esxi02 --addvmportgroup=0
reboot
####################################################

pxe installation on CentOS

2011 August 18
Comments Off
Posted by shirker2006

This article describes, how to make PXE on CentOS with multi level menu.

Finally i get it work with few OS in list, submenu CloneZilla and other submenu ESXi

working config (/tftpboot/pxelinux.cfg/default):

default menu.c32 menu title Choose operation system to install timeout 80 LABEL linux menu label CentOS 5.6 linux x86_64 KERNEL images/centos/x86_64/5.6/isolinux/vmlinuz APPEND ks initrd=images/centos/x86_64/5.6/isolinux/initrd.img ramdisk_size=100000 ksdevice=eth2 ip=dhcp LABEL linux2 menu label CentOS 6.0 linux x86_64 KERNEL images/centos/x86_64/6.0/isolinux/vmlinuz APPEND ks initrd=images/centos/x86_64/6.0/isolinux/initrd.img ramdisk_size=100000 ksdevice=eth2 ip=dhcp LABEL linux3 menu label CentOS 6.0 linux i386 minimal KERNEL images/centos/i386/6.0-min/isolinux/vmlinuz APPEND ks initrd=images/centos/i386/6.0-min/isolinux/initrd.img ramdisk_size=100000 ksdevice=eth2 ip=dhcp LABEL Clonezilla MENU LABEL Clonezilla_x64 KERNEL menu.c32 APPEND pxelinux.cfg/clonezilla-64 LABEL Clonezilla2 MENU LABEL Clonezilla i486 KERNEL menu.c32 APPEND pxelinux.cfg/clonezilla LABEL ESXi MENU LABEL ESXI x86_64 KERNEL menu.c32 APPEND pxelinux.cfg/esxi-64

Working config with diskless boot  (/tftpboot/pxelinux.cfg/default):

default menu.c32
menu title Choose operation system to boot/install
timeout 20
prompt 0
NOESCAPE 1
ONTIMEOUT Ubuntu

LABEL Ubuntu
MENU DEFAULT
KERNEL vmlinuz
APPEND root=/dev/nfs initrd=initrd.img nfsroot=192.168.11.11:/nfsroot/sda1 ip=dhcp rw

LABEL linux
menu label CentOS 5.6 linux x86_64
KERNEL images/centos/x86_64/5.6/isolinux/vmlinuz
APPEND ks initrd=images/centos/x86_64/5.6/isolinux/initrd.img ramdisk_size=100000 ksdevice=eth2 ip=dhcp

LABEL linux2
menu label CentOS 6.0 linux x86_64
KERNEL images/centos/x86_64/6.0/isolinux/vmlinuz
APPEND ks=http://192.168.0.1/repo/centos/ks/6.0/x86_64/ks.cfg initrd=images/centos/x86_64/6.0/isolinux/initrd.img ramdisk_size=100000 ksdevice=eth2 ip=dhcp

LABEL linux3
menu label CentOS 6.0 linux i386 minimal
KERNEL images/centos/i386/6.0-min/isolinux/vmlinuz
APPEND ks initrd=images/centos/i386/6.0-min/isolinux/initrd.img ramdisk_size=100000 ksdevice=eth2 ip=dhcp

LABEL Clonezilla
MENU LABEL Clonezilla_x64
KERNEL menu.c32
APPEND pxelinux.cfg/clonezilla-64

LABEL Clonezilla2
MENU LABEL Clonezilla i486
KERNEL menu.c32
APPEND pxelinux.cfg/clonezilla

LABEL ESXi
MENU LABEL ESXI x86_64
KERNEL menu.c32
APPEND pxelinux.cfg/esxi-64

pxelinux.cfg/clonezilla and pxelinux.cfg/esxi-64 conf files here

Kick Starter file (I set only URL for network installation)

http://192.168.0.1/repo/centos/ks/6.0/x86_64/ks.cfg :

url --url http://192.168.0.1/repo/centos/6.0/x86_64/

Duding CentOS installation choose from URL

  1. Be sure you on .DEFAULT. VLAN
  2. set in BIOS boot from LAN
  3. boot machine
  4. select from menu distribution of CentOS and architecture that you like

During the boot set right URL for installation. start from here: http://192.168.0.1/repo/centos/. For CentOS 5.6 x86_64 the URL will be http://192.168.0.1/repo/centos/5.6/x86_64

[root@gnom 6.0]# pwd
/var/www/html/repo/centos/6.0
[root@gnom 6.0]# ls -la
x86_64 -> /tftpboot/images/centos/x86_64/6.0
[root@gnom 6.0]# ls /tftpboot/images/centos/x86_64/6.0
CentOS_BuildTag  images                    repodata                       RPM-GPG-KEY-CentOS-Testing-6
EFI              isolinux                  RPM-GPG-KEY-CentOS-6           TRANS.TBL
EULA             Packages                  RPM-GPG-KEY-CentOS-Debug-6
GPL              RELEASE-NOTES-en-US.html  RPM-GPG-KEY-CentOS-Security-6

dhcpd.conf from working server:

[root@gnom ~]# cat /etc/dhcpd.conf
#
# DHCP Server Configuration file.
#   see /usr/share/doc/dhcp*/dhcpd.conf.sample
#
allow booting;
allow bootp;

ddns-updates                on;
ddns-update-style           interim;

subnet 192.168.66.0 netmask 255.255.255.0 {
  range 192.168.66.30 192.168.66.254;
  option broadcast-address 192.168.66.255;
  option routers 192.168.66.2;
  option domain-name-servers 192.168.66.2;
  next-server 192.168.66.3;
  filename "/pxelinux.0";
}

PXE Setup (from CenOS Wiki)

* yum install tftp-server

* vi /etc/xinetd.d/tftp and change disable to ‘no’

disable = no

* restart xinetd

service xinetd restart

* Install syslinux

yum install syslinux

* Copy needed files from syslinux to the tftpboot directory

cp /usr/lib/syslinux/pxelinux.0 /tftpboot
cp /usr/lib/syslinux/menu.c32 /tftpboot
cp /usr/lib/syslinux/memdisk /tftpboot
cp /usr/lib/syslinux/mboot.c32 /tftpboot
cp /usr/lib/syslinux/chain.c32 /tftpboot

* Create the directory for your PXE menus

mkdir /tftpboot/pxelinux.cfg

* Create a base directory for images. Create directories for each CentOS release you are supporting.

mkdir -p /tftpboot/images/centos/i386/3.0
mkdir -p /tftpboot/images/centos/i386/3.1
mkdir -p /tftpboot/images/centos/x86_64/3.0
mkdir -p /tftpboot/images/centos/x86_64/3.1
mkdir -p /tftpboot/images/centos/i386/4.0
mkdir -p /tftpboot/images/centos/i386/4.1
mkdir -p /tftpboot/images/centos/x86_64/4.0
mkdir -p /tftpboot/images/centos/x86_64/4.1
mkdir -p /tftpboot/images/centos/i386/5.0
mkdir -p /tftpboot/images/centos/i386/5.1
mkdir -p /tftpboot/images/centos/x86_64/5.0
mkdir -p /tftpboot/images/centos/x86_64/5.1

* For each “Release” and “ARCH” Copy vmlinuz and initrd.img from /images/pxeboot/ directory on “disc 1″ of that $Release/$ARCH to /tftpboot/images/centos/$ARCH/$RELEASE

* Add this to your existing or new /etc/dhcpd.conf.

Note: xxx.xxx.xxx.xxx is the IP address of your PXE server

allow booting;
allow bootp;
option option-128 code 128 = string;
option option-129 code 129 = text;
next-server xxx.xxx.xxx.xxx;
filename "/pxelinux.0";

* Restart DHCP server

service dhcpd restart

HowTo mount iso and copy/rsync to tftpboot:

 1004  mount -t iso9660 -o loop /var/www/html/it/isos/linux/centos/CentOS-5.6-x86_64-bin-DVD/CentOS-5.6-x86_64-bin-DVD-1of2.iso /mnt
 1005  ls /mnt
 1006  rsync -avz /mnt/ /tftpboot/images/centos/x86_64/5.6/
 1008  umount -f /mnt
 1009  mount -t iso9660 -o loop /var/www/html/it/isos/linux/centos/CentOS-5.6-x86_64-bin-DVD/CentOS-5.6-x86_64-bin-DVD-2of2.iso /mnt
 1010  ls /mnt/
 1011  rsync -avz /mnt/ /tftpboot/images/centos/x86_64/5.6/
 1012  umount -f /mnt
 1013  mount -t iso9660 -o loop /var/www/html/it/isos/linux/centos/CentOS-6.0-x86_64/CentOS-6.0-x86_64-bin-DVD1.iso /mnt
 1014  rsync -avz /mnt/ /tftpboot/images/centos/x86_64/6.0/
 1015  umount -f /mnt
 1016  mount -t iso9660 -o loop /var/www/html/it/isos/linux/centos/CentOS-6.0-x86_64/CentOS-6.0-x86_64-bin-DVD2.iso /mnt
 1017  rsync -avz /mnt/ /tftpboot/images/centos/x86_64/6.0/
 1018  mkdir  /tftpboot/images/clonezilla
 1019  mkdir  /tftpboot/images/clonezilla/amd64
 1020  mount -t iso9660 -o loop /var/www/html/it/isos/clonezilla/clonezilla-live-1.2.9-19-amd64.iso /mnt
 1021  rsync -avz /mnt/ /tftpboot/images/clonezilla/amd64/
 1022  umount -f /mnt
 1023  mount -t iso9660 -o loop /var/www/html/it/isos/linux/centos/CentOS-6.0-i386-minimal/CentOS-6.0-i386-minimal.iso /mnt
 1024  rsync -avz /mnt/ /tftpboot/images/centos/i386/6.0-min/

Or copy whole distributive directly from centos mirror by rsync

/usr/bin/rsync -iavrt rsync://mirror.nexicom.net/CentOS/6.0/os/x86_64/ /tftpboot/images/centos/x86_64/6.0/

yum install webmin

2011 August 12
Comments Off
Posted by shirker2006
vim /etc/yum.repos.d/webmin.repo
[Webmin]
name=Webmin Distribution Neutral
#baseurl=http://download.webmin.com/download/yum
mirrorlist=http://download.webmin.com/download/yum/mirrorlist

You should also fetch and install my GPG key with which the packages are signed, with the commands :

wget http://www.webmin.com/jcameron-key.asc
rpm --import jcameron-key.asc

You will now be able to install with the command :

yum install -y webmin --enablerepo=Webmin

multiply VLANs CentOs

2011 August 12
Comments Off
Posted by shirker2006
 vconfig add eth0 41

[root@heart ~]# cat /etc/sysconfig/network-scripts/ifcfg-vlan41
VLAN=yes
VLAN_NAME_TYPE=VLAN_PLUS_VID_NO_PAD
DEVICE=vlan41
PHYSDEV=eth0.41
BOOTPROTO=static
ONBOOT=yes
TYPE=Ethernet
IPADDR=192.168.41.7
NETMASK=255.255.255.0

[root@heart ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0.41
VLAN=yes
DEVICE=eth0.41
BOOTPROTO=static
ONBOOT=yes
TYPE=Ethernet
IPADDR=192.168.41.7
NETMASK=255.255.255.0

[root@heart ~]# service network restart
Shutting down interface eth0.41:                           [  OK  ]
Shutting down interface eth0:                              [  OK  ]
Shutting down loopback interface:                          [  OK  ]
Bringing up loopback interface:                            [  OK  ]
Bringing up interface eth0:                                [  OK  ]
Bringing up interface eth0.41:                             [  OK  ]
Bringing up interface vlan41:                              [  OK  ]
[root@heart ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:18:F3:6C:45:C6
          inet addr:192.168.11.7  Bcast:192.168.11.255  Mask:255.255.255.0
          inet6 addr: fe80::218:f3ff:fe6c:45c6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:382278 errors:0 dropped:15 overruns:0 frame:15
          TX packets:7215 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:29140778 (27.7 MiB)  TX bytes:1575096 (1.5 MiB)
          Interrupt:16

eth0.41   Link encap:Ethernet  HWaddr 00:18:F3:6C:45:C6
          inet addr:192.168.41.7  Bcast:192.168.41.255  Mask:255.255.255.0
          inet6 addr: fe80::218:f3ff:fe6c:45c6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:44 errors:0 dropped:0 overruns:0 frame:0
          TX packets:24 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:3082 (3.0 KiB)  TX bytes:1488 (1.4 KiB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:370 errors:0 dropped:0 overruns:0 frame:0
          TX packets:370 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:73790 (72.0 KiB)  TX bytes:73790 (72.0 KiB)

vlan41    Link encap:Ethernet  HWaddr 00:18:F3:6C:45:C6
          inet addr:192.168.41.7  Bcast:192.168.41.255  Mask:255.255.255.0
          inet6 addr: fe80::218:f3ff:fe6c:45c6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:768 (768.0 b)

daily cp backup of some dir

2011 August 9
Comments Off
Posted by shirker2006

to cron:

0 12 * * *  cp -R /etc/asterisk  /var/backup/asterisk`date +%m%d%y`

Disks sdb, sdc contain BIOS RAID metadata (cannot install CentOs 6)

2011 August 6
Comments Off
Posted by shirker2006

I encountered that problem during installation CentOS 6.0.  Google search helped me very much, but I dont remember, where did i get that article.. maybe even Yahoo answers…

Warning

Disks sdb, sdc contain BIOS RAID metadata, but are not
part of any recognized BIOS RAID sets. Ignorning disks sdb,
sdc.

I experienced the same problem. What finally worked for me is:

1) boot into rescue mode
2) execute dd if=/dev/zero of=/dev/sda

# <Ctrl>- z
# bg
# killall -USR1 dd

then wait………………………………………………………………………………………………………
…………………………………………………………………………………………………………………..
…………………………………………………………………………………………………………………..
…………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………….
……………………………………………………..

[bash] send to background

2011 August 5
Comments Off
Posted by shirker2006

Using the Job Control of bash to send the process into the background:

> [crtl]+z 
> bg

Tutorial – Dial Plan

2011 August 5
Comments Off
Posted by shirker2006

Setting up a dial plan

A dial plan is a mechanism that you can use to tell VoXaLot which providers should be used for which calls. For example, lets say that you have registered two providers’ details with VoXaLot, and one of them has good rates for overseas calls, and the other has good rates for domestic calls. You can use a dial plan to describe your international dialling prefix and VoXaLot will select the appropriate provider for you so as to minimise your call costs.

You can have as many dial plan entries as you need. Each dial plan entry has a field called Priority that is used to determine what order the plans get evaluated by VoXaLot. You can choose to use either the Simple or Advanced dial plan descriptions, depending on your level of technical expertise.


Simple Dial Plans

  1. Once you are logged in, click on the Dial Plans link in the right-hand menu. From there, you can either add new dial plans or edit existing ones.
  2. To add a new entry, click on the [Add] link
  3. On this screen, you will be asked to enter some information about your dial plan.
    • A priority that helps VoXaLot decide what order to check the dial plan entries. When you have more than one, the lower the number, the earlier this plan entry gets checked.
    • A simple pattern matching rule
    • The value that is used for the pattern matching
    • Which provider to use when this pattern is matched.

Advanced Dial Plans

To get the real benefit of dial plans, you need to use advanced dial plans. The notation is different to standard ATA boxes however it is not hard to learn. So first we will look at how the dial plans work. An advanced dial plan has 5 main sections:

  1. The Priority (straight forward – what order is the dial plan executed)
  2. Pattern (a string that either matches the dialled number or not)
  3. Replacement (instructions on what to replace the matched phone number with)
  4. Provider (who to send the matched number to)
  5. ENUM Replacement (instructions on what to replace the matched phone number with to use ENUM)

So let’s look at each section one at a time.

1. Priority

This is easy. It is just the numerical order in which VoXaLot will search your dial plans trying to find a match. It will start at the lowest numbered priority dial plan, check for a match. If no match, it will go to the next lowest numbered priority dial plan, and keep going until it finds the first match, and then send the dialled number to the VSP specified when a match is found.

2. Pattern

A pattern is a string of characters against which a dialled number will be compared. The dialled number with either “match” or “not match” the pattern. There are only a few rules for the pattern

    • All dial plan patterns must begin with an underscore _
    • X matches any digit from 0-9
    • Z matches any digit from 1-9
    • N matches any digit from 2-9
    • [ ] matches any digits in the brackets. eg [25] will match 2 and 5, but will not match 0,1,3,4 etc. [2-5] will match 2, 3, 4, 5, but will not match 0,1,6,7 etc. [02-5] will match 0,2,3,4,5 but will not match 1,6,7 etc.
    • . wildcard (full stop), matches one or more characters

Here are some examples

      _9XXXXXXX matches 98175555 etc
      _9817XXXX matches 98175555 but not 92595555 etc
      _13ZXX. matches 131241 but not 1300 123 456 (because the Z excludes 0 as an option)

3. Replacement

Replacment is the method to replace (or add) one or more digits to your dialled number after it has been matched. So if the dialled number matches the pattern in step 2. above, then you can apply a replacement.

The replacment syntax is Prefix${EXTEN:count1:count2}Suffix where count1 and count 2 are optional. Let’s look at this in parts.

    1. $[EXTEN}
      This is the default replacement string, and it

IS 

      the dialled number.
      eg if you dialled 98175555 and it matched your pattern in step 2. above, then ${EXTEN} = 98175555.
    1. Count1
      Count1 can be a positive integer or a negative integer.
      If it is a positive integer then we skip that number of digits from the left.
      eg if you dialled 0298175555 and it matched your pattern in step 2. above, then
      ${EXTEN:2} = 98175555
      ${EXTEN:6} = 5555 etc
      If Count1 is a negative integer, you drop that number of digits off of the end of the string.
      eg if you dialled 0298175555 and it matched your pattern in step 2. above, then
      ${EXTEN:-4} = 029817
      ${EXTEN:-6} = 0298
    1. Count2
      Count2 can only be used if Count1 is used. Together they specify a starting point in a dialled phone number, and the number of characters to be taken. Count2 can only be a positive integer and indicates how many digits should be counted from the point indicated by Count1. eg if you dialled 0298175555 and it matched your pattern in step 2. above, then ${EXTEN:2:4} = 9817 (ie skip the first 2 digits, then take the next 4 digits
    1. Prefix and Suffix
      You may also add prefixes and suffixes to your dialled number.
      eg if you dialled 98175555 and it matched your pattern in step 2. above, then 612${EXTEN} = 61298175555
      eg2 if you dialled 0298175555 and it matched your pattern in step 2. above, then 61${EXTEN:1} = 61298175555

4. Provider

Simply select one of the VSPs that you have registered with VoXaLot from the drop down list. This provider will be used for all calls matching the pattern you have set up (including those that matched the pattern but didn't find an ENUM match - see point 5 below).

5. ENUM Replacement

ENUM replacement follows exactly the same rules as covered in step 3 above, however it allows for a different replacement string to be used to find a ENUM match. You would want to use ENUM replacement so that VoXaLot can first try to find an ENUM match for your dialled number. Some VSPs (such as Engin) wont allow you to call a number in the format 612 xxxx xxxx. However ENUM must use this format. VoXaLot therefore caters for both. This is how it would work:

  1. you dial 98175555
  2. It finds a match in your number pattern
  3. The dial plan has Repacement set as ${EXTEN} = 98175555
  4. Your Provider was set as Engin
  5. Your ENUM Replacment was set as 612${EXTEN} = 61298175555

VoXaLot first checks to see if there is an ENUM match for 61298175555. If not, it goes ahead and routes the number 98175555 to Engin and the call is places as normal.


Entering Advanced Dial Plans

    1. As with the Simple plan entries, click on the Dial Plans link in the right-hand menu.
    1. Click on the [Add] link and you should see a page like this one:
    1. Click on the [Advanced Mode] link at the top of the Dial Entry panel and you will see a page like this one:
    1. On this screen, you will be asked to enter some information about your dial plan entry.
        • A priority that helps VoXaLot decide what order to check the dial plan entries. When you have more than one, the lower the number, the earlier this plan gets checked.
        • A pattern matching rule that uses a sequence of special symbols to match numbers (see below)
        • REPLACEMENT: The value that will actually be dialled via your VSP when the pattern is matched. (NB See ENUM REPLACEMENT below)
        • Which provider to use when this pattern is matched.
      • (Optional) ENUM REPLACEMENT: The value that will used to check for a ENUM match before the call is routered to your VSP. If there is a match, then the call will be routed for free. If this is left blank, no ENUM checking is performend.
        NB ENUM phone numbers must use the format Country Code, Area Code, Number (61 x xxxx xxxx for Australian numbers).

In the example above, any number that begins with 04 will be checked for a ENUM match, then sent to “Pennytel” if no match is found.

If you are unsure of what value to put in any of the fields, please feel free to visit oursupport forums.


Using Dial Plans

You can use VoXaLot dial plans in the same way that you use dial plans with a standard ATA. There are a couple of distinct advantages of VoXaLot dial plans over an ATA dial plan.

  • Only advanced ATAs have the capability to use more than 1 VSP. With VoXaLot you can use as many VSPs as you like.
  • VoXaLot allows you to modify the dialled number in 2 different formats: one format to be checked against ENUM, and a different format to by routed to your VSP if an ENUM match is not found. This is useful if your VSP doesn’t accept internationl number formats for regular dialling (ie Engin).

Examples of Using dial plans

Here is a set of sample dial plans that could be set up at VoXaLot to leverage the benefits it offers. Obviously these are not the only dial plans possible. You can create any dial plan you want/need using the rules outlined above.

Priority _________Pattern________ ___Replacement___ Provider ENUM Replacement______ Comments
10 _NXXXXXXX 02${EXTEN} Engin 612${EXTEN} If you call any 8 digit number starting with 2-9, then prepend 612 for ENUM and prepend 02 for your VSP. This assumes you are in the Sydney local call region.
20 _0[235-9]XXXXXXXX ${EXTEN} Engin 61${EXTEN:1} If you call any STD number, then remove the 0 from the front, prepend 61 for ENUM. If no match, pass the number as is to your VSP.
30 _1[38]00XXXXXX ${EXTEN} Engin 61${EXTEN} If you call 1300 or 1800 then prepend 61 for ENUM.
40 _04XXXXXXXX ${EXTEN} Pennytel 61${EXTEN:1} If you call any mobile number, then remove the 0 from the front, prepend 61 for ENUM. If no match, pass the number as is to Pennytel.
50 _0011. ${EXTEN} Engin ${EXTEN:4} If you make an international call, scrape away the 0011
60 _XXX. ${EXTEN}

HOW TO SHUTDOWN AND REBOOT WITHOUT SUDO PASSWORD?

2011 August 2
Comments Off
Posted by shirker2006

by Vladimir Mitrofanov

if you are gnome user, you probably enjoy shutdown with just a click on the dialog. In order to shutdown from command line, you are requested to be either root or using sudo, such as
sudo shutdown -h now
For more detail examples of shutdown, continue to read here.
With sudo, you need to type your password. Sometimes it will be more convenient to us if we are able to shutdown without sudo. Is it possible?
The answer is yes, there are two ways to do that (Any other ways available?)
1. Adding suid mode to /sbin/shutdown
2. Modify /etc/sudoers with visudo
1. Adding suid mode to /sbin/shutdown
By adding suid mode to shutdown command, you are allowing regular user to run shutdown command as root.

sudo chmod u+s /sbin/shutdown

Check out examples of chmod here.
Now you can run shutdown without needing sudo.
2. Modify /etc/sudoers with visudo
This seems to be proper way to allow a command to run as root from specified users without needing to type password.

sudo visudo

By running visudo, it leads to edit /etc/sudoers.
Adding the line below to that file, assume mysurface is the user that allow to shutdown without password.

mysurface ALL = NOPASSWD: /sbin/shutdown

For ubuntu, usually the default user is in the %admin group. Therefore, you can also allow all users from the %admin group to shutdown without password.

%admin ALL = NOPASSWD: /sbin/shutdown

In fact, you still need sudo to shutdown, but this time you do not need to specified password.

sudo shutdown -h now

You can also reboot the system by using shutdown command too.

sudo shutdown -r now

Related Posts
Shutdown/Reboot using ’shutdown’
It have a lot of way to shutdown/reboot your machine, the easier way is using shutdown button in gnome or KDE menu ;p Th…
shutdown using init
init are usually use to initialize linux runlevel, but 0 are run level of halt and 6 are run level of reboot. Therefo…
sudo is different from su
Some of the distro uses sudo to gaim access to run root privilage commands. But some of the distro do not include sudo b…

vicidial from scratch (not finished)

2011 August 2
Comments Off
Posted by shirker2006
yum -y upgrade
yum -y update
reboot
yum -y upgrade
yum -y install gcc gcc-c++ kernel-devel bison openssl openssl-devel perl perl-Net-SSLeay perl-Crypt-SSLeay
libtermcap-devel ncurses-devel doxygen curl-devel newt-devel mlocate lynx tar wget nmap bzip2 mod_ssl crontabs
vixie-cron speex speex-devel unixODBC unixODBC-devel libtool-ltdl libtool-ltdl-devel mysql-connector-odbc mysql
mysql-devel mysql-server php-mysql php-mbstring php-mcrypt flex screen libtiff-devel
   cd /tmp/
  wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
  rpm -Uvh epel-release-5-4.noarch.rpm
  wget http://rpms.famillecollet.com/enterprise/5/remi/x86_64/remi-release-5-8.el5.remi.noarch.rpm
  rpm -Uvh remi-release-5-8.el5.remi.noarch.rpm
  yum -y install --enablerepo=remi phpmyadmin

The first step is to add the Asterisk yum repositories to your CentOS or RedHat system. This is done by creating an
entry in the yum configuration directory (/etc/yum.repos.d by default).
Use the text editor of your choice to create a new file named “centos-asterisk.repo” in the “/etc/yum.repos.d”
folder. Add the following text to the file:

# vim /etc/yum.repos.d/centos-asterisk.repo
[asterisk-tested]
name=CentOS-$releasever - Asterisk - Tested
baseurl=http://packages.asterisk.org/centos/$releasever/tested/$basearch/
enabled=0
gpgcheck=0
#gpgkey=http://packages.asterisk.org/RPM-GPG-KEY-Digium
[asterisk-current]
name=CentOS-$releasever - Asterisk - Current
baseurl=http://packages.asterisk.org/centos/$releasever/current/$basearch/
enabled=1
gpgcheck=0
#gpgkey=http://packages.asterisk.org/RPM-GPG-KEY-Digium

Save the new file and create another named “centos-digium.repo” and insert the following text:

# vim /etc/yum.repos.d/centos-digium.repo
[digium-tested]
name=CentOS-$releasever - Digium - Tested
baseurl=http://packages.digium.com/centos/$releasever/tested/$basearch/
enabled=0
gpgcheck=0
#gpgkey=http://packages.digium.com/RPM-GPG-KEY-Digium
[digium-current]
name=CentOS-$releasever - Digium - Current
baseurl=http://packages.digium.com/centos/$releasever/current/$basearch/
enabled=1
gpgcheck=0
#gpgkey=http://packages.digium.com/RPM-GPG-KEY-Digium

Now you can see asterisk in yum search

yum search asterisk

Then perl modules

  perl -MCPAN -e shell

type in the command line
You will then go through CPAN setup, just hit ENTER for most prompts except
for the mirrors list, you will want to select at least 4 mirrors
- yes for manual configuration
- enter for the next 18 prompts
- for the “make install options” it’s a good idea to add UNINST=1
- enter for the next 4 prompts
- select your continent and country
- select a few cpan mirrors
- enter for the next 2 prompts
3.  Once you see the cpan> prompt you can begin installing modules
4.  If you’ve never installed cpan before you should probably install the
following modules first:   (say YES if asked to install prerequisites)

cpan> o conf prerequisites_policy follow
cpan> install MD5
cpan> install Digest::MD5
cpan> install Digest::SHA1
cpan> install readline (just hit Enter when it asks for operator)
cpan> install Bundle::CPAN
cpan> reload cpan

then you can install other modules:

cpan> install DBI
cpan> force install DBD::mysql (must at least have mysqlclientlibs installed)
cpan> install Net::Telnet
cpan> install Time::HiRes
cpan> install Net::Server
cpan> install Switch
cpan> install Mail::Sendmail
cpan> install Unicode::Map (needed for super list loader Excel)
cpan> install Jcode (needed for super list loader Excel)
cpan> install Spreadsheet::WriteExcel (needed for super list loader Excel)
cpan> install OLE::Storage_Lite (needed for super list loader Excel)
cpan> install Proc::ProcessTable (needed for super list loader Excel)
cpan> install IO::Scalar (needed for super list loader Excel)
cpan> install Spreadsheet::ParseExcel (needed for super list loader Excel)

- if Spreadsheet::ParseExcel fails to install try running the following:

cpan> force install Scalar::Util         (this will enable weak references)
cpan> install Spreadsheet::ParseExcel

- then quit cpan, you are done

Sox

[root@vicidialer ~]# yum -y install sox

php-eaccelerator

[root@vicidialer ~]# yum install --enablerepo=remi php-eaccelerator

balance

[root@vicidialer ~]# yum install -y balance

subversion

[root@vicidialer ~]# yum install -y subversion

mtop

[root@vicidialer ~]# echo “[dag]” > /etc/yum.repos.d/dag.repo
[root@vicidialer ~]# echo “name=Dag RPM Repository for Red Hat Enterprise Linux” >> /etc/yum.repos.d/dag.repo
[root@vicidialer ~]# echo “baseurl=http://apt.sw.be/redhat/el\$releasever/en/\$basearch/dag” >> /etc/yum.repos.d/dag.repo
[root@vicidialer ~]# echo “gpgcheck=0″ >> /etc/yum.repos.d/dag.repo
[root@vicidialer ~]# yum install mtop –enablerepo=dag

asterisk 1.4

 yum -y install asterisk14-core.i386 asterisk14-odbc.i386 asterisk14-configs.i386 asterisk14-addons-mysql.i386 asterisk14-addons-core.i386 asterisk14-addons.i386 asterisk14.i386 asterisk14-dahdi.i386 asterisk14-voicemail.i386 asterisk14-devel.i386

Install asterisk-perl via CPAN:

perl -MCPAN -e “install Asterisk::AGI; install Asterisk::Manager”

>>>>>>>

/usr/src/astguiclient/extras
\. /usr/src/astguiclient/agc_2.0.5/extras/MySQL_AST_CREATE_tables.sql
[goautodial]
disallow=all
allow=g729
allow=gsm
allow=ulaw
type=friend
username=username
secret=password
host=sip2.goautodial.com
dtmfmode=rfc2833
context=trunkinbound
qualify=yes
insecure=very
exten => _91XXXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log)
exten => _91XXXXXXXXXX,2,Dial(SIP/${EXTEN:1}@goautodial,,tTo)
exten => _91XXXXXXXXXX,3,Hangup
mkdir -p /usr/src/asterisk
cd /usr/src/asterisk
wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz

wget http://soft-switch.org/downloads/spandsp/spandsp-0.0.6pre18.tgz (or most current version)
wget http://downloads.digium.com/pub/libpri/libpri-1.4-current.tar.gz
tar -zxf dahdi-linux-complete-current.tar.gz
tar -zxf asterisk-1.6.1-current.tar.gz
tar -zxf spandsp-0.0.6pre18.tgz
tar -zxf libpri-1.4-current.tar.gz
tar -zxf asterisk-addons-1.6.1-current.tar.gz
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-1.8-current.tar.gz
Unpack it
tar xvfz asterisk-1.8-current.tar.gz
Go down to asterisk unpacked files directory
NOTE: You need to do a ls -l to see the directory created from the tar.
This is the latest release
cd asterisk-1.8.4.4
Download mp3 support files
contrib/scripts/get_mp3_source.sh
Run configure
./configure
Start menu based configuration
make menuconfig
select app_mysql, app_saycountpl, cdr_mysql, format_mp3, res_config_mysql
go to Extras Sound Packages
Select EXTRAS-SOUNDS-EN-GSM
Save & Exit
Run make
make
Then run the installer
make install

cpan install Не беси меня! все YES!!

2011 July 31
Comments Off
Posted by shirker2006

Markus Dehmann schrieb:

I use the CPAN shell to install a modules:

perl -MCPAN -e shell

But if the module needs a lot of other modules, CPAN asks me

“Do you want to add Date::Calc etc to the download chain? [y]”

and I have to hit enter a thousand times to confirm all the additional downloads.

Is there an option to allow these additional modules automatically?

Just change the prerequisites policy on the cpan shell by saying
cpan> o conf prerequisites_policy follow

If you want to change it back to prompting you everytime, give “ask”
as configuration value instead of “follow”.

-Chris

Installing the free G729 Codec for Asterisk

2011 July 31
Comments Off
Posted by shirker2006

http://www.blog.manhag.org/2010/05/installing-the-free-g729-codec-for-asterisk/

http://asterisk.hosting.lv/#bin

This tutorial will let you install the G729 Codec on an Asterisk installation in under 5 minutes.

cd /usr/lib/asterisk/modules

Download the codec

[root@Machine modules]# wget http://asterisk.hosting.lv/bin/codec_g729-ast14-gcc4-glibc-pentium.so

Notice that we are in the modules directory

Rename the codec file

mv codec_g729-ast14-gcc4-glibc-pentium4.so codec_g729.so

Restart Asterisk

/etc/init.d/asterisk restart

Check your work

Connect to Asterisk

asterisk -r

Then show all of the codec translations available using the command below, and check g729 at the left, you should see that it can be translated to many other codecs on the top of the table

Machine*CLI> show translations

         Translation times between formats (in milliseconds) for one second of data

          Source Format (Rows) Destination Format (Columns)

          g723 gsm ulaw alaw g726aal2 adpcm slin lpc10 g729 speex ilbc g726 g722

     g723    -   -    -    -        -     -    -     -    -     -    -    -    -

      gsm    -   -    2    2        2     2    1     2    3     -    -    2    -

     ulaw    -   3    -    1        2     2    1     2    3     -    -    2    -

     alaw    -   3    1    -        2     2    1     2    3     -    -    2    -

 g726aal2    -   3    2    2        -     2    1     2    3     -    -    2    -

    adpcm    -   3    2    2        2     -    1     2    3     -    -    2    -

     slin    -   2    1    1        1     1    -     1    2     -    -    1    -

    lpc10    -   3    2    2        2     2    1     -    3     -    -    2    -

     g729    -   3    2    2        2     2    1     2    -     -    -    2    -

    speex    -   -    -    -        -     -    -     -    -     -    -    -    -

     ilbc    -   -    -    -        -     -    -     -    -     -    -    -    -

     g726    -   3    2    2        2     2    1     2    3     -    -    -    -

     g722    -   -    -    -        -     -    -     -    -     -    -    -    -

Machine*CLI> quit

Troubleshooting

If you didn’t see the codec translation as mentioned above then probably you downloaded the wrong codec, please check again the points mentioned during downloading the codec, you can use the following commands to help you:

asterisk -V

uname -a

[goAutoDial]There is a time synchronization problem with your system

2011 July 30
Posted by shirker2006

There a nice build with Asterisk and ViCidial.. but the problem every time is time synchronization server -> agents PC. they are should be at same time zone

this solution from elfo forum:

ok this is what I had to do to fix this problem.

First set : Fix the admin type:

I am at GMT -7
the server time was at Gmt -5
so I went to admin, server and set it to GMT -7

But I still was having problems so I ran this command
ln -sf /usr/share/zoneinfo/UTC /etc/localtime
(for more detail read this
http://forums.theplanet.com/lofiversion/index.php/t39853.html
)

and rebooted the server. This fixed my admin time. But my agent time was still having the problems….

So I went to phones individually and changed the GMT there to -7 too.

and that fixed the problem.

So now my admin and agent time are fine. hope this helps someone in future

Thanks

Goautodial (ViciDialer)

2011 July 29
Comments Off
Posted by shirker2006

http://goautodial.org/projects/goautodialce/wiki/Goautodial_Getting_Started_Guide

mysql root passwd setup (first run)

2011 July 27
Comments Off
Posted by shirker2006
# mysql
mysql> USE mysql;
mysql> UPDATE user SET Password=PASSWORD(’passwd’) WHERE user=’root’;
mysql> FLUSH PRIVILEGES;
mysql> quit;

inbound calls to agents, logged into campaign

2011 July 27
Comments Off
Posted by shirker2006
extensions.conf:
...
[from-sip]
.....
exten => <your inbound number>,1,Set(__CAMPAIGN=<campaign name>)
exten => <your inbound number>,n,goto(inbound,s,1)
[inbound]
exten => s,1,Set(TIMEOUT(digit)=5)
exten => s,n,Set(TIMEOUT(response)=10)
exten => s,2,NoOp(${CALLERIDNUM})             ; we should have callerid by now, if not, we never will
exten => s,3,Answer()                         ; answer so asterisk knows to wake up
exten => s,n,Set(__CAMPAIGN=${CAMPAIGN})

exten => s,n,AGI(clid_generic.agi)              ; attempt to find this in shoppers table ; you need to write and agi to take that callerid number ; and attempt to find the leadid (or campaign and leadid) ; and use that to fill the below vars, if a record does not ; exist, create one, then fill in the leadid with the ; newly created record number. (this is so the agent will ; get a page that they can fill in and all the ; rest of the gnudialer/astcrm code can update something !!!
exten => s,n,Set(__ISTRANSFER=)                 ; remember the __ so it is inherited on on variable names
;these next 2 are examples for those that want to make separate/specific settings
exten => s,n,Set(__CAMPAIGN=${CAMPAIGN})         ; and here
exten => s,n,Set(__PHONENUM=${CALLERID(num)})   ; we fill phonenum var so we can track it throughout call
exten => s,n,Set(CALLERID(name)=~${CAMPAIGN}-${LEADID}-false~)  ; this is a function, so not __ here
                                                                ; the 'true' part is if you are using a
exten => s,n,Set(CDR(accountcode)=${CAMPAIGN})
exten => s,n,NOOP(${QUEUE_MEMBER_COUNT(${CAMPAIGN})})
;exten => s,n,GotoIF($[${QUEUE_MEMBER_COUNT(${CAMPAIGN})} = 0]?noagents:agents) ;exten => s,n(noagents),Playback(${CAMPAIGN}) ;exten => s,n,PLayback(this-call-may-be-monitored-or-recorded)
exten => s,n(agents),Set(__TRANSFER_CONTEXT=stations)
exten => s,n,Set(__RECORDING=agent${AGENTNUM}-${CAMPAIGN}-${LEADID}-${STRFTIME(,,%s)})
exten => s,n,MixMonitor(${RECORDING}.wav,b)
exten => s,n,Set(CDR(userfield)=/${RECORDING}.wav)
exten => s,n,Queue(${CAMPAIGN}|t|||1120)
exten => s,n,Queue(${CAMPAIGN}1|t||1120)
exten => s,n,hangup

Running Asterisk as Different User, NOT Root

2011 July 26
Comments Off
Posted by shirker2006
 Re: Running Asterisk as Different User, NOT Root

It will be simple to set up this.1. Create a system account named as asterisk

2. Change the ownership of the directories below as the account asterisk

chown -R asterisk:asterisk /var/lib/asterisk
chown -R asterisk:asterisk /var/run/asterisk
chown -R asterisk:asterisk /var/log/asterisk
chown -R asterisk:asterisk /var/spool/asterisk
chown -R asterisk:asterisk /etc/asterisk

3. Edit the file /etc/init.d/asterisk, uncomment these two lines

AST_USER=”asterisk”
AST_GROUP=”asterisk”

4. Restart the Asterisk service

error: rpmdbNextIterator: skipping h#

2011 July 26
Comments Off
Posted by shirker2006

ERROR:

error: rpmdbNextIterator: skipping h#

You might want to try to rebuild the yum/rpm db
Open a terminal and log in as root
then
rm /var/lib/rpm/__db*
then exit and reboot
and then open a terminal and log in as root
and type
rpm --rebuilddb
then try
yum check-update

HDD and swap file

2011 July 25
Comments Off
Posted by shirker2006

http://sec-zone.ru/workdisk.html

echo "/file.swp none swap defaults 0 0" >> /etc/fstab

How to Add Swap File

You can get memory information using free. The recommended swap space is twice the size of the physical memory. When you upgrade the system memory, you may need to increase the swap space as well. The most recommended way is to resize an existing swap partition or to use another swap partition. However, this involves adjusting disk partition, which may not be easily done in some cases. The second best method is to use a swap file. The following series of command shows how to this. Let us assume that we are adding a swap file of which size is 120MBytes. You need to be the root.

        # cd /mnt
        # dd if=/dev/zero of=one.swp bs=1024 count=131072
        # mkswap -c /mnt/one.swp
        # swapon /mnt/one.swp
        # free

Edit /etc/fstab file to add the following line so that the swap file can be used automatically at every boot.

        /mnt/one.swp    none    swap    defaults        0 0


AWK, поиск строки в обратном направлении

2011 July 12
Comments Off
Posted by shirker2006

http://www.linux.org.ru/forum/general/4742136

sipp installation on CentOS

2011 July 9
Comments Off
Posted by shirker2006

Dependencys installation

# yum install make gcc gcc-c++ ncurses ncurses.x86_64 ncurses-devel ncurses-devel.x86_64 openssl libnet libpcap libpcap-devel libpcap.x86_64 libpcap-devel.x86_64 gsl gsl-devel

Getting sipp:

# cd /root/downloads
# mkdir sipp
# cd sipp/
# wget http://downloads.sourceforge.net/project/sipp/sipp/3.2/sipp-3.2-Linux_RHEL5U2.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fsipp%2Ffiles%2Fsipp%2F3.2%2F&ts=1310121285&use_mirror=nchc
# tar xzvf sipp-3.2-Linux_RHEL5U2.tar.gz
# cd sipp_packages/
# rpm  -ivh sipp-standard-3.2-linux-2.6-intel.rpm
# sipp --help

2. Create this in your asterisk extensions file


[sipp]
exten => 2005,1,Answer
exten => 2005,2,SetMusicOnHold(default)
exten => 2005,3,WaitMusicOnHold(20)
exten => 2005,4,Hangup

exten => 2002,1,Answer
exten => 2002,2,Goto(MENUCONTEXTORSIMILARCONTEXT,s,1)
exten => 2002,3,Hangup

3. Create this in your sip.conf file

[sipp]
type=friend
context=sipp
host=dynamic
port=6000
user=sipp
canreinvite=no
disallow=all
allow=ulaw

5. Reload Asterisk (in debug mode if you want to verify it’s all working the first time around)

# /etc/init.d/asterisk stop
# /usr/sbin/asterisk -vvvvvvvvvvvvvvvvvvgc

6. Run this sipp command

# ./sipp -sn uac -d 20000 -s 2005 IP.OF.YOUR.BOX -l 30

This command will connect as a client, and give the duration of the call 20K miliseconds (or 20 seconds), will dial the server at ip IP.OF.YOUR.BOX, and try to reach the extension 2005, with a limit of 30 simultaneous calls.

If you want to instead test the actual calls per second isntead of just calling in waiting and hanging up, then make it do something more fasionable. Use this command instead.

# ./sipp -sn uac -d 10000 -s 2002 HOSTNAME.OF.YOUR.BOX -l 10 -mp 5606

OUTPUT:

SIPP:

------------------------------ Scenario Screen -------- [1-9]: Change Screen --
  Call-rate(length)     Port   Total-time  Total-calls  Remote-host
10.0(20000 ms)/1.000s   5061       6.01 s           59  10.0.2.10:5060(UDP)

  10 new calls during 1.000 s period     14 ms scheduler resolution
  46 calls (limit 161)                   Peak was 47 calls, after 5 s
  0 Running, 46 Paused, 0 Woken up
  244 out-of-call msg (discarded)
  1 open sockets

                                 Messages  Retrans   Timeout   Unexpected-Msg
      INVITE ---------->         59        0         0
         100 <----------         57        0                   2
         180 <----------         0         0                   0
         183 <----------         0         0                   0
         200 <----------  E-RTD1 57        0                   0
         ACK ---------->         57        0
       Pause [      0ms]         57                            11
         BYE ---------->         0         0         0
         200 <----------         0         0                   0

------ [+|-|*|/]: Adjust rate ---- [q]: Soft exit ---- [p]: Pause traffic -----

ASTERISK (DEBUG):

-- Executing [2005@sipp:1] Answer("SIP/sipp-085759b8", "") in new stack
-- Executing [2005@sipp:2] SetMusicOnHold("SIP/sipp-085759b8", "default") in new stack
-- Executing [2005@sipp:3] WaitMusicOnHold("SIP/sipp-085759b8", "20") in new stack
-- Started music on hold, class 'default', on channel 'SIP/sipp-085759b8'
-- Executing [2005@sipp:1] Answer("SIP/sipp-0858ff38", "") in new stack
-- Executing [2005@sipp:2] SetMusicOnHold("SIP/sipp-0858ff38", "default") in new stack
-- Executing [2005@sipp:3] WaitMusicOnHold("SIP/sipp-0858ff38", "20") in new stack
-- Started music on hold, class 'default', on channel 'SIP/sipp-0858ff38'

RAW SNMP DATA:

mythbox ~ # snmpwalk -On -c YOUR.COMMUNITY.NAME -v 2c YOUR.IP.GOES.HERE .1.3.6.1.4.1.22736.1.5.1.0
.1.3.6.1.4.1.22736.1.5.1.0 = INTEGER: 30

Private posts list menu for wordpress

2011 July 8
Comments Off
Posted by shirker2006

Edit sidebar.php

<h2 class="widgettitle">Private posts list</h2>
      <ul class="archive-list">
           <?php
                       $current_user = wp_get_current_user();
                        if ( 0 == $current_user->ID ) {
                         // Not logged in.
                       } else {
                                            $query = "SELECT post_title, MONTH( post_date ) AS month ,  YEAR( post_date ) AS year, DAY( post_date ) AS day , id FROM $wpdb->posts WHERE post_author=$current_user->ID AND post_status = 'private' AND post_date <= now( ) and post_type = 'post' ORDER BY post_date DESC";
                            if ( $posts = $wpdb->get_results($query) ) {
                                    foreach ($posts as $post) {
                                                               ?>
                        <li><a href="<?php echo get_permalink($post->id)?>"><?php echo $post->post_title ?> - <?php echo date("F jS, Y",mktime(0, 0, 0, $post->month, $post->day, $post->year)) ?><span></span></a></li>
                        <?php
                                                               }
                                                                            }
                            }
                        ?>
         </ul>

inbound number and X-Lite connection to Asterisk

2011 July 8
Comments Off
Posted by shirker2006

sip.conf:

;X-Lite connection
[9001]
type=friend
username=9001
secret=1234
nat=yes         ;I tried no and was not able to connect
host=dynamic
dtmfmode=rfc2833
disallow=all
allow=ulaw
context=from-sip

[9002]  ;this we will put ext that we setup on their site, not real no
;  ipkall
type=peer
dtmfmode=rfc2833
context=inbound
insecure=very
host=voiper.ipkall.com
nat=no

extensions.conf

[a2billing]
exten => _X.,1,Answerexten => _X.,2,Wait,2
exten => _X.,3,DeadAGI,a2billing.php
exten => _X.,4,Wait,2
exten => _X.,5,Hangup

[from-sip];echo test
exten => 111,1,Answer()
exten => 111,2,Playback(welcome)
exten => 111,3,Playback(demo-echotest)
exten => 111,4,Echo()
exten => 111,5,Playback(demo-echodone)
exten => 111,6,Playback(vm-goodbye)
exten => 111,7,Hangup()
[inbound]
exten => 9002,1,Dial(SIP/9001)

now we can connect to asterisk with softphone and we will able to receive inbound calls

if we dial 111 – we can get echo test

A2Billing installation on CentOS

2011 July 8
Comments Off
Posted by shirker2006

Install Dependencies

yum -y install perl-DBD-Pg subversion

get A2Billing

mkdir /usr/local/src/a2billing
cd /usr/local/src/a2billing	svn co --username guest --password guest http://svn.a2billing.net/svn/asterisk2billing/trunk/ /usr/local/src/a2billing

copy a2billing.conf in /usr/local/src/a2billing/a2billing.conf to /etc/a2billing.conf

Edit a2billing.conf to suit your installation. e.g. change dbtype to mysql. Install Database   Note that for Piaf and FonicaPABX, the database password is passw0rd and the location is localhost

cd /usr/local/src/a2billing/DataBase/mysql-5.x
./install-db.sh

Answer the questions appropriately with reference to /etc/a2billing.conf
You should now have a database called mya2billing with over 70 tables in it.
Install the AGI and Sound Files
So that we can easily update the system when changes are made during this period of change, we are going to use links back to the location where we installed the SVN   download, so that an update from the SVN will immediately reflect in your A2Billing install.   Note that Database changes will not be included using this methodology, so these will have to be done by hand.   This is not the usual way of doing it, but for testing, it works well. You can also simply move or copy the files into the appropriate location.

ln -s /usr/local/src/a2billing/AGI/a2billing.php /var/lib/asterisk/agi-bin/a2billing.php

chmod +x /var/lib/asterisk/agi-bin/a2billing.php

Set up sounds

cd /usr/local/src/a2billing/addons/sounds
./install_a2b_sounds.sh

Asterisk Manager

Now edit /etc/asterisk/manager.conf . Add the following lines

[myasterisk]
secret = mycode
deny=0.0.0.0/0.0.0.0
permit=127.0.0.1/255.255.255.0
read = system,call,log,verbose,command,agent,user
write = system,call,log,verbose,command,agent,user

Install Web Pages

vim /etc/httpd/conf.d/a2billing.conf

# SAMPLE CONFIG SNIPPETS FOR APACHE WEB SERVER
# Last Modified: 11-26-2005
#
# This file contains examples of entries that need
# to be incorporated into your Apache web server
# configuration file.  Customize the paths, etc. as
# needed to fit your system.

Alias /a2billing "/usr/local/src/a2billing"
    <Directory "/usr/local/src/a2billing">   
        Options None 
        AllowOverride None   
        Order allow,deny   
        Allow from all
    </Directory>

Alias /a2billing/common "/usr/local/src/a2billing/common"

     <Directory "/usr/local/src/a2billing/common">   
        Options None   
        AllowOverride None   
        Order allow,deny   
        Allow from all
     </Directory>

Alias /a2billing/agent "/usr/local/src/a2billing/agent"

     <Directory "/usr/local/src/a2billing/agent">
         Options None   
         AllowOverride None   
         Order allow,deny   
         Allow from all
     </Directory>
Alias /a2billing/customer "/usr/local/src/a2billing/customer"

     <Directory "/usr/local/src/a2billing/customer">   
          Options None   
          AllowOverride None   
          Order allow,deny   
          Allow from all
     </Directory>
#service httpd restart

Cronjobs

Create folder directory for Cronts PID

#mkdir -p /var/run/a2billing
echo "	# Automatically added for A2Billing	0 * * * * php /usr/local/src/a2billing/Cronjobs/a2billing_alarm.php	0 12 * * * php /usr/local/src/a2billing/Cronjobs/a2billing_archive_data_cront.php	0 10 21 * * php /usr/local/src/a2billing/Cronjobs/a2billing_autorefill.php	#Batch process at 00:20 each day	20 0 * * * php /usr/local/src/a2billing/Cronjobs/a2billing_batch_process.php	#Bill DID usage at 00:00 each day	0 0 * * * php /usr/local/src/a2billing/Cronjobs/a2billing_bill_diduse.php	#Generate Invoices at 6am everyday	0 6 * * * php /usr/local/src/a2billing/Cronjobs/a2billing_batch_billing.php	#Check if balance below preset value, and email user if so.	1 * * * * php /usr/local/src/a2billing/Cronjobs/a2billing_notify_account.php	#Charge subscriptions at 06:05 on the 1st of each month	0 6 1 * * php /usr/local/src/a2billing/Cronjobs/a2billing_subscription_fee.php	#Update currencies at 01:00 each day	0 1 * * * php /usr/local/src/a2billing/Cronjobs/currencies_update_yahoo.php	" >> /var/spool/cron/asterisk

Add directory for monitoring Script

mkdir -p /var/lib/a2billing/script

Create Log Files
touch /var/log/asterisk/a2billing-daemon-callback.log
touch /var/log/a2billing-daemon-callback.log
touch /var/log/cront_a2b_alarm.log
touch /var/log/cront_a2b_autorefill.log
touch /var/log/cront_a2b_batch_process.log
touch /var/log/cront_a2b_bill_diduse.log
touch /var/log/cront_a2b_subscription_fee.log
touch /var/log/cront_a2b_currency_update.log
touch /var/log/cront_a2b_invoice.log
touch /var/log/a2billing_paypal.log
touch /var/log/a2billing_epayment.log
touch /var/log/api_ecommerce_request.log
touch /var/log/api_callback_request.log
touch /var/log/a2billing_agi.log

Callback

Here is a little script to install the call-back Daemon.

#!/bin/bash
LOAD_LOC=/usr/src/a2billing
yum -y install python-setuptools.noarch
yum -y install MySQL-python
easy_install sqlalchemy
cd $LOAD_LOC/CallBack/callback-daemon-py
cp callback_daemon/a2b-callback-daemon.rc /etc/init.d/a2b-callback-daemon
chmod +x /etc/init.d/a2b-callback-daemon
cp dist/callback_daemon-1.0.prod-r1528.tar.gz /tmp
cd /tmp
tar xvfz callback_daemon-1.0.prod-r1528.tar.gz
cd callback_daemon-1.0.prod-r1528
python setup.py build
python setup.py bdist_egg
easy_install dist/callback_daemon-1.0.prod_r1528-py2.4.egg
chkconfig --add a2b-callback-daemon
service a2b-callback-daemon start
chkconfig a2b-callback-daemon on

Dialplan

Login

http://Your-Switch/a2billing   Log into the admin pages with root and changepassword

Installing Asterisk on CentOS

2011 July 7
Comments Off
Posted by shirker2006

What is Asterisk?

Asterisk PBX, from now on just called Asterisk, is Linux based, Open Source and free PBX software. Or to quote from the Asterisk website http://www.asterisk.org

This is for setup asterisk used for DIALER purpose:

yum install subversion

–DAHDI–

cd /usr/src/

svn co http://svn.digium.com/svn/dahdi/linux/trunk dahdi-kernel
cd dahdi-kernel
make MODULES_EXTRA='dahdi_dummy'
make MODULES_EXTRA='dahdi_dummy' install

maybe it will ask for kernel source

http://mirror.centos.org/centos/5/updates/x86_64/RPMS/

or

cd /tmp
wget http://mirror.centos.org/centos/5/updates/SRPMS/kernel-2.6.18-194.3.1.el5.src.rpm
rpm -ivh kernel-2.6*

for 64bit run this

wget http://mirror.centos.org/centos/5/updates/x86_64/RPMS/kernel-2.6.18-194.32.1.el5.x86_64.rpm
rpm -ivh kernel-2.6*

install the kernel source and restart server

cd /usr/src/

svn co http://svn.digium.com/svn/dahdi/tools/trunk dahdi-tools
yum install newt newt-devel
cd dahdi-tools
./configure
make menuselect

highlight all available

make install

–END DAHDI–

–ASTERISK–

copy asterisk from marble.

cd /usr/src/
rsync -rva 192.168.11.17:/usr/src/asterisk-1.4 /usr/src

when installing new asterisk we should rsync /usr/src/asterisk-1.4 from dragon…there are a couple of files that have modification.
app_queue.c and manager.c

[root@peebles asterisk-1.4]# svn diff apps/app_queue.c
Index: apps/app_queue.c
===================================================================
--- apps/app_queue.c    (revision 294987)
+++ apps/app_queue.c    (working copy)
@@ -3273,10 +3273,12 @@
"Channel: %s\r\n"
"Member: %s\r\n"
"MemberName: %s\r\n"
+                    "CallerIDName: %s\r\n"
"Holdtime: %ld\r\n"
"BridgedChannel: %s\r\n"
"%s",
queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
+                    qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
(long)time(NULL) - qe->start, peer->uniqueid,
qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
ast_copy_string(oldcontext, qe->chan->context, sizeof(oldcontext));
cd /usr/src/asterisk-1.4
make clean
./configure
make menuselect

Make sure in channel chan_dahdi is available
save

make
make install

–END ASTERISK—

copy safe_asterisk start and shutdown scripts:

rsync -rva 192.168.11.15:/usr/sbin/safe_a*  /usr/sbin/

safe_asterisk is to start
safe_asterisk_restart is to restart asterisk safely.

config files:

rsync -rva 192.168.11.50:/etc/asterisk /etc

we need to make a file /etc/sysconfig/route-eth0

make sure eth0 has address on 192.168.41.0 network:

[root@localhost network-scripts]# more route-eth0
192.168.4.0/24 via 192.168.41.1
[root@localhost network-scripts]#

Change selinux to permission in /etc/selinux/config

put startup to mount ram drive

scp 192.168.11.50:/etc/rc.local /etc/

add to /etc/fstab so the /mnt will get mounted on startup.

192.168.11.7:/monitor /mnt  nfs defaults  0 0

crontab:

to copy monitoring files

[root@peebles asterisk]# chkconfig nfs on
[root@peebles asterisk]# /etc/init.d/nfs start

Edit

/etc/asterisk/astmanproxy.conf to reflect this hosts IP

host = 192.168.11.242, 5038, dialer, 1234, on, off

For pebbles host is 192.168.11.242

Install Nagios-plugins and NRPE to Monitor Remote Linux Server

2011 July 6
Comments Off
Posted by shirker2006

Create Nagios user account on remote server to be monitored:

# useradd nagios
# passwd nagios

Download and Install Nagios Plugins:

# mkdir -p /root/downloads/nagios/plugins
# cd /root/downloads/nagios/plugins

Save file to directory /root/downloads/nagios/plugins

http://www.nagios.org/download/download.php

wget http://downloads.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.12/nrpe-2.12.tar.gz?r=http%3A%2F%2Fexchange.nagios.org%2Fdirectory%2FAddons%2FMonitoring-Agents%2FNRPE--2D-Nagios-Remote-Plugin-Executor%2Fdetails&ts=1309801287&use_mirror=nchc

As of this writing Nagios 3.0.6 (Stable) and Nagios Plugins 1.4.13 (Stable)

Extract Files:

# tar xzf nagios-plugins-1.4.13.tar.gz

# cd nagios-plugins-1.4.13

Compile and Configure Nagios Plugins

** You need the openssl-devel package installed to compile plugins with ssl support. **

# yum -y install openssl-devel

Instal Plugins:

# ./configure --with-nagios-user=nagios --with-nagios-group=nagios
# make
# make install

The permissions on the plugin directory and the plugins will need to be changed to nagios user

# chown nagios.nagios /usr/local/nagios
# chown -R nagios.nagios /usr/local/nagios/libexec

Package xinted is needed

# yum install xinetd

Downlad and Install NRPE Daemon

# mkdir -p /root/downloads/nagios/nagios_nrpe
# cd /root/downloads/nagios/nagios_nrpe

Save file to directory /root/downloads/nagios/

http://www.nagios.org/download/download.php

As of this writing NRPE 2.12 (Stable)

Extract the Files:

# tar -xzf nrpe-2.12.tar.gz
# cd nrpe-2.12

Compile and Configure NRPE

** You need the openssl-devel package installed to compile NRPE with ssl support. **

# yum -y install openssl-devel

Install NRPE:

# ./configure 

General Options:
 -------------------------
 NRPE port:    5666
 NRPE user:    nagios
 NRPE group:   nagios
 Nagios user:  nagios
 Nagios group: nagios

# make all

# make install-plugin

# make install-daemon

# make install-daemon-config

# make install-xinetd

Post NRPE Configuration

Edit Xinetd NRPE entry:

Add Nagios Monitoring server to the “only_from” directive

# vi /etc/xinetd.d/nrpe

only_from = 127.0.0.1 <nagios_ip_address>

Edit services file entry:

Add entry for nrpe daemon

# vi /etc/services

nrpe      5666/tcp    # NRPE

Restart Xinetd and Set to start at boot:

# chkconfig xinetd on

# service xinetd restart

Test NRPE Daemon Install

Check NRPE daemon is running and listening on port 5666:

# netstat -at |grep nrpe

Output should be:

tcp    0    0 *:nrpe    *.*    LISTEN

Check NRPE daemon is functioning:

# /usr/local/nagios/libexec/check_nrpe -H localhost

Output should be NRPE version:

NRPE v2.12

Open Port 5666 on Firewall

Make sure to open port 5666 on the firewall of the remote server so that the Nagios monitoring server can access the NRPE daemon.
just add this string and restart firewall

 -A RH-Firewall-1-INPUT -s <ip of nagios> -p tcp -m tcp --dport 5666 -j ACCEPT

Nagios Monitoring Host Server Setup

Downlad and Install NRPE Plugin

# mkdir -p /root/downloads/nagios/nagios_nrpe
# cd /root/downloads/nagios/nagios_nrpe

Save file to directory /root/downloads/nagios

http://www.nagios.org/download/download.php

As of this writing NRPE 2.12 (Stable)

Extract the Files:

# tar -xzf nrpe-2.12.tar.gz
# cd nrpe-2.12

Compile and Configure NRPE

# ./configure 

# make all

# make install-plugin

Test Connection to NRPE daemon on Remote Server

Lets now make sure that the NRPE on our Nagios server can talk to the NRPE daemon on the remote server we want to monitor. Replace “<IP of Remote Server>” with the remote servers IP address.

# /usr/local/nagios/libexec/check_nrpe -H <IP of Remote Server>
NRPE v2.12

Create NRPE Command Definition

A command definition needs to be created in order for the check_nrpe plugin to be used by nagios.

# vi /usr/local/nagios/etc/objects/commands.cfg

Add the following:

###############################################################################
# NRPE CHECK COMMAND
#
# Command to use NRPE to check remote host systems
###############################################################################

define command{
        command_name check_nrpe
        command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
        }

Create Linux Object template

In order to be able to add the remote linux machine to Nagios we need to create an object template file adn add some object definitions.

Create new linux-box-remote object template file:

# vi /usr/local/nagios/etc/objects/linux-box-remote.cfg

Add the following and replace the values “host_name” “alias” “address” with the values that match your setup:

** The “host_name” you set for the “define_host” section must match the “host_name” in the “define_service” section **

define host{
          name                  linux-box-remote             ; Name of this template
          use                   generic-host          ; Inherit default values
          check_period          24x7
          check_interval        5
          retry_interval        1
          max_check_attempts    10
          check_command         check-host-alive
          notification_period   24x7
          notification_interval 30
          notification_options  d,r
          contact_groups        admins
          register              0          ; DONT REGISTER THIS - ITS A TEMPLATE
          }

define host{
          use       linux-box-remote     ; Inherit default values from a template
          host_name Centos5    ; The name we're giving to this server
          alias     Centos5 ; A longer name for the server
          address   XX.XX.XX.XX   ; IP address of the server
          }

define service{
          use                 generic-service
          host_name           Centos5
          service_description CPU Load
          check_command       check_nrpe!check_load
          }
define service{
          use                 generic-service
          host_name           Centos5
          service_description Current Users
          check_command       check_nrpe!check_users
          }
define service{
          use                 generic-service
          host_name           Centos5
          service_description /dev/hda1 Free Space
          check_command       check_nrpe!check_sda1
          }
define service{
          use                 generic-service
          host_name           Centos5
          service_description Total Processes
          check_command       check_nrpe!check_total_procs
          }
define service{
          use                 generic-service
          host_name           Centos5
          service_description Zombie Processes
          check_command       check_nrpe!check_zombie_procs
          }

Activate the linux-box-remote.cfg template:

# vi /usr/local/nagios/etc/nagios.cfg

And add:

# Definitions for monitoring remote Linux machine
cfg_file=/usr/local/nagios/etc/objects/linux-box-remote.cfg

Verify Nagios Configuration Files:

# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
Total Warnings: 0
Total Errors:   0

Restart Nagios:

# service nagios restart

Check Nagios Monitoring server that the remote linux box was added and is being monitored !

TroubleShooting

NRPE ./configure error:

checking for SSL headers… configure: error: Cannot find ssl headers

Solution:

You need to install the openssl-devel package

# yum -y install openssl-devel

CHECK_NRPE: Error – Could not complete SSL handshake

Solution:

This is most likely not a probem with SSL but rather with Xinetd access restrictions.

Check the following files:

/etc/xinetd.d/nrpe

/etc/hosts.allow

/etc/hosts.deny

no acceptable c compiler found in $PATH

When I gave the ./configure command i got this error saying: no acceptable c compiler found in $PATH and then it stops.

After a quick google search I found a topic saying that i needed to install gcc so i entered:

yum install gcc glibc glibc-common gd gd-devel

(thanks to AgentOOX)

bash command list

2011 July 2
Comments Off
Posted by shirker2006

http://ss64.com/bash/

WordPress installation on CentOS. Steb by step

2011 July 1
Comments Off
Posted by shirker2006

Lets check architecture, IP and utilization:

    1  ifconfig
    2  uname -a
    3  uptime
    4  w
    5  top
    6  df
    7  df -h
    8  service httpd status
    9  service apache2 status
   10  rpm -qa | less

We can see, that webserver not yet installed.
rpm -qa command shows all packages installed

Now we need to install Apache, php and MySQL

First step – we have to update system:

   13  yum update
   14  free -m
   15  reboot now
   16  reboot
   17  yum update

with free -m we can see RAM utilization.

After restart we have to run again update..

   18  yum install -y httpd
   19  yum install -y mysql-server
   20  chkconfig httpd on
   21  chkconfig mysqld on

with chkconfig we can add cervice to startup.
Next step: setting up password for mysql user root

   24  mysql
   25  service mysqld start
   26  mysql
mysql> USE mysql;
mysql> UPDATE user SET Password=PASSWORD(’passwd’) WHERE user=’root’;
mysql> FLUSH PRIVILEGES;
mysql> quit;

After we have to change iptable rules to connect to webserver:

   28  service httpd status
   29  service httpd start
   30  service iptables
   31  service iptables status
   32  service iptables stop
   33  vim
   34  vim /etc/sysconfig/iptables

# Firewall configuration written by system-config-securitylevel
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT

   35  service iptables start

as you can see, we have added this line:
-A RH-Firewall-1-INPUT -m state –state NEW -m tcp -p tcp –dport 80 -j ACCEPT

next step is phpmyadmin. I want to show, hows easy it can be installed yum. This package is not included to official repository. we need to use remi:

   37  cd /tmp/
   38  wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
   39  ls
   40  rpm -Uvh epel-release-5-4.noarch.rpm
   41  wget http://rpms.famillecollet.com/enterprise/5/remi/x86_64/remi-release-5-8.el5.remi.noarch.rpm
   42  rpm -Uvh remi-release-5-8.el5.remi.noarch.rpm

now we can install phpmyadmin. If there some error with mysql-server, we have to reinstall it to latest version from remi:

   44  yum -y install --enablerepo=remi phpmyadmin
   45  service mysql stop
   46  yum
   47  yum erase mysql*
   48  yum -y install --enablerepo=remi phpmyadmin
   50  service mysqld start

as we can see, mysql-server not exist. Lets install it:

   51  yum -y install --enablerepo=remi mysql-server
   52  service mysqld start
   53  vim /etc/httpd/conf.d/phpMyAdmin.conf

we have to edit phpMyAdmin.conf to enable connection not only fron localhost:

......
Alias /phpMyAdmin /usr/share/phpMyAdmin
Alias /phpmyadmin /usr/share/phpMyAdmin

   order deny,allow
   allow from all
#   allow from 127.0.0.1
#   allow from ::1

.....

Then we apply changes by restarting Apache:

   55  service httpd restart

Now we can upload wordpress to our server:

   60  wget http://wordpress.org/latest.tar.gz
   61  ls /var/www/html/
   62  tar -?
   63  ls
   64  tar -xfz latest.tar.gz
   65  tar -xzf latest.tar.gz
   66  ls
   67  ls  wordpress
   68  cd  wordpress
   69  mv * /var/www/html/
   70  ls
   71  ls /var/www/html/
   72  ifconfig

Now, if we type out server IP address to address bar of our browser we suppose to see wordpress, but we still watching Apache welcome page. why? because we not disabled it.
We will open welcome.conf file and comment everything there:

   74  vim /etc/httpd/conf.d/welcome.conf
   75  service httpd restart

Then we apply changes by restarting Apache

Next problem, that we going to face is selinux restrictions.
if we go to http://127.11.140.22/ we will just get 403 error “Forbidden”

   78  echo 0 >/selinux/enforce

Lets turn off selinux and swap it to “permissive” mode, to find out, where is problem:

   82  vim /etc/selinux/config

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0

to apply that we have to restart server

ok, now we can start installation process of wordpress:

http://127.11.140.22/

to fix permissions of files of wordpress we need to change owner. Lets check, what is username of httpd:

   89  ps aux | grep httpd
[root@localhost ~]# ps aux | grep httpd
  root    3686  0.0  0.4 276968  1680 ?        Ss   Jun30   0:00 /usr/sbin/httpd
apache    3689  0.0  7.4 362824 28420 ?        S    Jun30   0:05 /usr/sbin/httpd
apache    3690  0.0  7.3 361800 28056 ?        S    Jun30   0:06 /usr/sbin/httpd
apache    3691  0.0  7.4 360776 28208 ?        S    Jun30   0:05 /usr/sbin/httpd
apache    3692  0.0  7.6 363868 29240 ?        S    Jun30   0:05 /usr/sbin/httpd
apache    3693  0.0  7.4 363868 28496 ?        S    Jun30   0:05 /usr/sbin/httpd
   90  chown -R apache:apache /var/www/html/

To secure server we have to use selinux.
echo 1 >/selinux/enforce
Recommendations of selinux developers is transferring httpd root directory from /var/www to /srv

   90  ls /srv
   91  mkdir /srv/www
   92  mkdir /srv/www/html
   93  mv /var/www/html/* /srv/www/html/
   94  vim /etc/httpd/conf/httpd.conf

and replace “/var/www” strings to “/srv/www”
Then apply:

   95  service httpd restart

Applying security policy:

   97  semanage fcontext --add --type httpd_sys_content_t '/srv/www(/.*)?'
   98  ls -Z /srv

Attribute should be like that:

[root@localhost ~]#  ls -Z /srv/www
drwxr-xr-x  apache apache system_u:object_r:httpd_sys_content_t html

only httpd_sys_content_t attribute will accepted by webserver

to setup secure context of entire html directory run:

  122  restorecon -R /srv/www/html/
[root@localhost ~]#  ls -Z /srv/www/html/
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t index.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t license.txt
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t readme.html
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-activate.php
drwxr-xr-x  apache apache system_u:object_r:httpd_sys_content_t wp-admin
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-app.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-atom.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-blog-header.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-comments-post.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-commentsrss2.php
-rw-r--r--  apache apache root:object_r:httpd_sys_content_t wp-config.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-config-sample.php
drwxr-xr-x  apache apache system_u:object_r:httpd_sys_content_t wp-content
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-cron.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-feed.php
drwxr-xr-x  apache apache system_u:object_r:httpd_sys_content_t wp-includes
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-links-opml.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-load.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-login.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-mail.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-pass.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-rdf.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-register.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-rss2.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-rss.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-settings.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-signup.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t wp-trackback.php
-rw-r--r--  apache apache system_u:object_r:httpd_sys_content_t xmlrpc.php

Now we can put enforce mode to selinux conf file:

  123  vim /etc/selinux/config
[root@localhost ~]# cat /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=enforcing
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0

Then reboot the server to ensure, that all services will start automatically:

  145  reboot

Lets move our blog to blog directory:

  311  mv wp* blog                                 (moving files with names started with wp)
  312  ls
  314  mv *php blog
  315  mv *txt blog
  316  mv *htm blog
  317  mv *html blog
  318  ls -Z

Enable .htaccess

Now we want to close the blog from strangers. I decide to use HTTP authentication.
To allow .htaccess on the server ve have to edit httpd.conf and restart apache:

319  vim /etc/httpd/conf/httpd.conf              (main apache configuration)

To enable .htaccess we need to turn directive “AllowOverride” from “None” to “All”

<Directory />  
  Options FollowSymLinks    
  AllowOverride All
</Directory>
<Directory "/srv/www/html">

#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
    Options Indexes FollowSymLinks

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride All

#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

Daily backup wordpress database:

mysqldump – a database backup program

mkdir /var/backups/
mkdir /var/backups/wordpress
mkdir /var/scripts
vim /var/scripts/wp-db-backup.sh

Then add this string to wp-db-backup.sh script:

#!/bin/bash
/usr/bin/mysqldump --user=XXXX --password=XXXX --databases wordpress > /var/backups/wordpress/wordpress_`date +\%Y-\%m-\%d-\%H-\%M-\%S`.SQL

make file executable and add to cron (every day at 01:01 am)

chmod +x /var/scripts/wp-db-backup.sh
[root@localhost ~]# crontab -e                          (editing cron schedule)
01 01 * * * /var/scripts/wp-db-backup.sh

Disabled (not applicable):

Basic HTTP authorization with username and passwd:

  324  cd /srv/www/html/blog/
  329  vim .htaccess
[root@localhost blog]# cat .htaccess                 (display file)
AuthType Basic
AuthName "By Invitation Only"
AuthUserFile /usr/local/httpd/passwords
Require user somename

To create passwd file and set password for user “somename”

[root@localhost html]# htpasswd -c /usr/local/httpd/passwords somename
New password:
Re-type new password:

Now to access to http://XX.XX.XX.XX/blog we have to use username and passwd

selinux setup

2011 July 1
Comments Off
Posted by shirker2006

http://www.opennet.ru/base/sec/selinux_setup.txt.html

yum install –enablerepo=remi phpmyadmin

2011 July 1
Comments Off
Posted by shirker2006

http://www.venkysblog.com/run-fusionpbx-for-freeswitch-on-centos-in-4-s

Show all installed packages or software in Linux, FreeBSD, OpenBSD

2011 July 1
Comments Off
Posted by shirker2006

Show all installed packages or software in Linux, FreeBSD, OpenBSD

by VIVEK GITE on AUGUST 25, 2006 · 5 COMMENTS

Q. I am using CentOS how do I show all installed packages in Linux?

A. You need to use rpm command to display all installed packages in Linux.

Red Hat/Fedora Core/CentOS Linux

Type the following command to get list of all installed software
# rpm -qa | less

Debian Linux

Type the following command to get list of all installed software:
# dpkg --get-selections

Ubuntu Linux

Type the following command to get list of all installed software:
# sudo dpkg --get-selections

FreeBSD

Type the following command to get list of all installed software:
# pkg_info | less
# pkg_info apache

Use pkg_version command to summarizes the versions of all installed packages:
# pkg_version | less
# pkg_version | grep 'lsof'

OpenBSD

OpenBSD also use pkg_info command to display list of all installed packages or software:
# pkg_info | less
# pkg_info apache

wanna more?

http://www.cyberciti.biz/tips/top-linux-monitoring-tools.html

Call Center Stats

2011 June 30
Comments Off
Posted by shirker2006

http://www.asternic.biz/

find command

2011 June 28
Comments Off
Posted by shirker2006

http://linuxway.ru/pervye-shagi/poisk-fajlov-v-linux-ili-izuchaem-komandu-find/

[bash] delay shutdown

2011 June 28
Comments Off
Posted by shirker2006
#!/bin/bash
VAR=`ls /var/spool/asterisk/monitor/ | wc -l`
while [ 1 ]
do
echo $VAR
if [ $VAR != 0 ]; then
echo "there some files"
/root/monmv.sh
else
echo "going to restart"
/sbin/init 0
fi
sleep 15
done

[bash] kill -9 $i

2011 June 27
Comments Off
Posted by shirker2006
for i in `ps aux | grep shutdown_server.sh | grep -v grep | awk '{print $2}'`; do kill -9 $i; done

html, php, sql and etc

2011 June 25
Comments Off
Posted by shirker2006

http://www.w3schools.com

2011 June 24
Comments Off
Posted by shirker2006

Can you telnet 192.168.40.10

this is the router in US.
passwd123
enable
passwd123
run
show run
you will see some routes redistributing some dialers between the links
Serial 0/3/0:1 is GLOBE that’s the one down
Serial 0/2/0:1 is PLDT  ( i may put it a bit wrong…but 2 is PLDT and 3 is GLOBE ).
remove the routes that point to 0/3/0
just look in the show running for full ip route
then do
config t
no ip route …. serial 0/3/0:1 …
Also on all asterisk the route to 192.168.40.0 should be through 192.168.41.1
p route 0.0.0.0 0.0.0.0 81.81.81.22
ip route 192.168.11.0 255.255.255.0 Serial0/2/0:1
ip route 192.168.11.81 255.255.255.255 Serial0/3/0:1
ip route 192.168.41.0 255.255.255.0 Serial0/3/0:1
ip route 192.168.41.12 255.255.255.255 Serial0/2/0:1
ip route 192.168.41.14 255.255.255.255 Serial0/2/0:1
ip route 192.168.41.15 255.255.255.255 Serial0/2/0:1
ip route 192.168.66.0 255.255.255.0 Serial0/3/0:1
no ip http server
no ip http secure-server
..
Router#config t
Enter configuration commands, one per line.  End with CNTL/Z.
Router(config)#no ip route 192.168.66.0 255.255.255.0 Serial0/3/0:1
Router(config)#no ip route 192.168.41.0 255.255.255.0 Serial0/3/0:1
Router(config)#no ip route 192.168.11.81 255.255.255.255 Serial0/3/0:1
Router(config)#
no ip forward-protocol nd
ip route 0.0.0.0 0.0.0.0 81.81.81.22
ip route 192.168.11.0 255.255.255.0 Serial0/2/0:1
ip route 192.168.41.12 255.255.255.255 Serial0/2/0:1
ip route 192.168.41.14 255.255.255.255 Serial0/2/0:1
ip route 192.168.41.15 255.255.255.255 Serial0/2/0:1
no ip http server
no ip http secure-server

[mysql] how to find duplicate value

2011 June 24
Comments Off
Posted by shirker2006

SELECT *
FROM `ESS`
GROUP BY ’id’
HAVING COUNT( ’phone’ ) >1
LIMIT 0 , 30

Auto login to Ubuntu

2011 June 23
Comments Off
Posted by shirker2006

https://help.ubuntu.com/community/AutoLogin

[net] MONITOR WHO RUNS WHAT, LISTEN TO WHAT PORTS, ESTABLISHED WHAT CONNECTIONS

2011 June 22
Comments Off
Posted by shirker2006

To identify and monitor who is running what applications, which the application is listening to what port, established what connections, we can use lsof. lsof (List Open Files) are use for listing all current opened files. Besides the file name, it includes info such as who open it, what command use to open it, what type of file is it etc.

To list all Internet or network related opened files.

lsof -i

output:

 COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME ktorrent 5220 mysurface 14u IPv4 13129 TCP *:6881 (LISTEN) ktorrent 5220 mysurface 15u IPv6 13152 UDP *:6881 ktorrent 5220 mysurface 16u IPv4 41606 TCP 192.168.1.101:43234->122.49.147.27:32006 (SYN_SENT) ktorrent 5220 mysurface 17u IPv4 41597 TCP 192.168.1.101:59485->host-63-239-252-1.tetonwireless.com:6881 (SYN_SENT) ktorrent 5220 mysurface 18u IPv4 36757 TCP 192.168.1.101:42724->203-36-217-77.dsl.dodo.com.au:25423 (ESTABLISHED) ... 

You might facing some latency while listing them, the reason is, lsof cleverly replace your IP with DNS, so it need times to resolve DNS. To ask it stop to act smart and display with only numerical IP addresses, specified -n.

lsof -i -n

You may want to list open files with root permission, which returns you more entries.

sudo lsof -i -n

lsof list both IPv6 and IPv4 related files by default. You specified -i4 if you want entries with IPv4 only, same thing to IPv6, specified -i6.

sudo lsof -i4 -n

Okay, If you just want to list files which triggers by a specific user only, you can do this:

sudo lsof -i -n -a -u toydi

-a indicate AND logic, the entire line simply means, I want to list Internet related open files and these files must be trigger by toydi.

Again, lsof capable of doing more, check out the manuals for more details.

[net]tcpdump

2011 June 22
Comments Off
Posted by shirker2006

посмотреть трафик на интерфейсе:

tcpdump -i fxp1

посмотреть трафик одного хоста:

tcpdump host 1.2.3.4

посмотреть трафик на порте:

tcpdump src port 80

посмотреть IP трафик на хост:

tcpdump ip host 1.2.3.4

посмотреть ARP трафик на хост:

tcpdump arp host 1.2.3.4

посмотреть RARP трафик на хост:

tcpdump rarp host 1.2.3.4

посмотреть трафик, кроме хоста unixserver:

tcpdump not host unixserver

посмотреть трафик на server1 и server2

tcpdump host server1 or host server2

посмотреть содержимое пакетов на интерфейсе tun0 на хост ya.ru

tcpdump -X -i tun0 host ya.ru

подсмотреть номера и пароли к icq

tcpdump -X -i fxp1 port aol

посмотреть содержимое пакетов на интерфейсе tun0 на хост ya.ru, при этом прочитать из каждого пакета по 1500 байт и не преобразовывать IP в имя хоста

tcpdump -X -s 1500 -n -i tun0 host ya.ru

[bash] scripts to run/restart dialer(program)

2011 June 22
Comments Off
Posted by shirker2006
vladimirm@Snow:~$ cat /usr/bin/check_gndlr_stuck.sh
#!/bin/bash

VAR1=`ls -la /tmp | grep gtrace |  awk '{print $5}'`
VAR2=`cat /tmp/gtrac_fsz`
echo  $VAR1
echo  $VAR2
if [ $VAR1 = $VAR2 ]; then
    echo "gnudialer needs to be restarted"
    /usr/bin/gnudialer stop
else
    echo "gnudialer is running well"
fi

echo $VAR1 > /tmp/gtrac_fsz

vladimirm@Snow:~$ cat /usr/bin/check_gnudialer_mysql.sh
#!/bin/bash

VAR1=`/usr/bin/tail -200 /tmp/gtrace | grep "Error selecting leads from mysql"`
#echo  $VAR1
if [ $VAR1=0 ]; then
    echo "gnudialer is running well"
else
    echo "gnudialer needs to be restarted"
    /usr/bin/gnudialer stop
fi

[bash] /usr/bin/check.sh

2011 June 22
Comments Off
Posted by shirker2006
root@Server:~$ cat /usr/bin/check.sh
#!/bin/sh

# Script that checks if a specified app is running.
# You need to invoke this script with the name of the app
# but with the first letter inside square brackets
# E.g. app_running [s]afari
# (The square brackets prevent the invocation of this script
#  matching in the grep of the ps results)
# Note that case does matter: [s]afari is different from [s]afari

while [ 1 ]
do

ps ax | grep [a]stmanproxy | grep -v grep
if [ $? = 0 ]; then
    echo "astmanproxy is running"
else
    echo "astmanproxy is not running"
    /usr/local/sbin/astmanproxy
fi

ps ax | grep gnudialer | grep -v grep
if [ $? = 0 ]; then
    echo "gnudialer is running"
else
    echo "gnudialer is not running"
    /usr/bin/gnudialer stop
    /usr/bin/gnudialer >> /tmp/gtrace
fi

grep Shoppers /etc/asterisk/queues.conf | grep -v grep
if [ $? = 0 ]; then
   echo "OK"
else
   cp /etc/asterisk/queues.conf.bak /etc/asterisk/queues.conf
fi

sleep 5
done

echo “1″ > /proc/sys/net/ipv4/ip_forward

2011 June 22
Comments Off
Posted by shirker2006

echo “1″ > /proc/sys/net/ipv4/ip_forward

Координатор

★★★★★

Для проверки:

cat /proc/sys/net/ipv4/ip_forward

Долно напечатать 0 или 1.

Для включения:

echo "1" > /proc/sys/net/ipv4/ip_forward
BrAB> эта команда живет до перезагрузки. А надо чтоб всегдаНу так и впиши

net.ipv4.ip_forward = 1

в /etc/sysctl.conf

pwconv from www.opennet.ru

2011 June 21
Comments Off
Posted by shirker2006

НАЗВАНИЕ

pwconv, pwunconv, grpconv, grpunconv – преобразует пароли пользователей и групп в/из защищённую форму 

СИНТАКСИС

pwconv
pwunconv
grpconv
grpunconv

ОПИСАНИЕ

Команда pwconv создаёт файл shadow из файла passwd и необязательно существующего файла shadow.

Команда pwunconv создаёт файл passwd из файлов passwd и shadow, а затем удаляет файл shadow.

Команда grpconv создаёт файл gshadow из файла group и необязательно существующего файла gshadow.

Команда grpunconv создаёт файл group из файлов group и gshadow, а затем удаляет файл gshadow.

Эти четыре программы работают с файлами обычных или теневых паролей пользователей и групп: /etc/passwd/etc/group/etc/shadow и /etc/gshadow.

Каждая программа выполняет необходимые блокировки перед преобразованиями. Команды pwconv и grpconv выполняют схожий порядок действий. Сначала удаляются записи из теневого файла которых нет в главном файле. Затем обновляются записи в теневом файле которые не содержат `x’ вместо пароля в главном файле. Далее добавляются отсутствующие теневые записи. Наконец, пароли в главном файле заменяются символом `x’. Данные программы можно использовать как для первоначального преобразования, так и для обновления теневого файла, если главный файл редактировался вручную.

Команда pwconv использует значения переменных PASS_MIN_DAYSPASS_MAX_DAYS и PASS_WARN_AGE из файла /etc/login.defs при добавлении новых записей в файл /etc/shadow.

Программы pwunconv и grpunconv также выполняют схожий порядок действий. Пароли в главном файле обновляются из теневого файла. Записи, которые существуют в главном файле, но не существуют в теневом файле оставляются как есть. По окончании, теневой файл удаляется. Информация об устаревании пароля не учитывается программой pwunconv. Конвертируется только возможное. 

ОШИБКИ РЕАЛИЗАЦИИ

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

CONFIGURATION

The following configuration variable in /etc/login.defs changes the behavior of grpconv and grpunconv:

MAX_MEMBERS_PER_GROUP (number)

Maximum members per group entry. When the maximum is reached, a new group entry (line) is started in /etc/group (with the same name, same password, and same GID).The default value is 0, meaning that there are no limits in the number of members in a group.

This feature (split group) permits to limit the length of lines in the group file. This is useful to make sure that lines for NIS groups are not larger than 1024 characters.

If you need to enforce such limit, you can use 25.

Note: split groups may not be supported by all tools (even in the Shadow toolsuite. You should not use this variable unless you really need it.

The following configuration variables in /etc/login.defs change the behavior of pwconv:

PASS_MAX_DAYS (number)

Максимальное число дней использования пароля. Если пароль старее этого числа, то будет запущена процедура смены пароля. Если значение не задано, то предполагается значение -1 (то есть возможность ограничения не используется).

PASS_MIN_DAYS (number)

Максимальное число дней между изменениями пароля. Любая смена пароля ранее заданного срока выполнена не будет. Если значение не задано, то предполагается значение -1 (то есть возможность ограничения не используется).

PASS_WARN_AGE (number)

Число дней за которое начнёт выдаваться предупреждение об устаревании пароля. Нулевое значение означает, что предупреждение выдаётся в день устаревания, при отрицательном значении предупреждение выдаваться не будет. Если значение не задано, выдача предупреждения отключается.

ФАЙЛЫ

/etc/login.defs

содержит конфигурацию подсистемы теневых паролей

СМОТРИТЕ ТАКЖЕ

grpck(8), login.defs(5), pwck(8).

[bash] queues.conf backup (or any file – backup by time)

2011 June 18
Comments Off
Posted by shirker2006
0 * * * * cp /etc/asterisk/queues.conf /var/backups/queues.conf_`date +\%Y-\%m-\%d-\%H-\%M-\%S` #Copy queue.conf file to queue.conf file with the date

[bash]Converting files by ext.. just some scripts

2011 June 18
Comments Off
Posted by shirker2006

#!/bin/bash
#
# wav2mp3
#
cd /home/user/folder`date +%m%d%y`
for i in `find . -cmin +1 -type f -regex “.+-out.wav$”`; do
/usr/bin/sox -v 1.2 -m “$i” “${i%out.wav}in.wav” “${i%-out.wav}.mp3″
rm $i “${i%out.wav}in.wav”
done

[root@server scripts]# cat convertshell_by_fodername_sox.sh

#!/bin/bash
#
# wav2mp3
#
cd /home/user/$1
for i in `find . -cmin +1 -type f -regex “.+wav$”`; do
/usr/bin/sox -v 1.2 -m “$i” “${i%.wav}.mp3″
rm “$i”
done

[bash]agents control script for Asterisk, that will send warning

2011 June 18
Comments Off
Posted by shirker2006

We need to make some script, that will warn TLs, that too many agents logged in some server
to see count of agents we can run:

sudo asterisk -rx “show queue CAMPAIGN” | grep Agent| grep -v Una | wc -l

#!/bin/bash

VAR1=`sudo asterisk -rx “show queue  CAMPAIGN” | grep Agent| grep -v Una | wc -l`
VAR2=`uname -a | awk ‘{print $2}’`

echo $VAR1
echo $VAR2

case $VAR2 in
["server1"]*)
SERV=”45″
;;
["server2"]*)
SERV=”88″
;;
["server3"]*)
SERV=”43″
;;
esac
echo $SERV
subject=`echo “move agents from server $SERV”`

if [$var2>50];then
echo $subject | mail -s $subject vladimir.mitrofanov@host.net
fi

HOW TO SHUTDOWN AND REBOOT WITHOUT SUDO PASSWORD?

2011 June 18
Comments Off
Posted by shirker2006

f you are gnome user, you probably enjoy shutdown with just a click on the dialog. In order to shutdown from command line, you are requested to be either root or using sudo, such as
sudo shutdown -h now
For more detail examples of shutdown, continue to read here.
With sudo, you need to type your password. Sometimes it will be more convenient to us if we are able to shutdown without sudo. Is it possible?
The answer is yes, there are two ways to do that (Any other ways available?)
1. Adding suid mode to /sbin/shutdown
2. Modify /etc/sudoers with visudo
1. Adding suid mode to /sbin/shutdown
By adding suid mode to shutdown command, you are allowing regular user to run shutdown command as root.

sudo chmod u+s /sbin/shutdown

Check out examples of chmod here.
Now you can run shutdown without needing sudo.
2. Modify /etc/sudoers with visudo
This seems to be proper way to allow a command to run as root from specified users without needing to type password.

sudo visudo

By running visudo, it leads to edit /etc/sudoers.
Adding the line below to that file, assume mysurface is the user that allow to shutdown without password.

mysurface ALL = NOPASSWD: /sbin/shutdown

For ubuntu, usually the default user is in the %admin group. Therefore, you can also allow all users from the %admin group to shutdown without password.

%admin ALL = NOPASSWD: /sbin/shutdown

In fact, you still need sudo to shutdown, but this time you do not need to specified password.

sudo shutdown -h now

You can also reboot the system by using shutdown command too.

sudo shutdown -r now

Related Posts
Shutdown/Reboot using ’shutdown’
It have a lot of way to shutdown/reboot your machine, the easier way is using shutdown button in gnome or KDE menu ;p Th…
shutdown using init
init are usually use to initialize linux runlevel, but 0 are run level of halt and 6 are run level of reboot. Therefo…
sudo is different from su
Some of the distro uses sudo to gaim access to run root privilage commands. But some of the distro do not include sudo b…

SSH login without password

2011 June 18
Comments Off
Posted by shirker2006

Your aim

You want to use Linux and OpenSSH to automize your tasks. Therefore you need an automatic login from host A / user a to Host B / user b. You don’t want to enter any passwords, because you want to call ssh from a within a shell script.

How to do it

First log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:

a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa):
Created directory ‘/home/a/.ssh’.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A
Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):

a@A:~> ssh b@B mkdir -p .ssh
b@B’s password:

Finally append a’s new public key to b@B:.ssh/authorized_keys and enter b’s password one last time:

a@A:~> cat .ssh/id_rsa.pub | ssh b@B ‘cat >> .ssh/authorized_keys’
b@B’s password:

From now on you can log into B as b from A as a without password:

a@A:~> ssh b@B hostname
B

A note from one of our readers: Depending on your version of SSH you might also have to do the following changes:

Put the public key in .ssh/authorized_keys2
Change the permissions of .ssh to 700
Change the permissions of .ssh/authorized_keys2 to 640

Linux Read CPU Temperature Sensor Chip Data

2011 June 18
Comments Off
Posted by shirker2006

Linux Read CPU Temperature Sensor Chip Data
by VIVEK GITE on MAY 5, 2008 · 13 COMMENTS

Q. How do I read CPU core temperature data from a shell prompt under Linux operating system? How do I monitor my cpu hardware?

A. You can use Linux hardware monitoring tool such as lm_sensor. This tool provides some essential tools for monitoring the hardware health of Linux systems containing hardware health monitoring hardware such as the LM78, and LM75.

This tool use the System Management Bus (SMBus or SMB), which is a simple two-wire bus, derived from I²C and used for communication with low-bandwidth devices on a motherboard, especially power related chips such as a laptop’s rechargeable battery subsystem. Other devices might include temperature, fan, or voltage sensors; and lid switches. PCI add-in cards may connect to an SMBus segment.

Install lm_sensors / lm-sensors package

This package may or may not be installed. Type the following command to install software on CentOS / RHEL / Fedora Linux:

# yum install lm_sensors

If you are using Debian / Ubuntu Linux, enter:

$ sudo apt-get install lm-sensors

Configure lm_sensors

To detect hardware monitoring chips, type the following command as the root user:

# sensors-detect

OR

$ sudo sensors-detect

Sample output:

# sensors-detect revision 4609 (2007-07-14 09:28:39 -0700)

This program will help you determine which kernel modules you need
to load to use lm_sensors most effectively. It is generally safe
and recommended to accept the default answers to all questions,
unless you know what you’re doing.

We can start with probing for (PCI) I2C or SMBus adapters.
Do you want to probe now? (YES/no):
Probing for PCI bus adapters…
Use driver `i2c-i801′ for device 0000:00:1f.3: Intel 82801G ICH7

We will now try to load each adapter module in turn.
Module `i2c-i801′ already loaded.
If you have undetectable or unsupported adapters, you can have them
scanned by manually loading the modules before running this script.

To continue, we need module `i2c-dev’ to be loaded.
Do you want to load `i2c-dev’ now? (YES/no):
Module loaded successfully.

We are now going to do the I2C/SMBus adapter probings. Some chips may
be double detected; we choose the one with the highest confidence
value in that case.
If you found that the adapter hung after probing a certain address,
you can specify that address to remain unprobed.

Next adapter: saa7133[0] (i2c-0)
Do you want to scan it? (YES/no/selectively):
Client found at address 0×47
Handled by driver `ir-kbd-i2c’ (already loaded), chip type `Pinnacle PCTV’
(note: this is probably NOT a sensor chip!)
Client found at address 0x4b
Handled by driver `tuner’ (already loaded), chip type `tda8290+75a’
(note: this is probably NOT a sensor chip!)
Client found at address 0×50
Probing for `Analog Devices ADM1033′… No
Probing for `Analog Devices ADM1034′… No
Probing for `SPD EEPROM’… No
Probing for `EDID EEPROM’… No

Next adapter: SMBus I801 adapter at 4000 (i2c-1)
Do you want to scan it? (YES/no/selectively):
Client found at address 0x2e
Probing for `Myson MTP008′… No
Probing for `National Semiconductor LM78′… No
Probing for `National Semiconductor LM78-J’… No
Probing for `National Semiconductor LM79′… No
Probing for `National Semiconductor LM80′… No
Probing for `National Semiconductor LM85 or LM96000′… No
Probing for `Analog Devices ADM1027, ADT7460 or ADT7463′… No
Probing for `SMSC EMC6D100, EMC6D101 or EMC6D102′… No
Probing for `Analog Devices ADT7462′… No
Probing for `Analog Devices ADT7467 or ADT7468′… No
Probing for `Analog Devices ADT7470′… No
Probing for `Analog Devices ADT7473′… No
Probing for `Analog Devices ADT7475′… No
Probing for `Analog Devices ADT7476′… No
Probing for `Andigilog aSC7611′… No
Probing for `Andigilog aSC7621′… Success!
(confidence 5, driver `to-be-written’)
Probing for `National Semiconductor LM87′… No
Probing for `National Semiconductor LM93′… No
Probing for `Winbond W83781D’… No
Probing for `Winbond W83782D’… No
Probing for `Winbond W83792D’… No
Probing for `Winbond W83793R/G’… No
Probing for `Winbond W83791SD’… No
Probing for `Winbond W83627HF’… No
Probing for `Winbond W83627EHF’… No
Probing for `Winbond W83627DHG’… No
Probing for `Asus AS99127F (rev.1)’… No
Probing for `Asus AS99127F (rev.2)’… No
Probing for `Asus ASB100 Bach’… No
Probing for `Winbond W83L785TS-S’… No
Probing for `Analog Devices ADM9240′… No
Probing for `Dallas Semiconductor DS1780′… No
Probing for `National Semiconductor LM81′… No
Probing for `Analog Devices ADM1026′… No
Probing for `Analog Devices ADM1025′… No
Probing for `Analog Devices ADM1024′… No
Probing for `Analog Devices ADM1029′… No
Probing for `Analog Devices ADM1030′… No
Probing for `Analog Devices ADM1031′… No
Probing for `Analog Devices ADM1022′… No
Probing for `Texas Instruments THMC50′… No
Probing for `Analog Devices ADM1028′… No
Probing for `ITE IT8712F’… No
Probing for `SMSC DME1737′… No
Probing for `Fintek F75373S/SG’… No
Probing for `Fintek F75375S/SP’… No
Probing for `Fintek F75387SG/RG’… No
Probing for `Winbond W83791D’… No
Client found at address 0×44
Probing for `Maxim MAX6633/MAX6634/MAX6635′… No
Client found at address 0×50
Probing for `Analog Devices ADM1033′… No
Probing for `Analog Devices ADM1034′… No
Probing for `SPD EEPROM’… Yes
(confidence 8, not a hardware monitoring chip)
Probing for `EDID EEPROM’… No

Some chips are also accessible through the ISA I/O ports. We have to
write to arbitrary I/O ports to probe them. This is usually safe though.
Yes, you do have ISA I/O ports even if you do not have any ISA slots!
Do you want to scan the ISA I/O ports? (YES/no):
Probing for `National Semiconductor LM78′ at 0×290… No
Probing for `National Semiconductor LM78-J’ at 0×290… No
Probing for `National Semiconductor LM79′ at 0×290… No
Probing for `Winbond W83781D’ at 0×290… No
Probing for `Winbond W83782D’ at 0×290… No
Probing for `Silicon Integrated Systems SIS5595′… No
Probing for `VIA VT82C686 Integrated Sensors’… No
Probing for `VIA VT8231 Integrated Sensors’… No
Probing for `IPMI BMC KCS’ at 0xca0… No
Probing for `IPMI BMC SMIC’ at 0xca8… No

Some Super I/O chips may also contain sensors. We have to write to
standard I/O ports to probe them. This is usually safe.
Do you want to scan for Super I/O sensors? (YES/no):
Probing for Super-I/O at 0x2e/0x2f
Trying family `National Semiconductor’… No
Trying family `SMSC’… Yes
Found `SMSC LPC47M182 Super IO Fan Sensors’
(but not activated)
Probing for Super-I/O at 0x4e/0x4f
Trying family `National Semiconductor’… No
Trying family `SMSC’… No
Trying family `VIA/Winbond/Fintek’… No
Trying family `ITE’… No

Some CPUs or memory controllers may also contain embedded sensors.
Do you want to scan for them? (YES/no):
AMD K8 thermal sensors… No
Intel Core family thermal sensor… Success!
(driver `coretemp’)
Intel AMB FB-DIMM thermal sensor… No

Now follows a summary of the probes I have just done.
Just press ENTER to continue:

Driver `to-be-written’ (should be inserted):
Detects correctly:
* Bus `SMBus I801 adapter at 4000′
Busdriver `i2c-i801′, I2C address 0x2e
Chip `Andigilog aSC7621′ (confidence: 5)

Driver `coretemp’ (should be inserted):
Detects correctly:
* Chip `Intel Core family thermal sensor’ (confidence: 9)

I will now generate the commands needed to load the required modules.
Just press ENTER to continue:

To make the sensors modules behave correctly, add these lines to
/etc/modules:

#—-cut here—-
# I2C adapter drivers
i2c-i801
# Chip drivers
# no driver for Andigilog aSC7621 yet
coretemp
#—-cut here—-

Do you want to add these lines to /etc/modules automatically? (yes/NO)

This is an interactive program that will walk you through the process of scanning your system for various hardware monitoring chips, or sensors, supported by libsensors, or more generally by the lm_sensors tool suite. For my system coretemp and i2c-i801 driver need to loaded in order to see sensors data. Type ‘YES” to update /etc/modules files. Now you need to reboot the box. Alternatively, you can load all drivers using modprobe command

# modprobe coretemp
# modprobe i2c-i801

How do I read sensors chip data such as temperature?

Type the following command at shell prompt:

$ sensors

Sample output:

coretemp-isa-0000
Adapter: ISA adapter
Core 0: +59°C (high = +100°C)

coretemp-isa-0001
Adapter: ISA adapter
Core 1: +59°C (high = +100°C)

coretemp-isa-0002
Adapter: ISA adapter
Core 2: +55°C (high = +100°C)

coretemp-isa-0003
Adapter: ISA adapter
Core 3: +56°C (high = +100°C)

Here is another output from Intel xeon server box:

w83627hf-i2c-0-2d
Adapter: SMBus I801 adapter at 1100

VCore 1: +4.08 V (min = +1.34 V, max = +1.49 V) ALARM
VCore 2: +4.08 V (min = +1.34 V, max = +1.49 V) ALARM
+3.3V: +4.08 V (min = +3.14 V, max = +3.46 V) ALARM
+5V: +5.11 V (min = +4.73 V, max = +5.24 V)
+12V: +11.73 V (min = +10.82 V, max = +13.19 V)
-12V: +1.21 V (min = -13.18 V, max = -10.88 V) ALARM
-5V: +2.24 V (min = -5.25 V, max = -4.75 V) ALARM
V5SB: +5.51 V (min = +4.73 V, max = +5.24 V) ALARM
VBat: +0.54 V (min = +2.40 V, max = +3.60 V) ALARM
fan1: 0 RPM (min = 0 RPM, div = 2)
fan2: 0 RPM (min = 2689 RPM, div = 2) ALARM
fan3: 0 RPM (min = 6553 RPM, div = 2) ALARM
temp1: -48°C (high = -1°C, hyst = -25°C) sensor = thermistor
temp2: -48.0°C (high = +80°C, hyst = +75°C) sensor = thermistor
temp3: -48.0°C (high = +80°C, hyst = +75°C) sensor = thermistor
vid: +1.419 V (VRM Version 11.0)
alarms:
beep_enable:
Sound alarm enabled

w83627hf-isa-0290
Adapter: ISA adapter
VCore 1: +4.08 V (min = +1.34 V, max = +1.49 V) ALARM
VCore 2: +4.08 V (min = +1.34 V, max = +1.49 V) ALARM
+3.3V: +4.08 V (min = +3.14 V, max = +3.46 V) ALARM
+5V: +5.11 V (min = +4.73 V, max = +5.24 V)
+12V: +11.73 V (min = +10.82 V, max = +13.19 V)
-12V: +1.29 V (min = -13.18 V, max = -10.88 V) ALARM
-5V: +2.24 V (min = -5.25 V, max = -4.75 V) ALARM
V5SB: +5.48 V (min = +4.73 V, max = +5.24 V) ALARM
VBat: +0.54 V (min = +2.40 V, max = +3.60 V) ALARM
fan1: 0 RPM (min = 0 RPM, div = 2)
fan2: 0 RPM (min = 2689 RPM, div = 2) ALARM
fan3: 0 RPM (min = 6553 RPM, div = 2) ALARM
temp1: -48°C (high = -1°C, hyst = -25°C) sensor = thermistor
temp2: -48.0°C (high = +80°C, hyst = +75°C) sensor = thermistor
temp3: -48.0°C (high = +80°C, hyst = +75°C) sensor = thermistor
vid: +1.419 V (VRM Version 11.0)
alarms:
beep_enable:
Sound alarm enabled

Configuring Static Routes CentOs

2011 June 17
Comments Off
Posted by shirker2006

Routing will be configured on routing devices, therefore it should not be necessary to configure static routes on Red Hat Enterprise Linux servers or clients. However, if static routes are required they can be configured for each interface. This can be useful if you have multiple interfaces in different subnets. Use the route command to display the IP routing table.

Static route configuration is stored in a /etc/sysconfig/network-scripts/route-interface file. For example, static routes for the eth0 interface would be stored in the /etc/sysconfig/network-scripts/route-eth0 file. The route-interface file has two formats: IP command arguments and network/netmask directives.

IP Command Arguments Format

Define a default gateway on the first line. This is only required if the default gateway is not set via DHCP:

default X.X.X.X dev interface
X.X.X.X is the IP address of the default gateway. The interface is the interface that is connected to, or can reach, the default gateway.

Define a static route. Each line is parsed as an individual route:

X.X.X.X/X via X.X.X.X dev interface
X.X.X.X/X is the network number and netmask for the static route. X.X.X.X and interface are the IP address and interface for the default gateway respectively. The X.X.X.X address does not have to be the default gateway IP address. In most cases, X.X.X.X will be an IP address in a different subnet, and interface will be the interface that is connected to, or can reach, that subnet. Add as many static routes as required.

The following is a sample route-eth0 file using the IP command arguments format. The default gateway is 192.168.0.1, interface eth0. The two static routes are for the 10.10.10.0/24 and 172.16.1.0/24 networks:

default 192.168.0.1 dev eth0
10.10.10.0/24 via 192.168.0.1 dev eth0
172.16.1.0/24 via 192.168.0.1 dev eth0

Static routes should only be configured for other subnets. The above example is not necessary, since packets going to the 10.10.10.0/24 and 172.16.1.0/24 networks will use the default gateway anyway. Below is an example of setting static routes to a different subnet, on a machine in a 192.168.0.0/24 subnet. The example machine has an eth0 interface in the 192.168.0.0/24 subnet, and an eth1 interface (10.10.10.1) in the 10.10.10.0/24 subnet:

10.10.10.0/24 via 10.10.10.1 dev eth1

Duplicate Default Gateways
If the default gateway is already assigned from DHCP, the IP command arguments format can cause one of two errors during start-up, or when bringing up an interface from the down state using the ifup command: “RTNETLINK answers: File exists” or ‘Error: either “to” is a duplicate, or “X.X.X.X” is a garbage.’, where X.X.X.X is the gateway, or a different IP address. These errors can also occur if you have another route to another network using the default gateway. Both of these errors are safe to ignore.
Network/Netmask Directives Format

You can also use the network/netmask directives format for route-interface files. The following is a template for the network/netmask format, with instructions following afterwards:

ADDRESS0=X.X.X.X
NETMASK0=X.X.X.X
GATEWAY0=X.X.X.X
ADDRESS0=X.X.X.X is the network number for the static route.
NETMASK0=X.X.X.X is the netmask for the network number defined with ADDRESS0=X.X.X.X.
GATEWAY0=X.X.X.X is the default gateway, or an IP address that can be used to reach ADDRESS0=X.X.X.X

The following is a sample route-eth0 file using the network/netmask directives format. The default gateway is 192.168.0.1, interface eth0. The two static routes are for the 10.10.10.0/24 and 172.16.1.0/24 networks. However, as mentioned before, this example is not necessary as the 10.10.10.0/24 and 172.16.1.0/24 networks would use the default gateway anyway:

ADDRESS0=10.10.10.0
NETMASK0=255.255.255.0
GATEWAY0=192.168.0.1
ADDRESS1=172.16.1.0
NETMASK1=255.255.255.0
GATEWAY1=192.168.0.1

Subsequent static routes must be numbered sequentially, and must not skip any values. For example, ADDRESS0, ADDRESS1, ADDRESS2, and so on.

Below is an example of setting static routes to a different subnet, on a machine in the 192.168.0.0/24 subnet. The example machine has an eth0 interface in the 192.168.0.0/24 subnet, and an eth1 interface (10.10.10.1) in the 10.10.10.0/24 subnet:

ADDRESS0=10.10.10.0
NETMASK0=255.255.255.0
GATEWAY0=10.10.10.1
DHCP should assign these settings automatically, therefore it should not be necessary to configure static routes on Red Hat Enterprise Linux servers or clients.

Apache – how to configure VirtualHost

2011 June 17
Comments Off
Posted by shirker2006
<VirtualHost *:80>
DocumentRoot “/var/www/html/pr1″
ServerName rec.host.com
ServerAlias rec3.host.com
<Directory “/var/www/html/pr1″>
Order Allow,Deny
allow from all
Options -Indexes
</Directory>
<Directory “/var/www/html/pr1/config”>
Order Deny,Allow
deny from all
</Directory>
<Directory “/var/www/html/pr1/dl”>
Order Allow,Deny
Allow from all
Options +Indexes
</Directory>
</VirtualHost>

How to find big files in linux

2011 June 17
Comments Off
Posted by shirker2006
# find / -type f -size +100000k -exec ls -lh {} \; | awk ‘{ print $8 “: ” $5 }’
zoestardust posts on Feb 26, 2008 at 23:06
This does not show names or locations, it just lists a bunch of file sizes

syncshaker posts on Apr 08, 2008 at 05:25
You can customize this command by changing e.g. / by . or any directory path, or – and zoestardust you’re right to point it out – by replacing in awk $9 by likely $8. Anyway the command is globally right ;) ( a typo ? )

webshowpro posts on Jul 22, 2008 at 10:56

It does work as shown on older versions of RedHat, and likely others. The output of awk seems to have changed a bit over the years and on Ubuntu (probably all Debian) based system the above command will only show a list of file sizes. As syncshaker pointed out on Ubuntu systems change the $9 to a $8 and it will work:

find / -type f -size +20000k -exec ls -lh {} \; | awk ‘{ print $8 “: ” $5 }’

actualmind posts on Mar 12, 2009 at 01:48

actually it’s probably just better to use the NF in place of numbers in that case no?

find / -type f -size +20000k -exec ls -lh {} \; | awk ‘{ print $NF “: ” $5 }’

michaelshiloh posts on Apr 17, 2009 at 12:22

Find reports errors when it searches directories for which it has no permissions. To discard these errors, redirect stderr to /dev/null:

find / -type f -size +20000k -exec ls -lh {} \; 2> /dev/null | awk ‘{ print $NF “: ” $5 }’

Additionally, I find it handy to sort (numerically) based on the size (second column):

find / -type f -size +20000k -exec ls -lh {} \; 2> /dev/null | awk ‘{ print $NF “: ” $5 }’ | sort -nk 2,2

michaelshiloh posts on Apr 17, 2009 at 12:30

I forgot to add to sort in reverse order, so you get the biggest ones first:

find / -type f -size +20000k -exec ls -lh {} \; 2> /dev/null | awk '{ print $NF ": " $5 }'  | sort -nrk 2,2

Next step will be to direct find to skip virtual directories like /proc and /sys

hrh_count_zero posts on Jun 17, 2010 at 03:46

why so complicated?

find . -size +20000k -exec du -h {} \;

du : Estimate file space usage
sort : Sort lines of text files or given input data
head : Output the first part of files i.e. to display first 10 largest file
Here is what you need to type at shell prompt to find out top 10 largest file/directories is taking up the most space in a /var directory/file system:
# du -a /var | sort -n -r | head -n 10

shutting down asterisk before power off

2011 June 17
Comments Off
Posted by shirker2006

script /usr/sbin/safe_asterisk_down ( just modified safe_asterisk_restart)

[root@Dragon ~]# crontab -l
* * * * * /root/monmv.sh
0 */1 * * * /root/monmddir.sh
*/10 * * * * /bin/mount -a

<***>

30 23 * * * /usr/sbin/safe_asterisk_down > /dev/null 2>&1
45 23 * * * /sbin/init 0

[root@helium ~]# cat /usr/sbin/safe_asterisk_down
#!/bin/bash
# vim:textwidth=80:tabstop=4:shiftwidth=4:smartindent
#
# this scripts prompts the user thrice, then tells asterisk to please shut down,
# then kills asterisk and related processes with SIGTERM, then kills asterisk
# and related processes with SIGKILL, and then starts asterisk with
# safe_asterisk. Three arguments are currently supported, –no-countdown,
# –no-prompt and –no-stop-now-first

LOGFILE=/var/log/asterisk/safe_asterisk_restart.log
ASTERISK=/usr/sbin/asterisk
SAFE_ASTERISK=/usr/sbin/safe_asterisk

DELAY=1 # Seconds between steps in countdown
COUNTDOWN_FROM=5 # Steps to count down
DO_COUNTDOWN=1 # Should I do a countdown before restarting asterisk?
# that this might make this script hang if asterisk
# can’t respond to the command.

# processes to kill. Please list all AGI scripts here as well as the asterisk
# processes, since asterisk may leave them unkilled.
PROCVICTIMS=”safe_asterisk asterisk mpg123″

# helper functions
# die ["string to print"]
function die {
if [[ "$1" != "" ]]; then
echo $1
else
echo “ok. no harm done…”
fi
exit
}

# docmd “string to print” “cmd”
function docmd {
printf “$1…”
`$2 >> $LOGFILE 2>&1`
RETCODE=$?
sleep $DELAY
if [[ "$RETCODE" == "0" ]]; then
echo ” OK”
else
echo ” FAILED”
fi
}

# prompt “string” “positive answer”
function prompt {
printf “$1″
read answer
if [[ "$answer" != "$2" ]]; then
die
fi
}

# am I really root?
if [[ "$UID" != "0" ]]; then
echo “Sorry, only root can do this.” >&2
exit;
fi

echo “`date`: $0 invoked” >> $LOGFILE

# doing the dirty work
docmd “Asking asterisk kindly to shutdown” “$ASTERISK -rx ‘stop now’”
docmd “Sending asterisk processes the TERM signal” “killall -15 $PROCVICTIMS”
docmd “Sending asterisk processes KILL signal” “killall -9 $PROCVICTIMS”

for i in $PROCVICTIMS
do
ps axf | grep -w $i | grep -v grep
done

Handy stuff for cisco routers

2011 June 17
Comments Off
Posted by shirker2006

17173

to add a route:
config t
ip route ipaddress subnetmask destination

to remove a route:
config t
no ip route ipaddress subnetmask destination

to null route an IP address:
config t
ip route ipaddress subnetmask null0

to find a dsl login:
sh user | include xxxxx
where xxxxx = either the login name or IP address

to show interfaces of a certain type quickly:
sh ip int brief | include ATM
where ATM can be whatever text identifies the interfaces

to show how much is blocked by access lists:
sh access-lists

to find a DSL user on a specific IP:
sh caller ip | include ipaddress

to reset a DSL user:
clear int vi4.28

to reinit a DSL user:
config t
int atm5/ima2.100 POI (or whatever their interface number is)
shut
no shut
exit

to track down non-existant dsl user:
config t
logging 216.144.x.x  (ip of syslog host)
debug pppoe or pppatm or whatever events you need.
debug ppp authentication
debug vpdn pppoe-events (att or sbc)
no debug all (to turn it off)

cle router
term mon
debug ppp auth
debug pppoe event (watch for login and write it down with vpi/vci)
no debug all
term no mon

ATM pinging from a cisco:
ping ATM INT a5/ima1.100 vpi vci e
Example: ping atm int a5/ima1.100 1 83 e
the e means ping endpoint.

Explains how to use a cisco router to track a flood

columbus- build a dlci based dsl interface
config t
int s2/1.136 poi
frame-relay interface-dlci 136 IETF
exit (once)
bridge-group 1

columbus find user
r-col1#sh arp | include 216.144.63.24
Internet 216.144.63.24 18 0010.dcf8.1dd1 ARPA BVI1

r-col1#sh bridge 1 | include 0010.dcf8.1dd1
0010.dcf8.1dd1 forward Serial6/0.131 0 627740 172240

lookup dlci 131 in chart

Access Lists (hssi1/0.500 and hssi2/0)
clear ip access-lists counters
sh ip access-lists 152
no ip access-group 152 out

Hung VPDN tunnels
sh vpdn tunnel sum
look for wt-ctl
sh config and look for atm5/ima1.something
config t to shut no shut

xp and freebsd

2010 April 3
Comments Off
Posted by shirker2006

1) Устанавливается XP.
2) Устанавливается FreeBSD.
3) файл /boot/boot1 копируем на дискету (ну или на fat раздел какой-нить)
4) С помощью установочного диска XP запускаем консоль восстановления, делаем последовательно
fixboot c: (зависит от вашего Windows раздела)
fixmbr \Device\HardDisk0. (Зависит от вашего жесткого диска, используйте map для определения точного названия)
(при этом восстанавливается загрузчик XP)
5) Копируем boot1 с дискеты в С:\bootsect.bsd (см. FreeBSD FAQ). В boot.ini добавляем строку C:\bootsect.bsd=”FreeBSD”.

Все. При перезагрузке появляется меню выбора между Windows и FreeBSD. Одна из прелестей в том, что всегда можно безбоязненно форматировать раздел с FreeBSD (полезно начинающим. мне БЫ в свое время ой как пригодилось )

[bash] Remove Users and their directories from LDAP server, that NOT in active users list

2010 April 2
Comments Off
Posted by shirker2006

Task: Remove Users and their directories from LDAP server, that NOT in active users list

users1.txt – userlist from HR

We will leave only theses users

users2.txt – all LDAP users:

smbldap-userlist -u > users.txt
awk -F"|" '{ print $2 }' users.txt > users_1.txt

Next we will clean tab signs and spaces:

cat users_1.txt | sed 's/^[ t]*//;s/[ t]*$//' > users2.txt

Next we will create PHP (php_script.php) to compare two files:

<?php
$file_array1 = file( "users1.txt" );
//print_r ($file_array1);

$file_array2 = file( "users2.txt" );
//print_r ($file_array2);

$result = array_diff($file_array2, $file_array1);
print_r ($result);
?>

To run this PHP script use:
root@localhos:~# /usr/bin/php -f php_script.php > users3.txt

clean up:

awk -F"=>" '{ print $2 }' tmp.txt > users_to_delete.txt

Then we will delete non-active users:

#!/bin/bash
for i in `cat users_to_delete.txt`;
do echo "going to remove user $i";
/usr/sbin/smbldap-userdel -r $i;
echo "going to remove directory of $i";
rm -R /home/$i;
done;

Asterisk 1.4.0 CLI commands

2010 April 2
Comments Off
Posted by shirker2006

Introduction

Asterisk CLI supports large variety of commands which can be used for testing, configuration and monitoring. In this tutorial we will describe all commands available at the standard Asterisk version 1.4.0. We will divide this tutorial into few sections in order to facilitate the reading.

General CLI commands

! – Execute a shell command
abort halt – Cancel a running halt
cdr status – Display the CDR status
feature show – Lists configured features
feature show channels – List status of feature channels
file convert – Convert audio file
group show channels – Display active channels with group(s)
help – Display help list, or specific help on a command
indication add – Add the given indication to the country
indication remove – Remove the given indication from the country
indication show – Display a list of all countries/indications
keys init – Initialize RSA key passcodes
keys show – Displays RSA key information
local show channels – List status of local channels
logger mute – Toggle logging output to a console
logger reload – Reopens the log files
logger rotate – Rotates and reopens the log files
logger show channels – List configured log channels
meetme – Execute a command on a conference or conferee
mixmonitor – Execute a MixMonitor command.

moh reload – Music On Hold
moh show classes – List MOH classes
moh show files – List MOH file-based classes
no debug channel (null)
originate – Originate a call
realtime load – Used to print out RealTime variables.
realtime update – Used to update RealTime variables.
restart gracefully – Restart Asterisk gracefully
restart now – Restart Asterisk immediately
restart when convenient – Restart Asterisk at empty call volume
sla show – Show status of Shared Line Appearances
soft hangup – Request a hangup on a given channel
stop gracefully – Gracefully shut down Asterisk
stop now – Shut down Asterisk immediately
stop when convenient – Shut down Asterisk at empty call volume
stun debug – Enable STUN debugging
stun debug off – Disable STUN debugging
udptl debug – Enable UDPTL debugging
udptl debug ip – Enable UDPTL debugging on IP
udptl debug off – Disable UDPTL debugging

AEL commands

ael debug contexts – Enable AEL contexts debug (does nothing)
ael debug macros – Enable AEL macros debug (does nothing)
ael debug read – Enable AEL read debug (does nothing)
ael debug tokens – Enable AEL tokens debug (does nothing)
ael nodebug – Disable AEL debug messages
ael reload – Reload AEL configuration

Agents commands

agent logoff – Sets an agent offline
agent show – Show status of agents
agent show online – Show all online agents

AGI commands

agi debug – Enable AGI debugging
agi debug off – Disable AGI debugging
agi dumphtml – Dumps a list of agi commands in html format
agi show- List AGI commands or specific help
dnsmgr reload – Reloads the DNS manager configuration
dnsmgr status – Display the DNS manager status
http show status – Display HTTP server status

Console commands

console active – Sets/displays active console
console answer – Answer an incoming console call
console autoanswer – Sets/displays autoanswer
console boost – Sets/displays mic boost in dB
console dial – Dial an extension on the console
console flash – Flash a call on the console
console hangup – Hangup a call on the console
console mute – Disable mic input
console send text – Send text to the remote device
console transfer – Transfer a call to a different extension
console unmute – Enable mic input

Core related commands

core clear profile – Clear profiling info
core set debug channel – Enable/disable debugging on a channel
core set debug – Set level of debug chattiness
core set debug off – Turns off debug chattiness
core set global – Set global dialplan variable
core set verbose – Set level of verboseness
core show applications – Shows registered dialplan applications
core show application – Describe a specific dialplan application
core show audio codecs – Displays a list of audio codecs
core show channels – Display information on channels
core show channel – Display information on a specific channel
core show channeltypes – List available channel types
core show channeltype – Give more details on that channel type
core show codecs – Displays a list of codecs
core show codec – Shows a specific codec
core show config mappings – Display config mappings (file names to config engines)
core show file formats – Displays file formats
core show file version – List versions of files used to build Asterisk
core show functions – Shows registered dialplan functions
core show function – Describe a specific dialplan function
core show globals – Show global dialplan variables
core show hints – Show dialplan hints
core show image codecs – Displays a list of image codecs
core show image formats – Displays image formats
core show license – Show the license(s) for this copy of Asterisk
core show profile – Display profiling info
core show switches – Show alternative switches
core show threads – Show running threads
core show translation – Display translation matrix
core show uptime – Show uptime information
core show version – Display version info
core show video codecs – Displays a list of video codecs
core show warranty – Show the warranty (if any) for this copy of Asterisk

Database commands

database del – Removes database key/value
database deltree – Removes database keytree/values
database get – Gets database value
database put – Adds/updates database value
database show – Shows database contents
database showkey – Shows database contents

Dialplan commands

dialplan add extension – Add new extension into context
dialplan add ignorepat – Add new ignore pattern
dialplan add include – Include context in other context
dialplan reload – Reload extensions and *only* extensions
dialplan remove extension – Remove a specified extension
dialplan remove ignorepat – Remove ignore pattern from context
dialplan remove include – Remove a specified include from context
dialplan save – Save dialplan
dialplan show – Show dialplan

DUNDI commands

dundi debug – Enable DUNDi debugging
dundi flush – Flush DUNDi cache
dundi lookup – Lookup a number in DUNDi
dundi no debug – Disable DUNDi debugging
dundi no store history – Disable DUNDi historic records
dundi precache – Precache a number in DUNDi
dundi query – Query a DUNDi EID
dundi show entityid – Display Global Entity ID
dundi show mappings – Show DUNDi mappings
dundi show peers – Show defined DUNDi peers
dundi show peer – Show info on a specific DUNDi peer
dundi show precache – Show DUNDi precache
dundi show requests – Show DUNDi requests
dundi show trans – Show active DUNDi transactions
dundi store history – Enable DUNDi historic records

GTalk & Jabber commands

gtalk reload – Enable Jabber debugging
gtalk show channels – Show GoogleTalk Channels
jabber debug – Enable Jabber debugging
jabber debug off – Disable Jabber debug
jabber reload – Enable Jabber debugging
jabber show connected – Show state of clients and components
jabber test – Shows roster, but is generally used for mog’s debugging.

IAX2 commands

iax2 provision – Provision an IAX device
iax2 prune realtime – Prune a cached realtime lookup
iax2 reload – Reload IAX configuration
iax2 set debug – Enable IAX debugging
iax2 set debug jb – Enable IAX jitterbuffer debugging
iax2 set debug jb off – Disable IAX jitterbuffer debugging
iax2 set debug off – Disable IAX debugging
iax2 set debug trunk – Enable IAX trunk debugging
iax2 set debug trunk off – Disable IAX trunk debugging
iax2 show cache – Display IAX cached dialplan
iax2 show channels – List active IAX channels
iax2 show firmware – List available IAX firmwares
iax2 show netstats – List active IAX channel netstats
iax2 show peers – List defined IAX peers
iax2 show peer – Show details on specific IAX peer
iax2 show provisioning – Display iax provisioning
iax2 show registry – Display IAX registration status
iax2 show stats – Display IAX statistics
iax2 show threads – Display IAX helper thread info
iax2 show users – List defined IAX users
iax2 test losspct – Set IAX2 incoming frame loss percentage

Manager commands

manager show command – Show a manager interface command
manager show commands – List manager interface commands
manager show connected – List connected manager interface users
manager show eventq – List manager interface queued events
manager show users – List configured manager users
manager show user – Display information on a specific manager user

MGCP commands

mgcp audit endpoint – Audit specified MGCP endpoint
mgcp reload – Reload MGCP configuration
mgcp set debug – Enable MGCP debugging
mgcp set debug off – Disable MGCP debugging
mgcp show endpoints – List defined MGCP endpoints

Module management

module load – Load a module by name
module reload – Reload configuration
module show – List modules and info
module show like – List modules and info
module unload – Unload a module by name

PRI commands

pri debug span – Enables PRI debugging on a span
pri intense debug span – Enables REALLY INTENSE PRI debugging
pri no debug span – Disables PRI debugging on a span
pri set debug file – Sends PRI debug output to the specified file
pri show debug – Displays current PRI debug settings
pri show spans – Displays PRI Information
pri show span – Displays PRI Information
pri unset debug file – Ends PRI debug output to file

Queue commands

queue add member – Add a channel to a specified queue
queue remove member – Removes a channel from a specified queue
queue show – Show status of a specified queue
rtcp debug ip – Enable RTCP debugging on IP
rtcp debug – Enable RTCP debugging
rtcp debug off – Disable RTCP debugging
rtcp stats – Enable RTCP stats
rtcp stats off – Disable RTCP stats
rtp debug ip – Enable RTP debugging on IP
rtp debug – Enable RTP debugging
rtp debug off – Disable RTP debugging
say load – Set/show the say mode
show parkedcalls – Lists parked calls
show queue – Show information for target queue
show queues – Show the queues

SIP commands

sip history – Enable SIP history
sip history off – Disable SIP history
sip notify – Send a notify packet to a SIP peer
sip prune realtime – Prune cached Realtime object(s)
sip prune realtime peer – Prune cached Realtime peer(s)
sip prune realtime user – Prune cached Realtime user(s)
sip reload – Reload SIP configuration
sip set debug – Enable SIP debugging
sip set debug ip – Enable SIP debugging on IP
sip set debug off – Disable SIP debugging
sip set debug peer – Enable SIP debugging on Peername
sip show channels – List active SIP channels
sip show channel – Show detailed SIP channel info
sip show domains – List our local SIP domains.
sip show history – Show SIP dialog history
sip show inuse – List all inuse/limits
sip show objects – List all SIP object allocations
sip show peers – List defined SIP peers
sip show peer – Show details on specific SIP peer
sip show registry – List SIP registration status
sip show settings – Show SIP global settings
sip show subscriptions – List active SIP subscriptions
sip show users – List defined SIP users
sip show user – Show details on specific SIP user

Skinny commands

skinny reset – Reset Skinny device(s)
skinny set debug – Enable Skinny debugging
skinny set debug off – Disable Skinny debugging
skinny show devices – List defined Skinny devices
skinny show lines – List defined Skinny lines per device

Voicemail commands

voicemail show users – List defined voicemail boxes
voicemail show users for – List defined voicemail boxes for target context
voicemail show zones – List zone message formats

Zaptel commands

zap destroy channel – Destroys a channel
zap restart – Fully restart zaptel channels
zap show cadences – List cadences
zap show channels – Show active zapata channels
zap show channel – Show information on a channel
zap show status – Show all Zaptel cards status



backup and restore MySQL database

2010 March 29
Comments Off
Posted by shirker2006
backup: # mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

restore:# mysql -u root -p[root_password] [database_name] < dumpfilename.sql

Dump only certain tables from a MySQL Database

mysqldump --user=XXXXXXXX --password=XXXXXXXX --databases DB_NAME --tables TABLE_NAME > /PATH/TO/DUMPFILE.SQL

on Heart server in /root/mysqltools i have some scripts:
to backup only one table run:

# ./one-table-dump.sh <dbname> <tablename>

#!/bin/bash
# one-table-dump.sh
/usr/bin/mysqldump --user=root --password=bigfoot123 --tables $1 --tables $2 | /bin/gzip -9 > $1.$2-/usr/bin/mysqldump --user=root --password=bigfoot123 --tables $1 --tables $2 | /bin/gzip -9 > $1.$2-`date +'%Y-%d-%m'`.gz

daily Rsnapshot backup MySQL db (mysqldump gzip rsync)

2010 March 29
Comments Off
Posted by shirker2006

backup MySQL databases from mysql.local to backup.local:/raid5/_rsnapshots

mysql.local:/root/rsnapshot.mysql script:

#!/bin/bash
# A UNIX / Linux shell script to backup mysql server database using rsnapshot utility.
# -------------------------------------------------------------------------
# Copyright (c) 2007 Vivek Gite
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# Tested under RHEL / Debian / CentOS / FreeBSD oses
# Must be Installed on remote MySQL Server
# -------------------------------------------------------------------------
# Last update: Sun Jul 5 2009 : Added mysql ping support and binary checking
# -------------------------------------------------------------------------
### SETUP MYSQL LOGIN ###
MUSER='root'
MPASS='passwd'
MHOST='localhost'

### Set to 1 if you need to see progress while dumping dbs ###
VERBOSE=0

### Set bins path ###
GZIP=/bin/gzip
MYSQL=/usr/bin/mysql
MYSQLDUMP=/usr/bin/mysqldump
RM=/bin/rm
MKDIR=/bin/mkdir
MYSQLADMIN=/usr/bin/mysqladmin
GREP=/bin/grep

### Setup dump directory ###
BAKRSNROOT=/raid5/mysql_dump

#####################################
### ----[ No Editing below ]------###
#####################################
### Default time format ###
TIME_FORMAT='%H_%M_%S%P'

### Make a backup ###
backup_mysql_rsnapshot(){
        local DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
        local db="";
        [ ! -d $BAKRSNROOT ] && ${MKDIR} -p $BAKRSNROOT
        ${RM} -f $BAKRSNROOT/* >/dev/null 2>&1
	[ $VERBOSE -eq 1 ] && echo "*** Dumping MySQL Database ***"
	[ $VERBOSE -eq 1 ] && echo -n "Database> "
#######for db in $DBS
        for db in `cat /root/rsnapshot.dblist`
        do
                local tTime=$(date +"${TIME_FORMAT}")
                local FILE="${BAKRSNROOT}/${db}.${tTime}.gz"
		[ $VERBOSE -eq 1 ] && echo -n "$db.."
                ${MYSQLDUMP} -u ${MUSER} -h ${MHOST} -p${MPASS} $db | ${GZIP} -9 > $FILE
        done
		[ $VERBOSE -eq 1 ] && echo ""
		[ $VERBOSE -eq 1 ] && echo "*** Backup done [ files wrote to $BAKRSNROOT] ***"
}

### Die on demand with message ###
die(){
	echo "$@"
	exit 999
}

### Make sure bins exists.. else die
verify_bins(){
	[ ! -x $GZIP ] && die "File $GZIP does not exists. Make sure correct path is set in $0."
	[ ! -x $MYSQL ] && die "File $MYSQL does not exists. Make sure correct path is set in $0."
	[ ! -x $MYSQLDUMP ] && die "File $MYSQLDUMP does not exists. Make sure correct path is set in $0."
	[ ! -x $RM ] && die "File $RM does not exists. Make sure correct path is set in $0."
	[ ! -x $MKDIR ] && die "File $MKDIR does not exists. Make sure correct path is set in $0."
	[ ! -x $MYSQLADMIN ] && die "File $MYSQLADMIN does not exists. Make sure correct path is set in $0."
	[ ! -x $GREP ] && die "File $GREP does not exists. Make sure correct path is set in $0."
}

### Make sure we can connect to server ... else die
verify_mysql_connection(){
	$MYSQLADMIN  -u $MUSER -h $MHOST -p$MPASS ping | $GREP 'alive'>/dev/null
	[ $? -eq 0 ] || die "Error: Cannot connect to MySQL Server. Make sure username and password are set correctly in $0"
}

### main ####
verify_bins
verify_mysql_connection
backup_mysql_rsnapshot

We no need backup all of our databases. i’ve change this
#######for db in $DBS
to
for db in `cat /root/rsnapshot.dblist`
in rsnapshot.dblist file we have databases list, that we need to backup
(to show all databases run SQL – show databases)

on backup.local rsnapshot program. this is config /etc/rsnapshot.conf

#################################################
# rsnapshot.conf - rsnapshot configuration file #
#################################################
#                                               #
# PLEASE BE AWARE OF THE FOLLOWING RULES:       #
#                                               #
# This file requires tabs between elements      #
#                                               #
# Directories require a trailing slash:         #
#   right: /home/                               #
#   wrong: /home                                #
#                                               #
#################################################

#######################
# CONFIG FILE VERSION #
#######################

config_version	1.2

###########################
# SNAPSHOT ROOT DIRECTORY #
###########################

# All snapshots will be stored under this root directory.
#
snapshot_root	/raid5/_rsnapshots/

# If no_create_root is enabled, rsnapshot will not automatically create the
# snapshot_root directory. This is particularly useful if you are backing
# up to removable media, such as a FireWire or USB drive.
#
#no_create_root	1

#################################
# EXTERNAL PROGRAM DEPENDENCIES #
#################################

# LINUX USERS:   Be sure to uncomment "cmd_cp". This gives you extra features.
# EVERYONE ELSE: Leave "cmd_cp" commented out for compatibility.
#
# See the README file or the man page for more details.
#
cmd_cp		/bin/cp

# uncomment this to use the rm program instead of the built-in perl routine.
#
cmd_rm		/bin/rm

# rsync must be enabled for anything to work. This is the only command that
# must be enabled.
#
cmd_rsync	/usr/bin/rsync

# Uncomment this to enable remote ssh backups over rsync.
#
cmd_ssh	/usr/bin/ssh

# Comment this out to disable syslog support.
#
cmd_logger	/usr/bin/logger

# Uncomment this to specify the path to "du" for disk usage checks.
# If you have an older version of "du", you may also want to check the
# "du_args" parameter below.
#
#cmd_du		/usr/bin/du

# Uncomment this to specify the path to rsnapshot-diff.
#
#cmd_rsnapshot_diff	/usr/local/bin/rsnapshot-diff

# Specify the path to a script (and any optional arguments) to run right
# before rsnapshot syncs files
#
#cmd_preexec	/path/to/preexec/script

# Specify the path to a script (and any optional arguments) to run right
# after rsnapshot syncs files
#
#cmd_postexec	/path/to/postexec/script

#########################################
#           BACKUP INTERVALS            #
# Must be unique and in ascending order #
# i.e. hourly, daily, weekly, etc.      #
#########################################

interval	hourly	6
interval	daily	7
interval	weekly	4
#interval	monthly	3

############################################
#              GLOBAL OPTIONS              #
# All are optional, with sensible defaults #
############################################

# Verbose level, 1 through 5.
# 1     Quiet           Print fatal errors only
# 2     Default         Print errors and warnings only
# 3     Verbose         Show equivalent shell commands being executed
# 4     Extra Verbose   Show extra verbose information
# 5     Debug mode      Everything
#
verbose		2

# Same as "verbose" above, but controls the amount of data sent to the
# logfile, if one is being used. The default is 3.
#
loglevel	3

# If you enable this, data will be written to the file you specify. The
# amount of data written is controlled by the "loglevel" parameter.
#
#logfile	/var/log/rsnapshot

# If enabled, rsnapshot will write a lockfile to prevent two instances
# from running simultaneously (and messing up the snapshot_root).
# If you enable this, make sure the lockfile directory is not world
# writable. Otherwise anyone can prevent the program from running.
#
lockfile	/var/run/rsnapshot.pid

# Default rsync args. All rsync commands have at least these options set.
#
#rsync_short_args	-a
#rsync_long_args	--delete --numeric-ids --relative --delete-excluded

# ssh has no args passed by default, but you can specify some here.
#
#ssh_args	-p 22

# Default arguments for the "du" program (for disk space reporting).
# The GNU version of "du" is preferred. See the man page for more details.
# If your version of "du" doesn't support the -h flag, try -k flag instead.
#
#du_args	-csh

# If this is enabled, rsync won't span filesystem partitions within a
# backup point. This essentially passes the -x option to rsync.
# The default is 0 (off).
#
#one_fs		0

# The include and exclude parameters, if enabled, simply get passed directly
# to rsync. If you have multiple include/exclude patterns, put each one on a
# separate line. Please look up the --include and --exclude options in the
# rsync man page for more details on how to specify file name patterns.
#
#include	???
#include	???
#exclude	???
#exclude	???

# The include_file and exclude_file parameters, if enabled, simply get
# passed directly to rsync. Please look up the --include-from and
# --exclude-from options in the rsync man page for more details.
#
#include_file	/path/to/include/file
#exclude_file	/path/to/exclude/file

# If your version of rsync supports --link-dest, consider enable this.
# This is the best way to support special files (FIFOs, etc) cross-platform.
# The default is 0 (off).
#
#link_dest	0

# When sync_first is enabled, it changes the default behaviour of rsnapshot.
# Normally, when rsnapshot is called with its lowest interval
# (i.e.: "rsnapshot hourly"), it will sync files AND rotate the lowest
# intervals. With sync_first enabled, "rsnapshot sync" handles the file sync,
# and all interval calls simply rotate files. See the man page for more
# details. The default is 0 (off).
#
#sync_first	0

# If enabled, rsnapshot will move the oldest directory for each interval
# to [interval_name].delete, then it will remove the lockfile and delete
# that directory just before it exits. The default is 0 (off).
#
#use_lazy_deletes	0

###############################
### BACKUP POINTS / SCRIPTS ###
###############################

# LOCALHOST
#backup	/home/		localhost/
#backup	/etc/		localhost/
#backup	/usr/local/	localhost/
#backup	/var/log/rsnapshot		localhost/
#backup	/etc/passwd	localhost/
#backup	/home/foo/My Documents/		localhost/
#backup	/foo/bar/	localhost/	one_fs=1, rsync_short_args=-urltvpog
#backup_script		/usr/local/bin/backup_pgsql.sh	localhost/postgres/

# EXAMPLE.COM
#backup_script	/bin/date "+ backup of example.com started at %c"	unused1
#backup	backup@192.168.11.7:/raid5/mysql/	mysql/	+rsync_long_args=--bwlimit=16,exclude=core
#backup	backup@192.168.11.7:/raid5/mysql/	Hart/
#backup	root@example.com:/etc/	example.com/	exclude=mtab,exclude=core
#backup_script	ssh root@example.com "mysqldump -A > /var/db/dump/mysql.sql"
#backup	root@example.com:/var/db/dump/	example.com/
#backup_script	/bin/date "+ backup of example.com ended at %c"	unused2

# CVS.SOURCEFORGE.NET
#backup_script	/usr/local/bin/backup_rsnapshot_cvsroot.sh	rsnapshot.cvs.sourceforge.net/

# RSYNC.SAMBA.ORG
#backup	rsync://rsync.samba.org/rsyncftp/	rsync.samba.org/rsyncftp/

backup_script	/usr/bin/ssh root@mysql.local "/root/rsnapshot.mysql"	mysqldump/
backup	root@mysql.local:/raid5/mysql_dump/	mysql/

this is crontab of backup.local server (we run only daily backup):

# m h  dom mon dow   command
#0 */8 * * * /usr/bin/rsnapshot hourly
00 11 * * * /usr/bin/rsnapshot daily

ubuntu – loosing array5 :(

2010 March 29
Comments Off
Posted by shirker2006

df
if we cant see array5 there use:

cat /proc/mdstat
cat /sys/block/md0/md/array_state
chould be “clean”
cat /sys/block/md5_d/md/array_state
-there is the problem

to check status use
mdadm -D /dev/md0
mdadm -D /dev/md_d5

if array5 is not exist in system after restart – go to /etc/mdadm/mdadm.conf

# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default, scan all partitions (/proc/partitions) for MD superblocks.
# alternatively, specify devices to scan, using wildcards if desired.
DEVICE partitions

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST 

# instruct the monitoring daemon where to send mail alerts
MAILADDR root

# definitions of existing MD arrays
ARRAY /dev/md0 level=raid1 num-devices=4 UUID=f6a9dc91:113e2dcc:e98f006c:315aa4a8

# This file was auto-generated on Tue, 29 Dec 2009 03:16:26 +0800
# by mkconf $Id$

ARRAY /dev/md_d5 level=raid5 num-devices=4 UUID=815a9f2b:ed3c8759:f827a6be:9a5128ee

last string you have to add manually. to get UUID use blkid

howto restart startx

2010 March 27
Comments Off
Posted by shirker2006

sudo kill `cat /tmp/.X0-lock`
startx

How to kill zombie process

2010 March 27
Comments Off
Posted by shirker2006

# ps aux | awk '{ print $8 " " $2 }' | grep -w Z

howto move table to another db

2010 March 22
Comments Off
Posted by shirker2006

ALTER TABLE base1.table RENAME base2.table

Create user account on LDAP.

2010 March 22
Comments Off
Posted by shirker2006

Create user account on LDAP.

LDAP accounts are used as centralized authentications for linux/windows/GLPI/KT.

use following format to create account on ldap server:

smbldap-useradd -a -m -A 1 -B 1 -N John -S Smith -T john.smith@724care.net (username)
smbldap-passwd -a -m (username)

replace name and email with the real name.

Modify user’s information

sudo smbldap-usermod -N -S -T

or we can write next script ldapuser_add

#!/bin/bash
#smbldap-useradd -a -m $1
#smbldap-useradd -a -m -A 1 -B 1 -N John -S Smith -T john.smith@724care.net (username)
smbldap-useradd -a -m -A 1 -B 1 -N $2 -S $3 -T $4 $1
smbldap-passwd $1

and run:

./ldapuser_add john John Smith john.smith@example.com

EmergencyPasswordReset Dell 3024/3048/5012

2010 March 22
Comments Off
Posted by shirker2006
Dell PowerConnect 3024/48/5012 Password Reset

Found this on the Dell Forums:
For the 3024/3048/5012 products:

1. Connect to the switch via the console port and manually reboot the switch
2. As soon as power is applied, press and hold the ESC key
3. At the command prompt, type “EmergencyPasswordReset” (case-sensitive without the quotation marks)
4. At the confirm (Y/N) prompt, type X
5. If done properly, you will receive a message stating that the password has been disabled
6. Type G and hit enter to reboot the switch

The switch will reboot with the password disabled.
This saved us in a pinch. Just goes to show that Physical Security is still the first and most important security.

Police clearance

2010 March 21
Comments Off
Posted by shirker2006

3620124648_a9fc028b621Для некоторых документов нам понадобится так называемый полис клиренс

Получаем Филиппинские права

2010 March 21
Comments Off

lto_logo

LTO (Land Transportation Office) – что-то типа нашего ГИБДД.   Офф сайт  – http://www.lto.gov.ph/ – куча полезной информации и (главное) ценники:)

Итак, по правилам, переданым мне словесно, иностранец может пользоваться своими водительскими правами на Филиппинах. Однако срок этот ограничен 3 месяцами. На самом деле никто не будет проверять ваш паспорт, на тему – “когда вы прилетели?”. Тем не менее каждый раз вопросы и каждый раз надо объяснять, что вы тут недавно и т.д. И все равно будут желающие забрать у вас права. В Себу как правило проверяют документы на мобильных чекпойнтах по ночам.

Первый совет – сразу сделайте фотографии 2х2 и 1х1 дюйма на все случаи. Чем больше тем лучше. Стоит один пакет с 40шт около 80 песо.

Что необходимо чтобы получить новые права:

  • Паспорт с действующей визой 5 мес (что в принципе делает возможным получение прав только резидентам и владельцев рабочей визы).
  • Умение читать и понимать английский или тагалог
  • Медицинский сертификат (делается очень просто)
  • 1 мес обученя в школе (можно заплатить и не ходить)

Чтобы начать процессинг, просто идем в офис ЛТО. Если все документы в порядке, но вы не очень уверены – можно обратиться к так называемым фиксерам. Они крутятся вокруг офиса. За небольшую плату они вам помогут

Однако более простой способ – конвертировать уже имеющиеся российские права. в непрофессиональные:

  • Перевод, заверенный в российском посольстве. (посольство в Маниле. Однако в Себу есть российский консул Гарсия. Перевод можно сделать через нее. Офис рядом с Аялой. Очень приятная женщина)
  • Драг-тест. Делается тут же, рядом с ЛТО. За 15 минут
  • Ну и паспорт с визой. с действующей любой визой. Вы должны быть тут не меньше (боюсь соврать) месяца.
  • ну и ксерокопии всего + фотографии

Если обратиться к фиксерам – это будет стоить 3 тыс песо. около того. но зато не надо стоять в очередях. Хотя советую сэкономить)

Далее – получам про. Немного про рестрикшены (категории). Они не соответствуют нашим:

  1. MOTORCYCLES/MOTORIZED TRICYCLES (Ну думаю тут все понятно -)
  2. VEHICLE UP TO 4500 KGS G V W (Авто с МЕХАНИЧЕСКОЙ коробкой до 4,5 Т. Типа нашего “B”. Однако может быть и пассажирским автобусом)
  3. VEHICLE ABOVE 4500 KGS G V W (Опять же только Механическая КПП. Типа наших “С” и “D” в одном флаконе)
  4. AUTOMATIC CLUTCH UP TO 4500 KGS G V W (Очень странная категория. Короче автомат КПП до 4.5Т)
  5. AUTOMATIC CLUTCH ABOVE 4500 KGS G V W (Ну и соответственно…  Я когда-то работал на ЛИАЗ-5256 – в аккурат для него)
  6. ARTICULATED VEHICLE 1600 KGS G V W & BELOW (тягач с полуприцепом  – Наше “Е”)
  7. ARTICULATED VEHICLE 1601 UP TO 4500KGS G V W
  8. ARTICULATED VEHICLE 4501 KGS AND ABUVE G V W

Для получения профессиональных прав нам понадобятся:

  • Наши новые филиппинские непрофессиональные права. Требуется наличие прав 5 мес – но мы поясним, что мы конвертировали наши заграничные
  • Дополнительная медицинская бумажка. Стоит 100 песо. Берем там же где прежде проходили драг-тест
  • Police clearance.
  • TIN number. Берется после полис клиренса в BIR офисе. Ну если нет желания заморачиваться – около ЛТО фиксеры возьмут 250 песо и за один день это будет готово. Долько не забудьте фото 1х1
  • копии паспорта и фотографии

Но придется сдавать экзамен. Письменно – 60 вопросов. Ответы на последнем листке. однако около 1500 песо – и вам дадут листок уже с отмеченными кружками. Останется только раскрасить. (что-то очень напоминает – “…жми номер вопроса и двойку. два раза двойку. и так 20 раз…” )

Поиск файлов с помощью find

2010 March 19
Comments Off
Posted by shirker2006

http://www.opennet.ru/docs/RUS/linux_base/node149.html

Используйте утилиту find для поиска файлов в дереве каталогов по имени файла. Укажите имя дерева каталогов для поиска, а затем, с помощью опции `-name’ – имя нужного Вам файла.

Чтобы увидеть список всех файлов системы, которые называются `top’, наберите:

$ find / -name top [Enter]

Эта команда проведет поиск во всех каталогах, куда Вам разрешен доступ; если Вы не имеете прав прочесть содержимое каталога, find сообщить, что поиск в данном каталоге Вам запрещен.

Опция `-name’ различает прописные и строчные буквы; чтобы использовать поиск без этих различий, воспользуйтесь опцией `-iname’.

Чтобы увидеть список всех файлов системы, которые называются `top’, без учета регистра символов, наберите:

$ find / -iname top [Enter]

Эта команда найдет все файлы, название которых состоит из букв `top’ – включая `Top’, `top’, и `TOP’.

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

Чтобы получить список файлов системы, имена которых начинаются с букв `top’, введите:

$ find / -name 'top*' [Enter]

Чтобы получить список файлов системы, имена которых начинаются с букв `top’, за которыми следуют еще три символа, введите:

$ find / -name 'top???' [Enter]

Чтобы получить список файлов системы, имена которых начинаются с букв `top’, за которыми следуют пять и более символов, введите:

$ find / -name 'top?????*' [Enter]

Чтобы увидеть все файлы с расширением `.tex’в Вашем рабочем каталоге, независимо от их написания, введите:

$ find ~ -iname '*.tex' [Enter]

Чтобы увидеть все файлы в каталоге `/usr/share’, содержащие в имени слово `farm’, введите:

$ find /usr/share -name '*farm*' [Enter]

Используйте `-regex’ вместо `-name’ для поиска файлов, имена которых удовлетворяют регулярному выражению, или образцу, описывающему несколько строк.

Чтобы увидеть все файлы в текущем каталоге, имена которых содержат строку `net’ или `comm’, наберите:

   $ find . -regex '.*\(net\|comm\).*' [Enter]

Примечание: Опция `-regex’ совпадает с полным именем файла относительно указанного каталога, а не с отдельным именем файла.

Чтобы найти файлы определенного размера, используйте опцию `-size’, указав после нее требуемый размер файла. Размер файла может быть задан в трех различных формах: если перед ним указан знак плюс (`+’), ищутся все файлы, большие, чем указанный размер; если указан знак минус (`-’), ищутся все файлы, меньшие, чем указанный размер; если префикс не указан, ищутся файлы точно указанного размера. (Единица измерения – блок 512 байт; символ `k’ после размера указывает килобайты, символ `b’ – байты.)

Чтобы вывести список файлов в каталоге `/usr/local’, размер которых больше 10,000 килобайт, введите:

$ find /usr/local -size +10000k [Enter]

Чтобы вывести список файлов в домашнем каталоге, размер которых меньше 300 байт, введите:

$ find ~ -size -300b [Enter]

Чтобы вывести список файлов системы, размер которых составляет 42 блока по 512 байт, наберите:

$ find / -size 42 [Enter]

Используйте опцию `-empty’ для поиска пустых файлов – т.е. файлов с размером 0 байт. Это полезно для поиска и удаления ненужных файлов.

Чтобы найти все пустые файлы в Вашем домашнем каталоге, введите:

$ find ~ -empty [Enter]

Чтобы найти файлы, модифицированные в определенное время, используйте команду find с опциями `-mtime’ или `-mmin’; аргумент опции `-mtime’ определяет количество прошедших суток (24 часа), а аргумент `-mmin’ – количество прошедших минут.

Чтобы вывести все файлы в каталоге `/usr/local’, модифицированные точно 24 часа назад, введите:

$ find /usr/local -mtime 1 [Enter]

Чтобы вывести все файлы в каталоге `/usr’, модифицированные 5 минут назад, введите:

$ find /usr -mmin 5 [Enter]

Если Вы хотите указать промежуток времени, поставьте перед числом либо знак плюс (`+’), определяя большее или равное аргументу время, или знак минус (`-’), определяя время, меньшее или равное аргументу.

Чтобы вывести все файлы в каталоге `/usr/local’, модифицированные в течение последних 24 часов, введите:

$ find /usr/local -mtime -1 [Enter]

Опция `-daystart’ определяет отсчет времени с момента начала текущих суток.

Чтобы вывести все файлы в Вашем домашнем каталоге, модифицированные вчера, введите:

$ find ~ -mtime 1 -daystart [Enter]

Чтобы вывести все файлы в каталоге `/usr’, модифицированные в течение года, введите:

$ find /usr -mtime +356 -daystart [Enter]

Чтобы вывести все файлы в Вашем домашнем каталоге, модифицированные в период от 2 до 4 дней тому назад, наберите:

$ find ~ -mtime 2 -mtime -4 -daystart [Enter]

Чтобы найти файлы, которые новее некоторого файла, введите его имя в качестве аргумента опции `-newer’.

Чтобы вывести все файлы в каталоге `/etc’, которые новее файла `/etc/motd’, введите:

$ find /etc -newer /etc/motd [Enter]

Чтобы найти все файлы новее определенной даты, используйте следующий трюк: создайте временный файл в каталоге `/tmp’ и установите дату его модификации на требуемую с помощью touch, а затем поределите его как аргумент для `-newer’.

Чтобы вывести все файлы в Вашем домашнем каталоге, модифицированные после 4 мая текущего года, введите:

   $ touch -t 05040000 /tmp/timestamp [Enter]
   $ find ~ -newer /tmp/timestamp [Enter]

Чтобы найти файлы, принадлежащие определенному пользователю, укажите имя пользователя в качестве агрумента опции `-user’. Например, для поиска всех файлов в каталоге `/usr/local/fonts’, принадлежащих пользователю warwick, наберите:

$ find /usr/local/fonts -user warwick [Enter]

Опция `-group’ подобным образом определяет файлы, принадлежащие некоторой группе пользователей.

Чтобы вывести список файлов в каталоге `/dev’, принадлежащих группе audio, введите:

$ find /dev -group audio [Enter]

Вы можете использовать команду find для выполнения других команд над найденными файлами, указав требуемые команды в качестве аргуентов опции `-exec’. Если Вы используететв команде строку `”’, эта строка в команде будет заменена именем текущего найденного файла. Окончание команды помечается строкой `’;”.

Чтобы найти все файлы в каталоге ` /html/’ с расширением `.html’, и вывести строки из этих файлов, содержащие слово `organic’, введите:

$ find ~/html/ -name '*.html' -exec grep organic '{}' ';' [Enter]

Чтобы ввести подтверждение выполнения команды для файла, найденного find, используйте ключ `-ok’ вместо `-exec’.

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

$ find ~ -used +365 -ok rm '{}' ';' [Enter]

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

Чтобы вывести список файлов в Вашем домашнем каталоге, имена которых начинаются со строки `top’, и которые новее файла `/etc/motd’, введите:

$ find ~ -name 'top*' -newer /etc/motd [Enter]

Чтобы сжать все файлы в Вашем домашнем каталоге, размер которых превышает 2 Mb, и которые еще не сжаты с помощью gzip (не имеют расширения `.gz’), введите:

$ find ~ -size +2000000c -regex '.*[^gz]' -exec gzip '{}' ';' [Enter]

Чтобы найти наибольший файл в каталоге, используйте команду ls с опцией `-S’, которая сортирует файлы в нисходящем порядке по размеру (обычно ls выводит список файлов по алфавиту). Добавьте опцию `-l’, чтобы вывести размер и другие атрибуты файла.Пример:

$ ls -lS [Enter]

Чтобы вывести оглавление каталога, начав с файлов наименьшего размера, используйте ls с ключами `-S’ и `-r’, которые сортируют вывод в обратном порядке.Пример:

$ ls -lSr [Enter]

Чтобы вывести список каталогов, отсортированных по размеру – то есть размеру всех содержащихся в них файлов – используйте du и sort. Команда du выводит список каталогов в восходящем порядке, начиная с самого маленького; опция `-S’ помещает при выводе в первую колонку размер каталога в килобайтах. Укажите требуемое дерево каталогов в качестве аргумента du и перенаправьте вывод в команду sort с ключом `-n’, которая отсортирует список по числам.

Чтобы вывести список подкаталогов в текущем дереве каталогов, отсортированный по размеру, введите:

$ du -S . sort -n [Enter]|

Если Вам нужно, чтобы первыми были указаны самые большие каталоги, используйте ключ `-r’:

$ du -S . sort -nr [Enter]|

Чтобы быстро определить количество файлов в каталоге, используйте ls и перенаправьте вывод в команду `wc -l’, которая выволит количество строк, пришедших на ее вход.

Для вывода общего количества файлов в текущем каталоге введите:

   $ ls | wc -l [RET]
   19
   $

Общее количество файлов – 19.

Поскольку ls по умолчанию не показывает скрытые файлы, приведенная выше команда не будет их учитывать. Опция `-A’ для ls позволит посчитать обычные и скрытые файлы:

   $ ls -A | wc -l [RET]
   81
   $

Чтобы посчитать количество файлов во всем дереве каталогов, а не только в отдельном каталоге, используйте find вместо ls, и укажите специальный ключ для find – строку `
! -type d’, чтобы исключить вывод и подсчет каталогов.

Чтобы вывести количество файлов в дереве `/usr/share’, введите:

$ find /usr/share \! -type d wc -l [Enter]|

Чтобы вывести количество файлов и каталогов в дереве `/usr/share’, введите:

$ find /usr/share wc -l [Enter]|

Чтобы вывести количество каталогов в дереве `/usr/share’, введите:

$ find /usr/share \! -type f wc -l [Enter]|

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

Чтобы определить, установлен ли в Вашей системе perl и где он расположен, введите:

   $ which perl [RET]
   /usr/bin/perl

Филиппины

2010 March 19
Comments Off
Posted by shirker2006

Итак! Есть идея начать публикацию об этой стране. Но малость лень, и недостаточно времени, да и опыта…

Я полагаю, что многие знают, что Филиппины располагаются на островах, причем на одноименных. Для европейцев эти острова были открыты самим великим Магелланом. Это было его последнее открытие, потому, как великий мореплаватель нашел здесь свою гибель в схватке с местными племенами. Однако дело колонизации было начато, и вскоре испанцы заселились на острова, построили крепости и взяли власть в свои руки. Так началась испанская эпоха Филиппин.

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

<продолжение предположительно следует>