Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Sunday, April 12, 2015

chkconfig run levels explained

PA runlevel is one of the modes that a Unix -based operating system will run in. Each runlevel has a certain number of services stopped or started, giving the user control over the behavior of the machine. Conventionally, seven runlevels exist, numbered from zero to six.

After the Linux kernel has booted, the init program reads the /etc/inittab file to determine the behavior for each runlevel. Unless the user specifies another value as a kernel boot parameter, the system will attempt to enter (start) the default runlevel.


Run Level

Mode

Action

0

Halt

Shuts down system

1

Single-User Mode

Does not configure network interfaces, start daemons, or allow non-root logins

2

Multi-User Mode

Does not configure network interfaces or start daemons.

3

Multi-User Mode with Networking

Starts the system normally.

4

Undefined

Not used/User-definable

5

X11

As runlevel 3 + display manager(X)

6

Reboot

Reboots the system
Most Linux servers lack a graphical user interface and therefore start in runlevel 3. Servers with a GUI and desktop Unix systems start runlevel 5. When a server is issued a reboot command, it enters runlevel 6.

Init scripts

Init (short for initialization) is the program on Unix and Unix-like systems that spawns all other processes. It runs as a daemon and typically has PID 1.
The /etc/inittab file is used to set the default run level for the system. This is the runlevel that a system will start up on upon reboot. The applications that are started by init are located in the /etc/rc.d folder. Within this directory there is a separate folder for each run level, eg rc0.d, rc1.d, and so on.

chkconfig

The chkconfig tool is used in Red Hat based systems (like CentOS) to control what services are started at which runlevels. Running the command chkconfig –list will display a list of services whether they are enabled or disabled for each runlevel.
 # chkconfig --list
filelimits 0:off 1:off 2:on 3:on 4:on 5:on 6:off
syslog 0:off 1:off 2:on 3:on 4:on 5:on 6:off
gpm 0:off 1:off 2:on 3:on 4:on 5:on 6:off
cpanel 0:off 1:off 2:off 3:on 4:on 5:on 6:off
kudzu 0:off 1:off 2:off 3:on 4:on 5:on 6:off
ntpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
netfs 0:off 1:off 2:off 3:on 4:on 5:on 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
netplugd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
rawdevices 0:off 1:off 2:off 3:on 4:on 5:on 6:off
ipchains 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iptables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
anacron 0:off 1:off 2:on 3:on 4:on 5:on 6:off
cups 0:off 1:off 2:on 3:on 4:on 5:on 6:off
xfs 0:off 1:off 2:on 3:on 4:on 5:on 6:off
xinetd 0:off 1:off 2:off 3:on 4:on 5:on 6:off
httpd 0:off 1:off 2:off 3:on 4:off 5:on 6:off

Single User mode is a mode that a multi-user system (like a Linux server) can be booted into the operating system as a superuser. Booting a system into this mode does not start networking, but can be used to make changes to any configuration files on the server. One of the most common usages for single-user mode is to change the root password for a server on which the current password is unknown.

Runlevels are an important part of the core of the Linux operating system. While not something the average administrator will work with on a daily basis, understanding runlevels gives the administrator another layer of control and flexibility over the servers they manage.

References

Sunday, April 5, 2015

How to install Jboss 5.1.0 GA on CentOS/RHEL

P
What is JBoss ? JBoss Application Server (or JBoss AS) is a free software/open-source Java EE-based application server. An important distinction for this class of software is that it not only implements a server that runs on Java, but it actually implements the Java EE part of Java. Because it is Java-based, the JBoss application server operates cross-platform: usable on any operating system that supports Java. JBoss AS was developed by JBoss, now a division of Red Hat.
This article will show you how to install and configure JBoss on CentOS 6.6.

What thing to do?


  1. Download and install Java Development Kit (JDK)
  2. Download and config JBoss 5.1.0 GA-jdk6
  3. Set JAVA_HOME and JBOSS_HOME as variables environment
  4. Config JBoss run as service (can start/stop/restart)
  5. Change password of JBoss Admin Console
  6. Set memory parameters for JBoss using JAVA_OPTS
  7. Configure JBoss to run on port 80

Download and install Java Development Kit (JDK)

It's recommended to use JDK 6 with JBoss 5.1.0 GA so to install JDK 6, please refer this post: How to install JDK 6 on CentOS

Download and config JBoss 5.1.0 GA-jdk6

You can download JBoss 5.1.0 GA at http://sourceforge.net/projects/jboss/files/JBoss/JBoss-5.1.0.GA. You should download jboss-5.1.0.GA-jdk6.zip, it's optimized for JDK6.

Create folder for JBoss
# mkdir /opt/server/

Move jboss-5.1.0.GA-jdk6.zip to newly created folder and unzip it
# mv jboss-5.1.0.GA-jdk6.zip /opt/server/
# cd /opt/server/
# unzip jboss-5.1.0.GA-jdk6.zip

Now your JBoss is located in /opt/server/jboss-5.1.0.GA, this is JBOSS_HOME which is set in next step for variables environment.

Set JAVA_HOME and JBOSS_HOME as variables environment

Add the following lines in .bashrc or .bash_profile
# vi ~/.bashrc

JAVA_HOME=/usr/java/latest
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH
JBOSS_HOME=/opt/server/jboss-5.1.0.GA
export JBOSS_HOME
Once finished, you have to log in current user again to verify that the JAVA_HOME and JBOSS_HOME are set correctly. This tutorial using root to config and run jboss therefore you have to log out and log in again with root account.
To verify variables set
# echo $JBOSS_HOME
# echo $JAVA_HOME

Output
/usr/java/latest
/opt/server/jboss-5.1.0.GA

Config JBoss run as service (can start/stop/restart)

JBoss 5.1.0 GA supports a script allow to run as service. Copy jboss_init_redhat.sh located in /opt/server/jboss-5.1.0.GA/bin paste it in etc/init.d and rename to jboss
# cp /opt/server/jboss-5.1.0.GA/bin/jboss_init_redhat.sh /etc/init.d/jboss
In jboss script, make the following changes:

Add lines 3,4 and 5
# description: JBoss Start Stop Restart
# processname: jboss
# chkconfig: 234 20 80

Line 21, Set the JBOSS_HOME to where we unzip JBoss:
JBOSS_HOME=${JBOSS_HOME:-"/opt/server/jboss-5.1.0.GA"}

Line 27. Set the JAVA_HOME to where we installed the JDK
JAVAPTH=${JAVAPTH:-"/usr/java/latest"}

Add line 33, which sets the JBOSS_HOST to 0.0.0.0, allowing JBoss to bind to any IP.
JBOSS_HOST="0.0.0.0"

There is complete jboss script after changed
#!/bin/sh
#
# description: JBoss Start Stop Restart
# processname: jboss
# chkconfig: 234 20 80
# $Id: jboss_init_redhat.sh 81068 2008-11-14 15:14:35Z dimitris@jboss.org $
#
# JBoss Control Script
#
# To use this script run it as root - it will switch to the specified user
#
# Here is a little (and extremely primitive) startup/shutdown script
# for RedHat systems. It assumes that JBoss lives in /usr/local/jboss,
# it's run by user 'jboss' and JDK binaries are in /usr/local/jdk/bin.
# All this can be changed in the script itself. 
#
# Either modify this script for your requirements or just ensure that
# the following variables are set correctly before calling the script.

#define where jboss is - this is the directory containing directories log, bin, conf etc
JBOSS_HOME=${JBOSS_HOME:-"/opt/server/jboss-5.1.0.GA"}

#define the user under which jboss will run, or use 'RUNASIS' to run as the current user
JBOSS_USER=${JBOSS_USER:-"root"}

#make sure java is in your path
JAVAPTH=${JAVAPTH:-"/usr/java/latest"}

#configuration to use, usually one of 'minimal', 'default', 'all'
JBOSS_CONF=${JBOSS_CONF:-"default"}

#if JBOSS_HOST specified, use -b to bind jboss services to that address
JBOSS_HOST="0.0.0.0"
JBOSS_BIND_ADDR=${JBOSS_HOST:+"-b $JBOSS_HOST"}


#define the classpath for the shutdown class
JBOSSCP=${JBOSSCP:-"$JBOSS_HOME/bin/shutdown.jar:$JBOSS_HOME/client/jnet.jar"}

#define the script to use to start jboss
JBOSSSH=${JBOSSSH:-"$JBOSS_HOME/bin/run.sh -c $JBOSS_CONF $JBOSS_BIND_ADDR"}

if [ "$JBOSS_USER" = "RUNASIS" ]; then
  SUBIT=""
else
  SUBIT="su - $JBOSS_USER -c "
fi

if [ -n "$JBOSS_CONSOLE" -a ! -d "$JBOSS_CONSOLE" ]; then
  # ensure the file exists
  touch $JBOSS_CONSOLE
  if [ ! -z "$SUBIT" ]; then
    chown $JBOSS_USER $JBOSS_CONSOLE
  fi 
fi

if [ -n "$JBOSS_CONSOLE" -a ! -f "$JBOSS_CONSOLE" ]; then
  echo "WARNING: location for saving console log invalid: $JBOSS_CONSOLE"
  echo "WARNING: ignoring it and using /dev/null"
  JBOSS_CONSOLE="/dev/null"
fi

#define what will be done with the console log
JBOSS_CONSOLE=${JBOSS_CONSOLE:-"/dev/null"}

JBOSS_CMD_START="cd $JBOSS_HOME/bin; $JBOSSSH"
JBOSS_CMD_STOP=${JBOSS_CMD_STOP:-"java -classpath $JBOSSCP org.jboss.Shutdown --shutdown"}

if [ -z "`echo $PATH | grep $JAVAPTH`" ]; then
  export PATH=$PATH:$JAVAPTH
fi

if [ ! -d "$JBOSS_HOME" ]; then
  echo JBOSS_HOME does not exist as a valid directory : $JBOSS_HOME
  exit 1
fi

echo JBOSS_CMD_START = $JBOSS_CMD_START

case "$1" in
start)
    cd $JBOSS_HOME/bin
    if [ -z "$SUBIT" ]; then
        eval $JBOSS_CMD_START >${JBOSS_CONSOLE} 2>&1 &
    else
        $SUBIT "$JBOSS_CMD_START >${JBOSS_CONSOLE} 2>&1 &" 
    fi
    ;;
stop)
    if [ -z "$SUBIT" ]; then
        $JBOSS_CMD_STOP
    else
        $SUBIT "$JBOSS_CMD_STOP"
    fi 
    ;;
restart)
    $0 stop
    $0 start
    ;;
*)
    echo "usage: $0 (start|stop|restart|help)"
esac

Now make jboss script executable
# chmod +x jboss

And make it run when every boot
# chkconfig jboss on

Check it
# chkconfig --list | grep jboss
jboss           0:off 1:off 2:on 3:on 4:on 5:on 6:off
By default, jboss script will be set at level 2345
Now you can start jboss as service
# service jboss start
JBOSS_CMD_START = cd /usr/share/jboss-5.1.0.GA/bin; /usr/share/jboss-5.1.0.GA/bin/run.sh -c default -b 0.0.0.0

Stop jboss
# service jboss stop
JBOSS_CMD_START = cd /usr/share/jboss-5.1.0.GA/bin; /usr/share/jboss-5.1.0.GA/bin/run.sh -c default -b 0.0.0.0  
Shutdown message has been posted to the server.  
Server shutdown may take a while - check logfiles for completion

Or restart
# service jboss restart

Make sure jboss has been started at http://localhost:8080 or http://yourIP:8080

Change password of JBoss Admin Console

The default user name and password for the JBoss Admin Console is admin/admin. To change the password, go to /usr/share/jboss-5.1.0.GA/server/default/conf/props and ddit the jmx-console-users.properties file as below
# A sample users.properties file for use with the UsersRolesLoginModule
admin=admin
Username is left and password is right. Change whatever you want

Set memory parameters for JBoss using JAVA_OPTS
You could set the memory parameters for JBoss using JAVA_OPTS. Edit .bashrc or .bash_profile where you set variables environment above
# Setup JBoss specific properties
JAVA_OPTS="-Dprogram.name=$PROGNAME $JAVA_OPTS"
JAVA_OPTS="$JAVA_OPTS -Xms128m -Xmx256m"
You should set this to whatever is appropriate to your server and application.

Configure JBoss to run on port 80

By default, JBoss uses port 8080, you could change this to others ports as you want.
Open file server.xml located in /opt/server/jboss-5.1.0.GA/server/default/deploy/jbossweb.sar
Find
<connector address="${jboss.bind.address}" connectiontimeout="20000" port="8080" protocol="HTTP/1.1" redirectport="8443">
</connector>
And change
<connector address="${jboss.bind.address}" connectiontimeout="20000" port="80" protocol="HTTP/1.1" redirectport="443">
</connector>
Now restart your JBoss to apply change
Another way, you don't need to change server.xml, just add the following to your IP tables
# iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080

and then restart iptables service
# service iptables restart
Done.

Reference

Wednesday, April 1, 2015

Synchronize the system clock to Network Time Protocol (NTP) in CentOS/RHEL

PThe Network Time Protocol daemon (ntpd) program is a Linux operating system daemon. It sets and maintains the system time of day in synchronism with time servers (Mills).

Install NTP Daemon

Open terminal and type:

# yum install ntp

Or

# up2date ntp

Configuration

Now you need to set ntp server to ntpd can synchronize your local date time to server's one. Configuration file located in /etc/ntp.conf

# vi /etc/ntp.conf

By default, ntpd uses these server to do its job

server 0.centos.pool.ntp.org
server 1.centos.pool.ntp.org
server 2.centos.pool.ntp.org
server 3.centos.pool.ntp.org

You can refer to http://www.pool.ntp.org/ and choose what server you want. After changes, save this file and start ntpd

Make ntpd run as service

By making ntpd run as service will make your PC's date time is synchronized every boot

# chkconfig ntpd on

Start ntpd

# service ntpd start

You can synchronize the system clock to an NTP server immediately with following command

# ntpdate pool.ntp.org

After synchronizing completed, check your date time again to make sure it worked

# date

Reference

Sunday, March 29, 2015

How to install JDK 6 on CentOS

P
This article today will show you how to download and install JDK 6 on CentOS through command line.
To download installer, just follow these commands
For x86 machine
[root@localhost phuongvu]# wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn/java/jdk/6u45-b06/jdk-6u45-linux-i586-rpm.bin
And x64 machine
[root@localhost phuongvu]# wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn/java/jdk/6u45-b06/jdk-6u45-linux-x64-rpm.bin
Now check whether it is installed
[root@localhost phuongvu]# ls
Desktop    Downloads                    Music     Public     Videos
Documents  jdk-6u45-linux-i586-rpm.bin  Pictures  Templates
Grant execute permission for it
[root@localhost phuongvu]# chmod +x jdk-6u45-linux-i586-rpm.bin
Now, just install
[root@localhost phuongvu]# ./jdk-6u45-linux-i586-rpm.bin
Output:
Unpacking...
Checksumming...
Extracting...
UnZipSFX 5.50 of 17 February 2002, by Info-ZIP (Zip-Bugs@lists.wku.edu).
  inflating: jdk-6u45-linux-i586.rpm
  inflating: sun-javadb-common-10.6.2-1.1.i386.rpm
  inflating: sun-javadb-core-10.6.2-1.1.i386.rpm
  inflating: sun-javadb-client-10.6.2-1.1.i386.rpm
  inflating: sun-javadb-demo-10.6.2-1.1.i386.rpm
  inflating: sun-javadb-docs-10.6.2-1.1.i386.rpm
  inflating: sun-javadb-javadoc-10.6.2-1.1.i386.rpm
Preparing...                ########################################### [100%]
   1:jdk                    ########################################### [100%]
Unpacking JAR files...
        rt.jar...
        jsse.jar...
        charsets.jar...
        tools.jar...
        localedata.jar...
        plugin.jar...
        javaws.jar...
        deploy.jar...
Installing JavaDB
Preparing...                ########################################### [100%]
   1:sun-javadb-common      ########################################### [ 17%]
   2:sun-javadb-core        ########################################### [ 33%]
   3:sun-javadb-client      ########################################### [ 50%]
   4:sun-javadb-demo        ########################################### [ 67%]
   5:sun-javadb-docs        ########################################### [ 83%]
   6:sun-javadb-javadoc     ########################################### [100%]

Done.
Now check your JDK version
[root@localhost phuongvu]# java -version
java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) Client VM (build 20.45-b01, mixed mode, sharing)
Done.

Saturday, March 28, 2015

How to install JDK 7 on CentOS

P
This article will show you how to download and install JDK 7 on CentOS through command line in case your PC has been installed the no GUI version.
Step 1: Download the file installer from this server to your machine, paste below code for x86 machine
[root@localhost phuongvu]# wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/7u75-b13/jdk-7u75-linux-i586.rpm
And if your machine is x64
[root@localhost phuongvu]# wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/7u75-b13/jdk-7u75-linux-x64.rpm
OK. let have a check
[root@localhost phuongvu]# ls
Desktop    Downloads                Music     Public     Videos
Documents  jdk-7u75-linux-i586.rpm  Pictures  Templates

Step 2: Install the file you just have downloaded
[root@localhost phuongvu]# rpm -ivh jdk-7u75-linux-i586.rpm
Unpacking JAR files...
        rt.jar...
        jsse.jar...
        charsets.jar...
        tools.jar...
        localedata.jar...
        jfxrt.jar...
        plugin.jar...
        javaws.jar...
        deploy.jar...
Now, check whether JDK is installed or not
[root@localhost phuongvu]# java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) Client VM (build 24.75-b04, mixed mode, sharing)
Now your PC has been installed JDK 7. You can set JAVA_HOME variable by typing
[root@localhost phuongvu]# export JAVA_HOME=/usr/java/latest
Done.

Wednesday, March 25, 2015

How to open file and go to the specific line or text string in Linux

P
This tutorial could resolve a problem that you want to edit a text file with the line number goes up to a hundred. Now you don't have to scroll down and wait until you're at the line need to be changed.
Please note that, this tutorial I am going to show you just works with vi/vim command, so your PC must be installed either of them.

About usage, vi and vim has the same way to use. Now I will show you how to do this

vi +SearchString fileName

Or

vi +LineNumber fileName

Others ways

vi +/SearchString fileName
vi +/LineNumber fileName
vim +/LineNumber fileName

Sample

In case you want to open Hello.java at line 90
vi +90 Hello.java

In case you want to open Hello.java at function say()
vim +/"say()" Hello.java

References

Friday, March 20, 2015

Set IP Address by using shell script on CentOS

P



You have a linux machine without GUI and you want to change its IP address? I was in this situation and spent few days to find way out. Now, I want to share this with you. You just copy and create your own shell script, that's all.



Create a bash script file

From command line, just type this then press Enter
$ vi setIP.sh
Copy and paste below scripts and save it
#!/bin/bash

#Usage: setIPHostName <ip> <netMask> <gateWay> <domainName> <domainIP>
get_prop(){ 
    propfile=$1
    key=$2
    grep  "^${2}=" ${1}| sed "s%${2}=\(.*\)%\1%"
}

ip=$1
netmask=$2
gateway=$3
domainname=$4
domainip=$5
hostname=$( cat /etc/hosts | grep 127.0.0.1 | awk '{ print $2 }' )
hostnameAlias=$( cat /etc/hosts | grep 127.0.0.1 | awk '{ print $3 }' )
uuid=`get_prop /etc/sysconfig/network-scripts/ifcfg-eth0 UUID`
hwaddr=`get_prop /etc/sysconfig/network-scripts/ifcfg-eth0 HWADDR`

checkVar ()
{

 echo ""
 echo "Variables to be set"
 echo IP = $ip
 echo NETMASK = $netmask
 echo GATEWAY = $gateway
 echo DOMAINNAME = $domainname
 echo DOMAINIP = $domainip
 echo HOSTNAME = $hostname
 echo HOSTNAME ALIAS = $hostnameAlias
 echo UUID = $uuid
 echo HWADDR = $hwaddr
 echo ""
 echo ""

}

setIpHostname ()
{
        # set hosts file
        echo "127.0.0.1 $hostname $hostnameAlias localhost" > /etc/hosts

        # set resolve.conf
        echo "search $domainname" > /etc/resolv.conf
        echo "nameserver $domainip" >> /etc/resolv.conf

        # set network file
        echo "NETWORKING=yes" > /etc/sysconfig/network
        echo "HOSTNAME=$hostname" >> /etc/sysconfig/network
 echo "GATEWAY=$gateway" >> /etc/sysconfig/network

        # set ifcfg-eth0
        echo "DEVICE=eth0" > /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "NAME=\"System eth0\"" > /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "BOOTPROTO=none" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "NETMASK=$netmask" >> /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "IPADDR=$ip" >>  /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "GATEWAY=$gateway" >> /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "TYPE=Ethernet" >> /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "NM_CONTROLLED=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "IPV4_FAILURE_FATAL=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "IPV6INIT=no" >> /etc/sysconfig/network-scripts/ifcfg-eth0
        echo "DEFROUTE=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "DOMAIN=$domainname" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "DNS1=$domainip" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "UUID=$uuid" >> /etc/sysconfig/network-scripts/ifcfg-eth0
 echo "HWADDR=$hwaddr" >> /etc/sysconfig/network-scripts/ifcfg-eth0
  
}

main ()
{
 setIpHostname
 # This VA so set it for every boot
 #cp /etc/hosts /root/
 #cp /etc/resolv.conf /root/
 #cp /etc/sysconfig/network /root/
 #cp /etc/sysconfig/network-scripts/ifcfg-eth0 /root/

 #{
  #echo "## Following line is added by ISV"
  #echo "cp /root/hosts /etc/hosts"
  #echo "cp /root/resolv.conf /etc/resolv.conf"
  #echo "cp /root/network /etc/sysconfig/network"
  #echo "cp /root/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0"
 #} >> /etc/rc.local

 echo "IP is changed. Rebooting..."
 #sleep 2
 #shutdown -r 1
 shutdown -r now
}

#checkVar
#setIpHostname
main

How to use
From command line, type this
$ ./setIP.sh     
For example
$ ./setIP.sh 192.168.1.241 192.168.1.254 255.255.255.0 google.com 8.8.8.8
NOTE: After run this script, your computer will be restart automatically. After your machine started, check your IP to make sure it is changed by command
$ ifconfig
Done!

Wednesday, March 18, 2015

How to set date and time in Linux

P




You want to change your date time system but your machine doesn't have GUI. Don't worry, this tips will show you how to do that.
Because date time is a system part, so you need to have root privileges to do that. Here we go.


Linux Display Current Data and Time

Just type this command and then enter
$ date
Sample outputs:
Wed Mar 18 22:38:41 ICT 2015

Linux Display The Hardware Clock (RTC)
Type the following hwclock command to read the Hardware Clock and display the time on screen:
# hwclock -r
Or
# hwclock --show
Or show it in Coordinated Universal time (UTC):
# hwclock --show --utc
Sample outputs:
Wed 18 Mar 2015 10:42:59 PM ICT  -0.078791 seconds

Linux Set Date Time Command Example

Use the following syntax to set new data and time:
date --set="STRING"
For example, set new data to Mar 02 2015 14:30:00, type the following command as root user:
# date -s "Mar 02 2015 14:30:00"
Or
# date --set "Mar 02 2015 14:30:00"
You can also simplify format using following syntax:
# date +%Y%m%d -s "20150302"

Linux Set Time Only Command Example

To set time use the following syntax:
# date +%T -s "10:13:13"
10: Hour (hh)
13: Minute (mm)
13: Second (ss)
Use %p locale's equivalent of either AM or PM, enter:
# date +%T%p -s "6:10:30AM"
# date +%T%p -s "12:10:30PM"

References



Saturday, March 14, 2015

CentOS - Open port in Firewall

Step 1: Edit file /etc/systemconfig/iptables


vi /etc/sysconfig/iptables


Append rule as follows:
If you want to open port 80:


-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT


If you want to open port 443:


-A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT


If you want to open port 8888:


-A INPUT -m state --state NEW -m tcp -p tcp --dport 8888 -j ACCEPT


Step 2: Save this file by pressing ESC and type :wq! then Enter


Step 3: Restart iptables service


service iptables restart

Done!

References




Thursday, March 12, 2015

How to find out linux distribution name and version


How do I find out what version of Linux distribution I'm using from the shell (bash) prompt?

You can use any one of the following method to find out your Linux distribution and name:

Method #1: /etc/*-release file

To find out what version of Linux (distro) you are running, enter the following command at the shell prompt:



$ cat /etc/*-release


Sample output from my CentOS 6.6:


[root@localhost ~]# cat /etc/*-release
CentOS release 6.6 (Final)
LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
CentOS release 6.6 (Final)
CentOS release 6.6 (Final)


Method #2: lsb_release Command To Find Out Linux Distribution Name/Version
The lsb_release command displays certain LSB (Linux Standard Base) and distribution-specific information. Type the following command:


$ lsb_release -a


Sample outputs:


[root@localhost ~]# lsb_release -a
LSB Version:    :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description:    CentOS release 6.6 (Final)
Release:        6.6
Codename:       Final


How Do I Find Out My Kernel Version?


Type the following command:


$ uname -a


Or


$ uname -mrs


Sample outputs:


[root@localhost ~]# uname -a
Linux localhost.localdomain 2.6.32-504.el6.x86_64 #1 SMP Wed Oct 15 04:27:16 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost ~]# uname -mrs
Linux 2.6.32-504.el6.x86_64 x86_64

Where,

  1. Linux - Kernel name
  2. 2.6.32-5-amd64 - Kernel version number
  3. x86_64 - Machine hardware name (64 bit)


References

Monday, March 9, 2015

Where Are MySQL Files Stored in UNIX / Linux

P
Usually /var/lib/mysql or /var/db/mysql directory used to store database and tales under UNIX like operating systems.
You can use the following command to locate MySQL datadir:


grep datadir /etc/my.cnf


Sample outputs:


datadir=/var/lib/mysql


Another command that will display datadir:


ps -eo cmd,args | grep mysql


Sample outputs:


/bin/sh /usr/bin/mysqld_saf /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --user=mysql
/usr/libexec/mysqld --based /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --skip-external-locking --socket=/var/lib/mysql/mysql.sock


FreeBSD UNIX specific ps example:


ps -ao pid,command | grep mysql


Sample outputs:


5343 /bin/sh /usr/local/bin/mysqld_safe --defaults-extra-file=/var/db/mysql/my.cnf --user=mysql --datadir=/var/db/mysql --socket=/tmp/mysql.sock --pid-file
 5381 /usr/local/libexec/mysqld --defaults-extra-file=/var/db/mysql/my.cnf --basedir=/usr/local --datadir=/var/db/mysql --user=mysql --pid-file=/var/db/mysq
References

Tuesday, March 3, 2015

Replace a String in Multiple Files in Linux Using Grep and Sed

P
I recently had to replace every occurrence of a certain word / string in a ton of files spanning multiple directories, and this is the quickest way I've found to do it. It uses grep to search for a certain word and if it find its it runs sed to replace the strings you want.
Note: This will not work on windows systems
Basic Format

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

Note: The forward slash '/' delimiter in the sed argument could also be a different delimiter (such as the pipe '|' character). The pipe delimiter might be useful when searching through a lot of html files if you didn't want to escape the forward slash, for instance.
matchstring is the string you want to match, e.g., "football" string1 would ideally be the same string as matchstring, as the matchstring in the grep command will pipe only files with matchstring in them to sed. string2 is the string that replace string1. There may be times when you want to use grep to find only files that have some matchstring and then replace on a different string in the file than matchstring. For example, maybe you have a lot of files and only want to only replace on files that have the matchstring of 'phonenumber' in them, and then replace '555-5555' with '555-1337'. Not that great of an example (you could just search files for that phone number instead of the string 'phonenumber'), but your imagination is probably better than mine.

Example
grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

This will search for the string 'windows' in all files relative to the current directory and replace 'windows' with 'linux' for each occurrence of the string in each file.
Conclusion
Any comments / suggestions for improvement are much welcomed.

Thanks to vasir.net 

Friday, February 27, 2015

OutOfMemoryError in Java

P

java.lang.OutOfMemoryError now and then, OutOfMemoryError in Java is one problem which is more due to system's limitation (memory) rather than due to programming mistakes in most cases though in certain cases you could have memory leak which causing OutOfMemoryError. I have found that even though java.lang.OutOfMemoryError is quite common basic knowledge of its cause and solution is largely unknown among junior developers. In this article we will explore what is java.lang.OutOfMemoryError; Why OutOfMemoryError comes in Java application, different type of OutOfMemoryError and How to fix OutOfMemoryError in Java. This article is purely meant to provide basic knowledge of java.lang.OutMemoryError and won't discuss profiling in detail.

I have seen mainly two types of OutOfMemoryError in Java:

1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space

The solution to solve this problem is use options of JVM.

export JAVA_OPTS="-Xms256m -Xmx512m -XX:PermSize=64M -XX:MaxPermSize=256M"

On Windows, you can set variables environment by right clicking computer and choosing Properties



Note that, these values above just sample, you can adapt to your own project.

Reference: javarevisited

"User" is not in the sudoers file on CentOS

P
When you try to do a command that required root privilege like this
[phuongvu@localhost Desktop]$ sudo cat /etc/sudoers

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for phuongvu: 
phuongvu is not in the sudoers file.  This incident will be reported.

A solution for this is add a current user in sudoers file. This file located in /etc/sudoers and you must use root privilege to edit this file.
Let do this:

Normally, sudoers file is read-only, therefore, we have to change access permission for it. Login as root user

[phuongvu@localhost Desktop]$ su
Password: 
[root@localhost Desktop]# chmod 666 /etc/sudoers

Edit sudoers file
[root@localhost Desktop]# vi /etc/sudoers

Find this line and add new line like below
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
phuongvu        ALL=(ALL)       ALL

Save and re-grant read-only property for it
[root@localhost Desktop]# chmod 440 /etc/sudoers
Done. Now logout root account and use this command as normal user

[phuongvu@localhost Desktop]$ sudo cat /etc/sudoers

Thursday, February 26, 2015

How to remove MySQL completely on CentOS

P
Step 1: List the mysql rpm which is installed on server

[root@localhost ~]# rpm -qa | grep mysql
mysql-5.0.95-5.el5_9
mysql-server-5.0.95-5.el5_9
Step 2: Remove Mysql

[root@localhost ~]# yum remove mysql-5.0.95-5.el5_9

Step 3: Search for Mysql Related Files on server

[root@localhost ~]# find / -iname '*mysql*'

Step 4: Remove all mysql related files

[root@localhost ~]# find / -iname ‘*mysql*’ -exec rm -rf {} \;

Step 5: Remove this folder

[root@localhost ~]# rm -rf /var/lib/mysql

Complete!

Tuesday, February 24, 2015

How to install the latest MySQL on CentOS

P
The previous post I show you how to install MySQL on CentOS from its repository but it is not the latest MySQL version. Today, on this post, I will show you how to install the latest MySQL on CentOS.

Downloading the MySQL Yum Repository Release Package

[phuongvu@localhost ~]$ wget http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm
--2014-08-28 22:59:50--  http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm
Resolving dev.mysql.com... 137.254.60.11
Connecting to dev.mysql.com|137.254.60.11|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm [following]
--2014-08-28 22:59:50--  http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm
Resolving repo.mysql.com... 23.202.216.96
Connecting to repo.mysql.com|23.202.216.96|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5824 (5.7K) [application/x-redhat-package-manager]
Saving to: `mysql-community-release-el6-5.noarch.rpm'

100%[====================================>] 5,824       --.-K/s   in 0s     

2014-08-28 22:59:51 (741 MB/s) - `mysql-community-release-el6-5.noarch.rpm' saved [5824/5824]

[phuongvu@localhost ~]$ ls
mysql-community-release-el6-5.noarch.rpm

We have a rpm file.

Installing the MySQL Yum Repository Release Package

[phuongvu@localhost~]$ sudo yum localinstall mysql-community-release-el6-5.noarch.rpm

Installed:
  mysql-community-release.noarch 0:el6-5

Complete!

Checking the Version of the Available Mysql

[phuongvu@localhost~]$ yum info mysql-community-server

Now, you will see the result

Available Packages
Name        : mysql-server
Arch        : i686
Version     : 5.1.73
Release     : 3.el6_5
Size        : 8.8 M
Repo        : updates
Summary     : The MySQL server and related files
URL         : http://www.mysql.com
License     : GPLv2 with exceptions
Available Packages
Name        : mysql-community-server
Arch        : i686
Version     : 5.6.20
Release     : 4.el6
Size        : 51 M
Repo        : mysql56-community
Summary     : A very fast and reliable SQL database server
URL         : http://www.mysql.com/
License     : Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. Under GPLv2 license as shown in the Description field

Notice that there are two packages:

  1. mysql-server
  2. mysql-community-server

mysql-server is the one provided by the default yum repositories. mysql-community-server is the one provided by our newly installed MySQL yum repository, which should be the latest stable release.

Installing

Use this command to install:
[phuongvu@localhost~]$ yum install mysql-community-server

warning: rpmts_HdrFromFdno: V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Retrieving key from file:/etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
Importing GPG key 0x5072E1F5:
 Userid : MySQL Release Engineering <mysql-build@oss.oracle.com>
 Package: mysql-community-release-el6-5.noarch (@/mysql-community-release-el6-5.noarch)
 From   : file:/etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
Is this ok [y/N]:

Enter "y" to finish

Complete!

Starting MySQL

[phuongvu@localhost~]$ sudo service mysqld start
Initializing MySQL database:
Starting mysqld:                                           [  OK  ]

Securing the Installation

As mentioned in the above output, if we are running this on a production server then we should do a secure installation as follows:

[phuongvu@localhost~]$ mysql_secure_installation


NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL

      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!



In order to log into MySQL to secure it, we'll need the current

password for the root user.  If you've just installed MySQL, and

you haven't set the root password yet, the password will be blank,

so you should just press enter here.



Enter current password for root (enter for none):



This should be the first time, so we shouldn’t have a password yet. Just press enter.



OK, successfully used password, moving on...



Setting the root password ensures that nobody can log into the MySQL

root user without the proper authorisation.



Set root password? [Y/n]



Enter Y and enter your new password:



New password:

Re-enter new password:

Password updated successfully!

Reloading privilege tables..

 ... Success!





By default, a MySQL installation has an anonymous user, allowing anyone

to log into MySQL without having to have a user account created for

them.  This is intended only for testing, and to make the installation

go a bit smoother.  You should remove them before moving into a

production environment.



Remove anonymous users? [Y/n]



If you are running on a production server then you should definetely press Y.



Normally, root should only be allowed to connect from 'localhost'.  This

ensures that someone cannot guess at the root password from the network.



Disallow root login remotely? [Y/n]



Once again if you are in production then enter Y. In fact enter Y for all the questions if you are in production:



By default, MySQL comes with a database named 'test' that anyone can

access.  This is also intended only for testing, and should be removed

before moving into a production environment.



Remove test database and access to it? [Y/n] Y

 - Dropping test database...

ERROR 1008 (HY000) at line 1: Can't drop database 'test'; database doesn't exist

 ... Failed!  Not critical, keep moving...

 - Removing privileges on test database...

 ... Success!



Reloading the privilege tables will ensure that all changes made so far

will take effect immediately.



Reload privilege tables now? [Y/n] Y

 ... Success!









All done!  If you've completed all of the above steps, your MySQL

installation should now be secure.

Congratulations you are done. Now let’s see if mysql will survive a reboot:

Surviving a reboot

[phuongvu@localhost~]$ sudo chkconfig --level 3 mysqld on

[phuongvu@localhost~]$ chkconfig --list | grep mysql

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

Now let’s reboot again and test:

[phuongvu@localhost~]$ sudo service mysqld status

mysqld is stopped

[phuongvu@localhost~]$ sudo service mysqld start

Starting mysqld:                                           [  OK  ]

[phuongvu@localhost~]$ sudo service mysqld status

mysqld (pid  1159) is running...

[phuongvu@localhost~]$ sudo reboot

Now let’s test:

[phuongvu@localhost~]$ sudo service mysqld status

mysqld (pid  733) is running...

Looks like it works fine.

Monday, February 23, 2015

How to install MySQL on CentOS from its repository

P

Installation

This tutorial will show you how to install MySQL on CentOS from its repository. Because it is installed from CentOS's repository then I'm sure the latest version of MySQL will be installed.
Open terminal and type with root privileges



yum -y install mysql-server

Make MySQL run once computer started


chkconfig mysqld on

Make MySQL run as service


service mysqld start
Change Root Password

Login MySQL with root account (Blank for password by default)

mysql -u root -p
Use this command to change root's password
use mysql;

UPDATE user SET Password=PASSWORD('MyNewPass') WHERE User='root';
Make an external access
GRANT ALL ON *.* to 'user1'@'theIP' IDENTIFIED BY 'password1';

flush privileges;
After this command executed, user1 has been created for theIP access to MySQL with password is password1. NOTE: if you want all IP address can be accessed MySQL just replace 'theIP' to '%'