Binding Multiple IP Addresses on the Same Network Interface

Posted by 4Aiur on 01/13/2012 in MacOSX with Comments closed |

Binding Multiple IP Addresses on the Same Network Interface

Add new address

sudo ifconfig en1 alias netmask
sudo ifconfig en1 alias netmask
sudo ifconfig en1 alias netmask
sudo ifconfig lo0 alias

Remove alias address

sudo ifconfig en1 remove netmask
sudo ifconfig en1 netmask delete
sudo ifconfig en1 netmask -alias
sudo ifconfig lo0 -alias


Installing Logster on CentOS

Posted by 4Aiur on 01/10/2012 in SysAdmin with Comments closed |

Installing Logster on CentOS

Install EPEL repository

sudo rpm -Uvh
yum update # This takes quite a while for a fresh install

Setting locale

cat >> ~/.bash_profile 

Install Dependence

yum -y install logcheck

logcheck dependencies:

  • liblockfile
  • lockfile-progs
  • perl-IPC-Signal
  • perl-Proc-WaitStat
  • perl-mime-construct

Install logster

git clone git://
cd logster
make install

dry run

/usr/sbin/logster --output=stdout SampleLogster /var/log/httpd/access_log

Add crontab

crontab -e
* * * * * /usr/sbin/logster -p blog_4aiur_net --output=graphite --graphite-host=localhost:2003 SampleLogster /var/log/httpd/blog.4aiur.net_access_log >/dev/null 2>&1


Installing and Configuring Graphite on CentOS

Posted by 4Aiur on 01/10/2012 in SysAdmin with Comments closed |

Installing and Configuring Graphite on CentOS

Install EPEL repository

sudo rpm -Uvh
sudo yum -y update # This takes quite a while for a fresh install


wget -r -l1 --no-parent -A "epel*.rpm"
sudo yum -y --nogpgcheck localinstall */pub/epel/6/x86_64/epel-*.rpm

Install Dependences

sudo yum -y install gcc.x86_64 git.x86_64 python-devel pyOpenSSL \
    python-memcached bitmap bitmap-fonts python-crypto zope pycairo \
    mod_python python-ldap Django django-tagging python-sqlite2

Install Python package management software

sudo yum -y install python-pip.noarch

Install Graphite

  • carbon

    a Twisted daemon that listens for time-series data

  • whisper

    a simple database library for storing time-series data (similar in design to RRD)

  • graphite-web

    a Django webapp that renders graphs on-demand using Cairo

sudo pip-python install whisper carbon graphite-web 

Configure graphite

cd /opt/graphite/conf
sudo rename .conf.example .conf *
cd /opt/graphite/webapp/graphite
sudo python syncdb
sudo chown -R apache:apache /opt/graphite/storage/

Start the data collection daemon carbon-cache

cd /opt/graphite/bin
sudo ./ start

Configure Apache VirtualHost

edit /etc/httpd/conf/httpd.conf

    DocumentRoot "/opt/graphite/webapp"
    CustomLog /var/log/httpd/graphite.4aiur.net_access_log combined

        SetHandler python-program
        PythonPath "['/opt/graphite/webapp'] + ['/usr/lib/python/site-packages/'] + sys.path"
        PythonHandler django.core.handlers.modpython
        SetEnv DJANGO_SETTINGS_MODULE graphite.settings
        PythonDebug Off
        PythonAutoReload Off
        SetHandler None
        SetHandler None
    alias /media/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/

Test insert data to graphite

run test

python /opt/graphite/examples/ source code

"""Copyright 2008 Orbitz WorldWide

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License."""

import sys
import time
import os
import platform
import subprocess
from socket import socket


delay = 60
if len(sys.argv) > 1:
  delay = int( sys.argv[1] )

def get_loadavg():
  # For more details, "man proc" and "man uptime"
  if platform.system() == "Linux":
    return open('/proc/loadavg').read().strip().split()[:3]
    command = "uptime"
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    os.waitpid(, 0)
    output =',', ' ').strip().split()
    length = len(output)
    return output[length - 3:length]

sock = socket()
  sock.connect( (CARBON_SERVER,CARBON_PORT) )
  print "Couldn't connect to %(server)s on port %(port)d, is running?" % { 'server':CARBON_SERVER, 'port':CARBON_PORT }

while True:
  now = int( time.time() )
  lines = []
  #We're gonna report all three loadavg values
  loadavg = get_loadavg()
  lines.append("system.loadavg_1min %s %d" % (loadavg[0],now))
  lines.append("system.loadavg_5min %s %d" % (loadavg[1],now))
  lines.append("system.loadavg_15min %s %d" % (loadavg[2],now))
  message = '\n'.join(lines) + '\n' #all lines must end in a newline
  print "sending message\n"
  print '-' * 80
  print message

View graphite data

sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT
sudo service httpd restart

goto your graphite site

Delete graphite data

cd /opt/graphite/storage/whisper
rm your_data.wsp

Some wonderful Graphite dashboards


JMX monitoring

Posted by 4Aiur on 01/09/2012 in Default with Comments closed |

JMX monitoring


java app -> jmxagent ->
                         jmxtrans -> jmx_output.log -> -> send mail
java app -> jmxagent ->

Configuration jmx agent with authentication

JMX dynamically allocated random port, and it will bind the port at internal address.
If you connecting jmx through firewall or your servers on Amazon EC2,
maybe can’t connect to the jmx agent, So need to do some prepare.

add jmx agent parameter in your java startup script

cmd[0]='curl -s 2>/dev/null | tr -d "\n"'
cmd[1]='curl -s 2>/dev/null'
for ((x=0; x

configuration jmx authentication

cat > /opt/app/conf/jmxremote.access  /opt/app/conf/jmxremote.password 

build JMXAgent.class to jmx-agent.jar

package example.rmi.agent;

import java.rmi.registry.LocateRegistry;
import java.util.HashMap;


 * This class is used for the resolve the
 * "Connecting Through Firewall Using JMX" issue.
 * @author root
public class JMXAgent {

    private static int _rmiRegistryPort=3000;

    public static void premain(String agentArgs) throws IOException {

        // Ensure cryptographically strong random number generator used
        // to choose the object number - see java.rmi.server.ObjID
        System.setProperty("java.rmi.server.randomIDs", "true");

        // Start an RMI registry on port specified by example.rmi.agent.port
        // (default 3000).
        final int port = Integer.parseInt(System.getProperty(
                "yottaa.rmi.agent.port", String.valueOf(_rmiRegistryPort)));

        System.out.println("Create RMI registry on port " + port);

        // Retrieve the PlatformMBeanServer.
        System.out.println("Get the platform's MBean server");
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        // Environment map.
        System.out.println("Initialize the environment map");
        HashMap env = new HashMap();

        // This where we would enable security - left out of this
        // for the sake of the example....

        // Create an RMI connector server.
        // As specified in the JMXServiceURL the RMIServer stub will be
        // registered in the RMI registry running in the local host on
        // port 3000 with the name "jmxrmi". This is the same name the
        // out-of-the-box management agent uses to register the RMIServer
        // stub too.
        // The port specified in "service:jmx:rmi://"+hostname+":"+port
        // is the second port, where RMI connection objects will be exported.
        // Here we use the same port as that we choose for the RMI registry.
        // The port for the RMI registry is specified in the second part
        // of the URL, in "rmi://"+hostname+":"+port
        System.out.println("Create an RMI connector server");
        final String hostname = InetAddress.getLocalHost().getHostName();
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + hostname
                + ":" + port + "/jndi/rmi://" + hostname + ":" + port
                + "/jmxrmi");

        // Now create the server from the JMXServiceURL
        JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);

        // Start the RMI connector server.
        System.out.println("Start the RMI connector server on port " + port);


Install jmxtrans on your alert server

rpm -Uvh
ln -s /usr/java/jdk1.6.0_27/bin/jps /usr/bin/jps

Configuration jmxtrans

cat > /var/lib/jmxtrans/monitoring.json 

Running Jmx Transformer

service jmxtrans start
# or run jmxtrans manually
cd /usr/share/jmxtrans/
/usr/share/jmxtrans/ start /var/lib/jmxtrans/monitoring.json
/usr/share/jmxtrans/ stop /var/lib/jmxtrans/monitoring.json

View jmxtrans log

cd /var/log/jmxtrans
tailf jmxtrans.log

Alert script thresholds config

cat > thresholds.conf 

Alert script

cat > /opt/ /dev/null | head -${max_line} | \
    awk -v Now=$now -v Expire=$expire '
    # configuration
    # #parttern expression value
    # HeapMemoryUsage_used Maximum 2500000000
    # HeapMemoryUsage_committed Minimum 6000000000
    while (getline = Values[Parttern]) {
                    return Hit=1
            } else if (Expressions[Parttern] == "Minimum") {
                if (Value = Now) {
            scanner(Attr, Value)
            if (Hit == 1) {
        } else {

if [[ ! -z $message ]]; then
    send_mail "$message"
logger "done."
chmod +x /opt/

Add script into crontab

crontab -l > tmp.cron
echo "* * * * * /opt/ >> /var/log/jmxtrans/alert.log 2>&1" >> tmp.cron
crontab tmp.cron
rm -f tmp.cron


Suppressing paramiko log

Posted by 4Aiur on 12/26/2011 in Python with Comments closed |

Suppressing paramiko log

Backup paramiko source file.

cd /usr/local/lib/python2.7/site-packages/
cp -p paramiko/{,.bak}

Modify paramiko/

diff paramiko/{,.bak}

         return True

Set logger name "suppress" in your code.

self.client = SSHClient()

Tags: , ,

Zenoss Core setup guide

Posted by 4Aiur on 12/16/2011 in SysAdmin with Comments closed |

Zenoss Core setup guide

Zenoss Core is a powerful monitoring system, and it is a OpenSource software.

Install Zenoss Core
Install ZenPacks
Setup snmp and snmpd config
Add user command
Add a single device
Add custom Device Class
Custom new class properties
Setup Processes
Custom Zenoss reports

Install Zenoss Core

Before you install:

1) Run the Yellowdog Updater, Modified (YUM), which you will use to install Zenoss. To run YUM, enter this command:

# yum -y install mysql-server.x86_64 mysql-devel.x86_64 net-snmp.x86_64 \
        net-snmp-utils.x86_64 gmp.x86_64 libgomp.x86_64 libgcj.x86_64 \
        liberation-fonts.noarch sysstat.x86_64 fping.x86_64

2) Download the Zenoss installation files.

# mkdir /opt/package
# cd /opt/package
# wget ""

3) If you have just installed MySQL, then use the following command to add MySQL into the startup sequence:

# /sbin/chkconfig --add mysqld

4) Enter the following command to display current run levels:

# /sbin/chkconfig --list mysqld

5) If the system responds with something similar to:

mysqld 0:off 1:off 2:off 3:off 4:off 5:off 6:off

then enter the following command to adjust run levels:

# /sbin/chkconfig --level 2345 mysqld on

6) Restart MySQL and set the password.

    Do not add a space between the single quotes in the following commands.

# /etc/init.d/mysqld restart
# /usr/bin/mysql_secure_installation
# /usr/bin/mysqladmin -u root password ''
# /usr/bin/mysqladmin -u root -h localhost password ''

    Initially, the MySQL password must be blank so that Zenoss can correctly create the database. After you have installed and started Zenoss, you can change this password.

Install the Software

Follow these steps to install Zenoss for Red Hat Enterprise Linux 5 or CentOS 5.

1) Enter one of the following commands to install the Zenoss RPM.

# rpm -ivh zenoss-3.2.0.el5.x86_64.rpm

2) If MySQL is running on a different server, or has a different root user password, edit the /opt/zenoss/bin/ zenoss_init_pre file and adjust the MYSQLHOST, MYSQLROOTUSER, and MYSQLROOTPASSWD values.

3) Enter this command to start Zenoss.

# service zenoss start

    This step may take several minutes.

Install ZenPacks

Setup snmp and snmpd config

add snmp.conf to zenoss server /etc/snmp/snmp.conf.
snmp.conf example:

defversion 3
defsecurityname yourname
defsecuritylevel authNoPriv
defauthtype MD5
defauthpassphrase yourpassword

add snmpd.conf to client /etc/snmp/snmpd.conf.
snmpd.conf example:

createUser yourname MD5 "yourlonglonglonglongpassword" DES
rouser yourname auth -V yourview

#                     sec.model
group monitorGroup    usm         yourname

#       name          incl/excl    subtree         mask(optional)
view    yourview    included     .
view    yourview    included     .

#       group         context sec.model sec.level prefix read       write  notif
access  monitorGroup  ""      any       auth      exact  yourview none none

syslocation Undefined
syscontact NOC 

# "Pass-through" MIB extension command
pass . /usr/share/doc/net-snmp-

Add user command for debug snmp setting

  1. Go to http://yourhost:8080/zport/dmd/dataRootManage
  2. Click "Add User Command"
  3. Input value
    Name: snmpwalkV3
    Description: snmpwalk using version 3
    Command: snmpwalk -${device/zSnmpVer} -l authNoPriv -u ${device/zSnmpSecurityName} -A ${device/zSnmpAuthPassword} -a ${device/zSnmpAuthType} ${here/manageIp} system

Add a single device

  • Go to http://yourhost:8080/zport/dmd/itinfrastructure
  • Click "Add a Single Device"
  • Input items
  • Click "Zenoss Server", and Click left "Configuration Properties" to edit the server’s properties
    • zSnmpVer: v3
    • zSnmpSecurityName: yourname
    • zSnmpAuthPassword: yourlonglonglonglongpassword
    • zSnmpAuthType: MD5
  • Click "Commands –> snmpwalkV3" verify server and client snmp configuration
  • Click "Actions –> Model Device"

Add custom Device Class

Custom new class properties


using zenoss portal

using zenoss manage and zendmd

1) Login to Zenoss as "admin" and go to the URL http://yourhost:8080/zport/dmd/Devices/manage
2) Click left "your new class name", and click top "Properties"
3) To add a new property, enter a name, type and value for the new property and click the "Add" button.
Name: zCollectorPlugins
Type: lines


  • zenoss.snmp.NewDeviceMap
  • zenoss.snmp.DeviceMap
  • zenoss.snmp.InterfaceMap
  • zenoss.snmp.RouteMap
  • zenoss.snmp.IpServiceMap
  • zenoss.snmp.HRFileSystemMap
  • zenoss.snmp.HRSWInstalledMap
  • zenoss.snmp.HRSWRunMap
  • zenoss.snmp.CpuMap

Name: zDeviceTemplates
Type: lines


  • b_fping
  • Device
  • FileSystem

Name: zIcon
Type: string
Value: /zport/dmd/img/icons/server.png
Name: zSnmpAuthType
Type: string
Value: MD5
Name: zSnmpVer
Type: string
Value: v3

4) Login zendmd, change default snmp auth password

# su - zenoss
$ zendmd
>>> dmd.Devices.yourclassname.zSnmpAuthPassword = 'yourlonglonglonglongpassword'
>>> commit()

Add Custom Schema

Setup Processes

Zenoss API

Zenoss have jsonapi and xmlrpc interface, you can using it’s API to integrate your management system.
jsonapi code demo:

def add_device(self, deviceName, deviceClass, title,
                productionState=1000, model=False):
    data = dict(deviceName=deviceName, deviceClass=deviceClass,
                title=title, productionState=productionState, model=model)
    return self._router_request('DeviceRouter', 'addDevice', [data])

xmlrpc code demo:

def add_device(self, deviceName, devicePath, tag):
    url = 'http://%s:%s@%s/zport/dmd/DeviceLoader' % (self.username,
            self.password, self.zenoss_host)
    serv = ServerProxy(url)
    serv.loadDevice(deviceName, devicePath, tag)

Custom Zenoss Reports

Column syntax

buildin command:


python command:


custom python script:


Goto http://yourhost:8080/zport/dmd/Devices/manage first.


Input script name getMemUtil(), and input content like this:

total_memory = context.hw.totalMemory
mem_avail_real = context.getRRDValue('memAvailReal_memAvailReal')
mem_cached = context.getRRDValue('memCached_memCached')
if total_memory and mem_avail_real and mem_cached:
    print '%.2f%%' % ((total_memory - (mem_avail_real + mem_cached) * 1024) / total_memory * 100)
return printed

Send report email

cat  $ZENHOME/scripts/
$ZENHOME/bin/reportmail \
--user=username \
--passwd= yourlonglonglonglongpassword \
--from="" \
--address="" \
--address="" \
--subject="Zenoss: System Summary Daily Report" \

Add it into crontab

0 20 * * * /opt/zenoss/scripts/ 2>&1 >/dev/null


Tags: , ,


Posted by 4Aiur on 06/10/2011 in SysAdmin with Comments closed |





yum -y install OpenIPMI.x86_64 OpenIPMI-tools.x86_64 OpenIPMI-libs.x86_64 ipmitool.x86_64

添加ipmi module

modprobe ipmi_si 
modprobe ipmi_devintf
modprobe ipmi_msghandler


lsmod | grep -i ipmi
ipmi_si                77900  0 
ipmi_devintf           44688  0 
ipmi_msghandler        73176  2 ipmi_si,ipmi_devintf


ipmitool -I open sel list
   1 | 09/02/2010 | 04:10:26 | OEM #0x02 | 
   2 | 09/02/2010 | 04:10:29 | OEM #0x02 | 
   3 | 03/23/2011 | 16:02:59 | OEM #0x02 | 
   4 | 03/23/2011 | 16:03:02 | OEM #0x02 | 


ipmitool -I open sel clear



Posted by 4Aiur on 04/06/2011 in Default with Comments closed |



Downloading update from
Download failed.: Operation timed out after 300 seconds with 1340586 bytes received
Installation Failed


# wget
--2011-04-06 15:01:31--
Connecting to||:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/zip]
Saving to: `'
    [                                        ] 17,114      3.70K/s



# wget
# vi /etc/hosts


Downloading update from
Unpacking the update…
Verifying the unpacked files…
Installing the latest version…
Upgrading database…
WordPress updated successfully
Go to Dashboard




Posted by 4Aiur on 03/16/2011 in SysAdmin with Comments closed |




  1. 添加监控设备

    1. 首先需要在被监控的设备上安装与配置snmp agent,Linux平台请参考Linux安装与配置Snmpd,OpenSolaris参考OpenSolaris net-snmp install script,windows安装配置snmp agent方法

      检查是否存在SNMP Service,需要将此服务启动。我的电脑-管理-服务-SNMP Ssrvice.
      单击属性-安全,添加发送身份验证陷阱。添加在cacti中的SNMP Community,在下面添加监控端的IP地址

    2. 添加设备
      登陆Cacti后点击面板左侧的devices后点击右侧面板的Add,之后填写Description, Hostname, Host Template(Linux与Solaris使用ucd/net SNMP Host,Windows使用windows2000/xp Host), 其他部分可以使用自己的值来填写"SNMP Community"或者保持不变。配置完成后点击Create增加此设备。
      在创建完毕后出现的页面中点下Query Verbose 来测试下snmp数据抓取是否正常。

      Cacti Data Query Debug

    3. 添加图像
      点击页面中的"Create Graphs for this Host"

    4. 设置图像数
      点击面板左侧的"Graph Trees" –> "Add",输入name后"Create" –> "Save"

    5. 把设备添加到心的图像树中

      Cacti Place on a Tree

      "Place on a Tree" –> "Go" –> "Continue",到这里设备的配置已经完成,可以点击导航栏的graphs查看新增加设备的各种监控图像,下面是我Cacti监控数据的两个截图

      Linux Traffic
      Linux Load Average

  2. 权限配置

    1. 增加新用户
      "User Management" –> "Add",填写相应项"User Name", "Full Name", "Password", "Enabled Determines if user is able to login."这里选中"Enabled"
      权限规则"Realm Permissions"处选中"View Graphs", "Export Data"即可
      Cacti Tree Permission
    2. 权限设置
      Tree Permissions中"Default Policy"使用"Deny",并增加新增的图像树如下图,之后"Save"
      把"Graph Permissions (By Graph)", "Graph Permissions (By Device)", "Graph Permissions (By Graph Template)"后面的"Policy"修改为"Allow",之后"Save"。

Tags: ,


Posted by 4Aiur on 03/16/2011 in Linux with Comments closed |



Script on CentOS

# Install snmp and agent
yum install -y net-snmp net-snmp-utils

# Backup snmpd.conf
mv /etc/snmp/snmpd.conf /etc/snmp/snmpd.conf-date +%Y%m%d%H%M%S

# Write new snmpd config
cat > /etc/snmp/snmpd.conf  (configure /etc/snmp/snmp.local.conf)
disk / 20%

chkconfig snmpd on
/etc/init.d/snmpd restart

Script on Unbuntu

# Install snmp and agent
apt-get -y install snmpd snmp

# Modify snmpd listening ipaddress
sed -i 's/' /etc/default/snmpd

# Backup snmpd.conf
mv /etc/snmp/snmpd.conf /etc/snmp/snmpd.conf-date +%Y%m%d%H%M%S

# Write new snmpd config
cat > /etc/snmp/snmpd.conf  (configure /etc/snmp/snmp.local.conf)
disk / 20%
/etc/init.d/snmpd restart

Tags: ,

Copyright © 2010-2019 4Aiur All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from