Tuesday, October 23, 2018

A bash script to run a jar file as a backend service in Linux boxes with user ownership

#!/bin/sh
PROCESS_NAME=pname
PATH_TO_JAR=/var/www/html/stable_build/build.jar
LOG_PATH=/home/user/tomcat/wolf/wolf-backend.log
USER=user
pidfile=${PIDFILE-/var/run/${PROCESS_NAME}.pid};
lockfile=${LOCKFILE-/var/lock/subsys/${PROCESS_NAME}};

RETVAL=0

. /etc/init.d/functions

. /home/user/.bashrc

start() {

PID=`pidofproc -p ${pidfile} ${PROCESS_NAME}`
if [[ (-n ${PID}) && ($PID -gt 0) ]]; then
echo "${PROCESS_NAME}(pid ${PID}) is already running."
exit;
fi

echo -n $"Starting $PROCESS_NAME ..."
daemon --user $USER java -Dprocessname=${PROCESS_NAME} -jar $PATH_TO_JAR >> $LOG_PATH 2> $LOG_PATH < /dev/null &
sleep 10
PID=`ps -eaf|grep processname=${PROCESS_NAME}|grep -v grep|awk '{print $2}'| tail -1`
RETVAL=$?
[ $RETVAL = 0 ] && touch ${lockfile}
[ $RETVAL = 0 ] && echo "${PID}" > ${pidfile}
echo " Started"
}

status(){
PID=`pidofproc -p ${pidfile} ${PROCESS_NAME}`
if [[ (-n ${PID}) && ($PID -gt 0) ]]; then
echo "${PROCESS_NAME}(pid ${PID}) is running."
else
echo "${PROCESS_NAME} is stopped."
fi
}

stop() {
echo -n $"Stopping $PROCESS_NAME: ..."
PID=`pidofproc -p ${pidfile} ${PROCESS_NAME}`
if [[ (${PID} -gt 0) ]];
then
kill -9 $PID
RETVAL=$?
[ $RETVAL = 0 ] && rm -f ${lockfile}
[ $RETVAL = 0 ] && rm -f ${pidfile}
fi
echo " Stopped"
}

case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
stop
start
;;
*)
echo "Usage: service $SERVICE_NAME {start|stop|status|restart}"
exit 1
;;
esac

A bash script to install a package w.r.to the OS flavor in Linux

#!/bin/bash

func1()
{
yum -y install httpd
systemctl start httpd
systemctl enable httpd
}

func2()
{
apt-get -y install nginx
/etc/init.d/nginx start
update-rc.d nginx defaults
 }

file1="/etc/redhat-release"
file2="/etc/lsb-release"

if [ -f "$file1" ]
then
echo "Centos box"
cat /etc/redhat-release | grep -i 'Centos' | awk '{if(NR==2) print $0}'; echo $?
func1
elif [ -f "$file2" ]
then echo " Ubuntu Box "
cat /etc/lsb-release | grep -i 'Ubuntu' | awk '{if(NR==2) print $0}'; echo $?
func2
else
echo "desired OS flavor not found"
fi

A simple python script to fetch and save memory stats to sqlite3 database in Linux machines.

#!/usr/local/bin/python
import distro
import os
import time
import sqlite3
import re
memfile = "/home/sibin/python-projects/memstat"
db = sqlite3.connect('/home/sibin/python-projects/data.db')
os_version = distro.linux_distribution()
def mem_info():
  with open("/proc/meminfo", "r") as f:
    lines = f.readlines()
    line1 = lines[0].strip()
    line2 = lines[1].strip()
    line3 = lines[3].strip()
    line4 = lines[14].strip()
    line5 = lines[15].strip()
    line = ("%s \n %s \n %s \n %s \n %s \n %s \n" % (os_version,line1,line2,line3,line4,line5))
    result1 = re.sub('[^0-9]','',line1)
    result2 = re.sub('[^0-9]','',line2)
    result3 = re.sub('[^0-9]','',line3)
    result4 = re.sub('[^0-9]','',line4)
    result5 = re.sub('[^0-9]','',line5)
    cursor = db.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS memoryinfo(id INTEGER PRIMARY KEY,MemTotal TEXT, MemFree TEXT,
    Buffers TEXT, SwapTotal TEXT,SwapFree TEXT)''')
    for i in line:
      cursor.execute('''INSERT INTO memoryinfo(MemTotal, MemFree, Buffers, SwapTotal, SwapFree)
      VALUES(?,?,?,?,?)''', (result1, result2, result3, result4, result5))
      db.commit()
  return mem_info
while True:
  mem_info()
  time.sleep(3)

Wednesday, November 16, 2016

Change ssh default port in Centos 7

Hi folks,

For the latest Centos7 Operating system ssh port change need below procedures,

take backup of original ssh config file,

cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

Then edit config file of ssh to add new port in the line

#Port 22 (uncomment it and change port number from 22 to desired number)

If semanage package not existing run below command,

yum -y install policycoreutils-python

Then add new port number to selinux configuration to allow for ssh,

 semanage port -a -t ssh_port_t -p tcp 'port'

Then restart ssh service ,

service sshd restart

If firewalld is using in the server add new port to firewall,

firewall-cmd --permanent --zone=public --add-port='port'/tcp
firewall-cmd --reload


That's all fellas ....................

Tuesday, May 26, 2015

How to create a mail account in Webmin server

Ref : http://how-to.tcwebadmin.com/linux-server/how-to-setup-a-mail-user-in-webmin-dovecot-and-postfix/

STEP 1. From the left-side Menu, click “System” and then click on “Users and Groups”

STEP 2. Click on “Create a new user” link

STEP 3. Fill in the form with appropriate information. For this article’s purposes we will use the username: demouser. The following ones are recommended to be filled-in:

- Username (if you want to have an email address demouser@yourdomain.com , set the username’s value to demouser)
- User ID: leave it automatic
- Real Name: required only for you to identify each account from the list
- Home Directory: Click “Directory” and set it to: /home/<username> where <username> is what you set in the Username field
- Shell: Leave it as it is
- Password: click the “Normal password” and type your desired password (it will be encrypted on save/exit)

You will see few more settings/fields on the same form. You may fill them in if you like. However, the above mentioned fields are those required to have a valid e-mail account created.

FINAL STEP 4. Now click the “Create” button and you are done!


Now that you have the user and new password created, you are ready to setup the new user mailbox on the server. You now want to go over to Servers > Postfix Mail Server. Now in order to use your new user as an outgoing email you must next click on the icon labeled “Virtual Domains” then.. Next simply go to “Add New Mapping”. 
Create mapping for user to user@domainname , it will make mail account.

The account can access using usermin link : https://server:20000  
Then enter access details with mail ID and user password . 

Wednesday, December 10, 2014

How to find the Outdated Wordpress Versions serverwide and send email to domain users ?


Hi, 
Here is the perl script doing it.

#!/usr/bin/perl -w
use HTML::Template;
use MIME::Lite;
 
my $email;
my $domains;
my @locate;
my @s;
my $emails;
my @d;
my $currentversion;
my $latestversion="3.5.1";
my @current;
my $installdir;
 
@locate=`/usr/bin/locate wp-includes/version.php | grep -v virtfs | xargs grep "wp_version = " 2>/dev/null | grep -v " = '3.5.1'"`;
 
foreach my $k (@locate){
        chomp($k);
 
        @s=split(/\//, $k);
 
        $emails=`/bin/grep -i contactemail /var/cpanel/users/$s[2] |/bin/grep \@`;
 
        chomp($emails);
        @e=split(/\=/,$emails);
 
        $email=$e[1] if $e[1]=~/\@/i;
 
        $domains=`/bin/grep -i dns\= /var/cpanel/users/$s[2]`;
        chomp($domains);
 
        @d=split(/\=/, $domains);
 
        $domain=$d[1] if $d[1];
 
        @current=split(/\s+/, $k);
 
$currentversion=$current[$#current];
 
        $currentversion=~s#;##g;
 
        $installdir=$current[0];
 
        $installdir=~s#wp-includes/version.php:\$wp_version##g;
 
        print "$k , $domain , $email\n";
 
$template = HTML::Template->new(filename =>"/scripts/wpemail.tmpl");
$template->param(
                domain=>$domain,
                installdir=>$installdir,
                currentversion=>$currentversion,
                latestversion=>$latestversion
                );
 
        my $msg2 = MIME::Lite->new(
                        From    =>"info\@domain.com",
                        To      =>"desination\@emailaddress.com",
                        Subject =>"Your Wordpress Outdated notice for $domain",
                        Type    =>'multipart/related'
                        );
 
                $msg2->attach(Type => 'text/html',
                             Data =>$template->output
                            );
 
#                $msg2->send();
 
}

How to remove a physcal volume/drive from a Volumegroup or How to move a root volume group to new drive

Scenario

The root VG needs to be moved to a different physical disk (e.g. to convert from ATA to SATA drives).

Assumptions

  1. You know how to partition disks using fdisk and can edit /etc/fstab with a text editor (such as vim).
  2. Your /boot filesystem is on a separate partition, and your root filesystem is part of an LVM VG.
  3. Your root VG contains only one PV.

Environment

This procedure was developed on a system with an Intel Core i5 3.2 GHz CPU with 4 GB RAM. The source disk is a Seagate ST3802110A (80 GB ATA), and the destination is a Maxtor 7Y250M0 (250 GB SATA). The Linux distribution used was CentOS 5.4, but these commands should apply to nearly all Linux distributions which support LVM.

Special note

Because LVM is below the filesystem layer (see filesystem layers overview for more information), all of the following operations (with the exceptions of the reboots in the first and last steps) may be done online, without unmounting any filesystems. However, this work should be scheduled for non-peak times, because there is no way (to my knowledge) to control the rate at which pvmove copies data. Therefore, it will usually utilise almost all of your disk's I/O bandwidth.

Procedure

  1. Connect the new disk to the system. Depending on your hardware and kernel version, you may need to reboot your system to detect it.
  2. Check the partition structure on the source drive. In this case, it has one partition for /boot and the rest of the drive is LVM (output from fdisk -l):
    Disk /dev/hde: 80.0 GB, 80026361856 bytes
    255 heads, 63 sectors/track, 9729 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes
       Device Boot      Start         End      Blocks   Id  System
    /dev/hde1   *           1          13      104391   83  Linux
    /dev/hde2              14        9729    78043770   8e  Linux LVM
  3. Create partitions on the destination drive to match the source drive. It's OK if they are larger than their equivalents on the source drive. In this scenario, i've increased /boot to 1 GB, and used the remainder of the 250 GB drive forLVM. Here's the final partition setup:
    Disk /dev/sdb: 250.0 GB, 250058268160 bytes
    255 heads, 63 sectors/track, 30401 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes
       Device Boot      Start         End      Blocks   Id  System
    /dev/sdb1   *           1         123      987966   83  Linux
    /dev/sdb2             124       30401   243208035   8e  Linux LVM
  4. Create the boot filesystem on the new drive:
    mkfs -t ext3 -L /boot /dev/sdb1
  5. Mount it on /mnt:
    mount /dev/sdb1 /mnt
  6. Change /etc/fstab to use label rather than path to mount the disk. The line should look something like this when you're done:
    LABEL=/boot  /boot  ext3  defaults  1 2
  7. Copy files from the existing /boot to the new /boot (mounted on /mnt):
    cd /mnt
    dump -0 -b 1024 -f - /boot/ | restore -r -f - -b 1024
  8. Unmount the new /boot filesystem:
    umount /mnt
  9. Install GRUB to the new drive:
    grub
    grub> device (hd1) /dev/sdb
    device (hd1) /dev/sdb
    grub> root (hd1,0)
    root (hd1,0)
     Filesystem type is ext2fs, partition type 0x83
    grub> setup (hd1)
    setup (hd1)
     Checking if "/boot/grub/stage1" exists... no
     Checking if "/grub/stage1" exists... yes
     Checking if "/grub/stage2" exists... yes
     Checking if "/grub/e2fs_stage1_5" exists... yes
     Running "embed /grub/e2fs_stage1_5 (hd1)"...  15 sectors are embedded.
    succeeded
     Running "install /grub/stage1 (hd1) (hd1)1+15 p (hd1,0)/grub/stage2 /grub/grub.conf"... succeeded
    Done.
    grub> quit                                                                                             
  10. Set up the other partition on your new root disk as an LVM PV:
    pvcreate /dev/sdb2
  11. Find your current root VG and PV names:
    vgdisplay -v
  12. Add the new PV to your root VG (substitute vg00 for the name of your VG):
    vgextend /dev/vg00 /dev/sdb2
  13. Now comes the LVM magic to move the LVs on your current root PV to the new PV. First, test the operation we're about to commence:
    pvmove --test --verbose /dev/hde2 /dev/sdb2

    Then run it:
    pvmove --verbose /dev/hde2 /dev/sdb2
  14. This operation will take some time, depending on the size of your data and the speed of your disks. (The system with which i tested this article (see above for specifications) completed the move in approximately 45 minutes.) Pvmove will keep you up-to-date with its progress, but i like to also see how it's performing by running iostat in another terminal:
    iostat -dkx 30

    Iostat is part of the sysstat package on most Linux distributions. It is not installed by default.
  15. When the pvmove is complete, remove the old root disk from the VG (once again, substitute the name of your VGfor vg00):
    vgreduce /dev/vg00 /dev/hde2
  16. Shut down your system, disconnect the old drive, and reboot using your new drive.

Miscellaneous notes

  • If something has gone wrong with your /boot copy or GRUB install, you can boot your system by installing the old disk again, because the old disk contains a fully functional /boot partition, and the LVM VG will be found regardless of which drive it resides upon.
  • It is possible to interrupt pvmove with Ctrl-C and resume it by re-running the same command.
  • I have never seen pvmove fail if its test run succeeds, so i have no idea what to do if this happens. :-)