Friday, 6 November 2015

Concurrent connection in apache

#!/bin/bash

## Purpose:
## This script provide number of connection established with the port and type of connection


## Variable Declaration

LINE='#######################################################################################################'
tput clear
RED='\033[0;33m'
GREEN='\033[0;32m'
NC='\033[0m'

## Help Menu

help()
        {
        echo -e '\033[33;36m
        USAGE:'${NC}' '$0' OPTIONS [ m | p | h ]

        -m Accepts multiport --> '$0' 80 443
        -p Accept single port --> '$0' 80
        '
        }



## Packet function

packet()
        {

        echo $LINE
        echo -e "\t\t\t${RED} PORT => ${1} $NC"
        total=`netstat -antupe |  perl -ane 'if($F[4]=~/:'${1}'/) {print}' | tee /tmp/netstat.log | wc -l`
        echo
        echo  -e "Total number of request for the  Port: ${1}  => ${GREEN}  ${total} ${NC}\n"
        echo "Detailed request for the port number: ${1}"
        cat /tmp/netstat.log | perl -ane 'print $F[5]."\n"' | uniq -c
        perl -e 'print "\n" foreach(0..2)'
        echo $LINE

        }

##Main

while getopts "p:m:h" opt
do
        case $opt in

                p)
                shift
                [[ $# -ne 1 ]] && echo "Pass single arguement " && exit
                packet $OPTARG;;
                m)
                shift
                [[ $# -lt 2 ]] && echo -e "not enough arguement\n use -p instead for single port" && exit 7
                for i in $*
                do
                        packet ${i}
                        echo
                done;;
                h)
                help;;
                *)
                echo "Generating help menu"
                help;;

        esac
done

Wednesday, 14 October 2015

Finding highest CPU utilization last 20 mins + perl + sar

sar -s `date '+%R:00' -d '20 minute ago'` | grep  -v Average | perl -ane 'if($F[@f-1] > 10) {print "Highest CPU utilization $F[0]\n"}'

Monday, 22 June 2015

Grepping file based on month + perl + one liner

# ls -l | perl -ne '@s=split(" ");if(($s[5] eq "May")&&($s[6] > 27)) {print}'

[root@centos64 ~]# ls -l | perl -ne '@s=split(" ");if(($s[5] eq "May")&&($s[6] > 27)) {print}'
-rw-r--r--  1 root root    284857 May 28 05:45 apr-1.5.0-1.x86_64.rpm
-rw-r--r--  1 root root   1072141 May 28 05:45 apr-devel-1.5.0-1.x86_64.rpm
-rw-r--r--  1 root root     77504 May 28 05:45 apr-util-1.5.3-1.x86_64.rpm
-rw-r--r--  1 root root    489168 May 28 05:45 apr-util-devel-1.5.3-1.x86_64.rpm
-rw-r--r--  1 root root   3684645 May 28 05:45 httpd-2.4.12-1.x86_64.rpm
-rw-r--r--  1 root root    203249 May 28 05:45 httpd-devel-2.4.12-1.x86_64.rpm
-rw-r--r--  1 root root   4226183 May 28 05:45 httpd-manual-2.4.12-1.x86_64.rpm
-rw-r--r--  1 root root    152418 May 28 05:45 httpd-tools-2.4.12-1.x86_64.rpm
-rw-r--r--  1 root root    129045 May 28 05:45 mod_lua-2.4.12-1.x86_64.rpm
You have mail in /var/spool/mail/root


Wednesday, 17 June 2015

Perl variabe input + stdin + arguement pass

[root@ENGWEB01T ~]# cat samd.pl

$s=( ! "$ARGV[0]" )?(<STDIN>):($ARGV[0]);
print $s."\n";

[root@ENGWEB01T ~]# perl samd.pl sam
sam
[root@ENGWEB01T ~]# perl samd.pl
sam
sam

Sunday, 14 June 2015

RPM build + spec + file

Folder Structure

[root@centos64 rpmbuild]# ls
BUILD  BUILDROOT  RPMS  SOURCES  SPECS  SRPMS



Sources Files , should be placed inside SOURCES folder. The file inside tar ball would be placed on respective location , which specified in spec file

[root@centos64 rpmbuild]# cd SOURCES/
[root@centos64 SOURCES]# ls
s3fs-0.1.tar.gz


[root@centos64 SOURCES]# tar -ztvf s3fs-0.1.tar.gz

drwxr-xr-x root/root         0 2015-06-14 09:00 s3fs-0.1/
-rw-r--r-- root/root      1162 2015-06-14 10:05 s3fs-0.1/s3fsd
-rw-r--r-- root/root       738 2015-06-14 10:05 s3fs-0.1/s3fs
-rw-r--r-- root/root        36 2015-06-14 05:01 s3fs-0.1/s3fs.conf





Spec file:

[root@centos64 rpmbuild]# cat SPECS/sam.spec
Summary: s3fs manage services for mount points
Name: s3fs
Version: 0.1
Release: 1
URL:     http://samlinuxsam.blogspot.in/2015/06/s3fs-service-bash.html
License: GPL
Group: Applications/Internet
BuildRoot: %{_tmppath}/%{name}-root
Requires: bash
Source0: s3fs-%{version}.tar.gz
BuildArch: noarch

%description
s3fs manages mount points and check the mount points every 15 minutes

%prep
%setup

%build


%install
rm -rf ${RPM_BUILD_ROOT}
mkdir -p ${RPM_BUILD_ROOT}/usr/bin
mkdir -p ${RPM_BUILD_ROOT}/etc
mkdir -p ${RPM_BUILD_ROOT}/etc/init.d
install -m 755 s3fs ${RPM_BUILD_ROOT}%{_bindir}
install -m 755 s3fs.conf ${RPM_BUILD_ROOT}/etc/
install -m 755 s3fsd ${RPM_BUILD_ROOT}/etc/init.d/



%clean
rm -rf ${RPM_BUILD_ROOT}

%files
%defattr(-,root,root)
%attr(755,root,root) %{_bindir}/s3fs
%config /etc/s3fs.conf
%config /etc/init.d/s3fsd

%changelog
* Fri Jun 12 2015 praveensams16@gmail.com
- Uberscript!





#########




Building RPM


rpmbuild --bb rpmbuild/SPECS/sam.spec



Friday, 12 June 2015

s3fs service + bash

Service file /etc/init.d/s3fsd

#!/bin/bash

start()
        {
        if [ ! -f /var/run/s3fs_lock ]
        then
                touch /var/run/s3fs_lock
                ./usr/bin/s3fs &
                sleep 1
                if [  -f "/var/run/s3fs_lock" ]
                then
                        echo -e "\e[1;32m s3fs service  \e[0;36m [started] \e[0m"
                else
                        echo "Error in starting the service , Please check var log messages"
                fi
        else
                echo -e "\e[1;32m s3fs service \e[1;35m [Already Running] \e[0m"
                echo -e "\n Please do restart , if the service is not proper\n"
        fi
        }
stop()
        {
        if [ ! -f "/var/run/s3fs_lock" ]
        then
                echo -e "\e[1;32m s3fs service \e[1;35m [Already Stopped] \e[0m"
        else
                rm -rf /var/run/s3fs_lock
                echo -e "\e[1;32m s3fs service \e[0;36m [stopped] \e[0m"
        fi
        }

status()
        {
        if [ -f "/var/run/s3fs_lock" ]
        then
                echo -e "\e[1;32m s3fs service \e[1;33m [Running] \e[0m"
        else
                echo -e "\e[1;32m s3fs service \e[1;35m [Not Running] \e[0m"
        fi
        }


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



## Running code file

#!/bin/bash
while true
        do
        [ ! -f "/var/run/s3fs_lock" ] && echo "service stopped" >> /tmp/logs && kill -9 $$
        echo "`date`" >> /tmp/logs

                cat /etc/s3fs.conf | grep -v '#' | grep -v '^$' > /tmp/s3fs_tmp
                line="`wc -l /tmp/s3fs_tmp 2> /dev/null | awk '{print $1}'`"
                if [ $line -lt 1 ]
                then
                logger "/etc/s3fs.conf file is empty , please make some entry and restart the service"
                rm -rf /var/run/s3fs_lock
                exit 0
                fi

               cat /etc/s3fs.conf | grep -v '#' | grep -v '^$' | while read i
                do
                source="`echo $i | awk '{print $1}'`"
                destination="`echo $i | awk '{print $2}'`"
                check="`df -h | grep -i $destination`"

                if [ ! "$check" ]
                then
                        mount  $source $destination
                fi
                done
        sleep 5
done

## Configuration File


cat /etc/s3fs.conf
#bucktname                                      mountpoints             options
/dev/sam/sam                                    /sam


Monday, 8 June 2015

Tomcat Cookbook

#
# Cookbook Name:: tomcat
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute


tomcat_base="#{node['tomcat']['basedir']}"
tomcat_user="#{node['tomcat']['user']}"


user tomcat_user do
        shell '/bin/false'
        action :create
        not_if  "grep #{node['tomcat']['user']} /etc/passwd", :user => "#{node['tomcat']['user']}"
end

directory tomcat_base do
        owner tomcat_user
        group tomcat_user
        mode "0755"
        action :create
        recursive true
        not_if { File.exist?("#{node['tomcat']['basedir']}") }
end


remote_file "/tmp/tomcat.tar.gz" do
        #source 'http://10.72.6.182/tars/mysql-5.6.23-linux-glibc2.5-x86_64.tar.gz'
        source 'ftp://192.168.33.10/pub/apache-tomcat-7.0.59.tar.gz'
        path "/tmp/tomcat.tar.gz"
        not_if { File.exist?("/tmp/tomcat.tar.gz") }
        end


execute "Extracting source" do
        command <<-EOH
        tar -zxvf /tmp/tomcat.tar.gz -C #{node['tomcat']['basedir']}/
        EOH
        not_if { File.exist?("/MSVOL/apache-tomcat-7.0.59") }
end

#Executing environment  variable

bash "Exporting catalina variable" do
        code <<-EOH
        cp  /etc/profile /etc/profile_orig
        cat >> /etc/profile <<-EOH1
        export CATALINA_BASE=#{node['tomcat']['home']}
        export CATALINA_HOME=#{node['tomcat']['home']}
        export CATALINA_TMPDIR=#{node['tomcat']['home']}/TEMP
        export CLASSPATH=#{node['tomcat']['home']}/bootstrap.jar:#{node['tomcat']['home']}/bin/tomcat-juli.jar
        EOH1
        EOH
        not_if { File.exist?("/etc/profile_orig") }
end




Friday, 29 May 2015

MySQL cook Book(RUBY)

#
# Cookbook Name:: mysql
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#


mysql_home = "#{node['mysql']['homedir']}"
var_dir = "#{node['mysql']['homedir']}/mysql/var"
var_log = "#{node['mysql']['homedir']}/mysql/var/log"
mysql_user="#{node['mysql']['user']}"

##Creating mysql user
user mysql_user do
        shell '/bin/false'
        action :create
        not_if "grep #{node['mysql']['user']} /etc/passwd", :user => "#{node['mysql']['user']}"
end

#creating mysql home directory

directory mysql_home do
        owner mysql_user
        group mysql_user
        mode "0755"
        action :create
        recursive true
        not_if { File.exist?("#{node['mysql']['homedir']}") }
end

#Taking backup of already existing my.cnf file
#
execute "mv /etc/my.cnf /etc/my.cnf_old" do
        only_if { File.exist?("/etc/my.cnf") }
end

## Using remote_file , we are downloading the tar file through apache

remote_file "/tmp/mysql.tar.gz" do
        #source 'http://10.72.6.182/tars/mysql-5.6.23-linux-glibc2.5-x86_64.tar.gz'
        source 'ftp://192.168.33.10/pub/mysql-5.6.23-linux-glibc2.5-x86_64.tar.gz'
        path "/tmp/mysql.tar.gz"
        not_if { ::File.exist?("/tmp/mysql.tar.gz") }
end

## Un-tarring downloaded package and renaming it as mysql

execute "Downloading source" do
        command <<-EOH
        echo "masterone" > /tmp/masterone
        tar -zxvf /tmp/mysql.tar.gz -C #{node[:mysql][:homedir]}/
        mv -f   #{node[:mysql][:homedir]}/mysql-5.6.23* #{node[:mysql][:homedir]}/mysql
        cp -rf  #{node[:mysql][:homedir]}/mysql  /usr/local/
        EOH
        not_if { ::File.exist?("/usr/local/mysql/bin/mysql")}
end

##creating /AZVOL/mysql/var/log folder

directory var_log do
        owner mysql_user
        group mysql_user
        mode "0755"
        action :create
        recursive true
        not_if { ::File.exist?("#{node['mysql']['homedir']}/mysql/var/log") }
end


##Installing libaio and perl-Data-Dumper ( mysql_install_db script need the following package during installation )

package ['libaio', 'perl-Data-Dumper'] do
        action :install
end

#Creating mysqld init services file
#
execute "Changing permission" do
        command <<-EOH
        chown -R mysql:mysql #{node[:mysql][:homedir]}/mysql
        cp -rf #{node[:mysql][:basedir]}/support-files/mysql.server /etc/init.d/mysqld
        EOH
end

##Copying all the binarys in /MSVOL/mysql/bin to /usr/local/bin /bin /usr/bin locations

bash "Copying_file" do
        code <<-EOH
        for i in "#{node['mysql']['basedir']}/bin/*"
        do
                bas="`basename $i`"
                cp -rvf $i /usr/local/bin && chmod 755 /usr/local/bin/$bas && chown mysql:mysql /usr/local/bin/$bas
                cp -rvf $i /usr/bin && chmod 755 /usr/bin/$bas && chown mysql:mysql /usr/bin/$bas
                cp -rvf $i  /bin && chmod 755 /bin/$bas && chown mysql:mysql /bin/$bas
        done
        EOH

       not_if { ::File.exist?("/usr/local/bin/mysql")}
end

##Creating my.cnf file from template

template "/etc/my.cnf" do
        source "masterone.cnf.erb"
        action :create
        not_if { ::File.exist?("/tmp/masterone")}

end

##Installing mysql , using mysql_install_db script

execute "Installing mysql" do
        command <<-EOH
        cd  #{node[:mysql][:basedir]}/
        scripts/mysql_install_db --user=#{node['mysql']['user']}
        echo "Installation completed" > /tmp/mysql_install
        EOH
        not_if do File.exists?('/tmp/mysql_install') end
end


service "mysqld" do
        action :start
end

#Creating link for socket. ( Mysql failed to start without /tmp/mysql.sock file . So we are creating the link )

execute "#{node[:mysql][:basedir]}/tmp/mysql.sock" do
        command <<-EOH
        cd  /tmp
        ln -s #{node[:mysql][:basedir]}/tmp/mysql.sock .
        EOH
        not_if do File.exists?('/tmp/mysql.sock') end
end

service "mysqld" do
        action :restart
end

##Setting mysql user password

bash "Creating user" do
        code <<-EOH
        #{node['mysql']['basedir']}/bin/mysqladmin -u #{node['mysql']['root-user']} password '#{node['mysql']['root-pass']}'
        echo "user created" > /tmp/mysql
        EOH
        not_if do File.exists?('/tmp/mysql') end
end



#Attribute

default['mysql']['homedir']='/AZVOL'
default['mysql']['basedir']='/AZVOL/mysql'
default['mysql']['bindaddress']='localhost'
default['mysql']['port']='3306'
default['mysql']['user']='mysql'
default['mysql']['masterreplication']='true'
default['mysql']['slavereplication']='false'
default['mysql']['binlog_do_db']='reptest'
default['mysql']['masterone-server-id']=1
default['mysql']['mastertwo-server-id']=2
default['mysql']['slave-server-id']=3
default['mysql']['root-user']='root'
default['mysql']['root-pass']='mysql123'


##My.cnf File

##Mysql Conf
[mysqladmin]
user=<%= node['mysql']['user'] %>

[mysqld]
basedir=<%= node['mysql']['basedir'] %>
datadir=<%= node['mysql']['basedir'] %>/data
port=3306
socket=<%= node['mysql']['basedir'] %>/tmp/mysql.sock
bind-address=<%= node['ipaddress'] %>
skip-name-resolve
key_buffer_size=256M
max_allowed_packet=20M
sort_buffer_size=4M
read_buffer_size=1M
read_rnd_buffer_size=128M
myisam_sort_buffer_size=8M
thread_cache_size=512
innodb_data_home_dir=<%= node['mysql']['basedir'] %>/data
#innodb_log_group_home_dir=/var/lib/mysql/
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
innodb_buffer_pool_size=4096M
innodb_additional_mem_pool_size=512M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size=25M
#innodb_log_buffer_size=128M
#innodb_flush_log_at_trx_commit=1
#innodb_lock_wait_timeout=50
net_buffer_length=1000000
### added by xavier
max_connections=500
wait_timeout = 25000
interactive_timeout=25000
tmp_table_size=24M
max_heap_table_size=24M
read_rnd_buffer_size=4M
join_buffer_size=8M
expire_logs_days = 7
key_buffer_size=64M
query_cache_size=128M
query_cache_limit=128M
log-queries-not-using-indexes
join_buffer_size=1M
#log-slow-queries=/AZVOL/mysql/var/log/slow.log

##Replication conf

<% if node['mysql']['masterreplication']=="true" %>
server-id=<%= node['mysql']['masterone-server-id'] %>
binlog_do_db=<%= node['mysql']['binlog_do_db'] %>
log_bin=<%= node['mysql']['basedir'] %>/mysql-bin.log
<% end %>
<% if node['mysql']['slavereplication']=="true" %>
server-id=<%= node['mysql']['slave-server-id'] %>
binlog_do_db=<%= node['mysql']['binlog_do_db'] %>
log_bin=<%= node['mysql']['basedir'] %>/mysql-bin.log
relay-log=<%= node['mysql']['basedir'] %>/mysql-relay-bin.log
<% end %>

# * Query Cache Configuration
#
#query_cache_limit       = 512M
#query_cache_size        = 512M

[mysqld_safe]
mysqld=mysqld

port=<%= node['mysql']['port'] %>
socket=<%= node['mysql']['basedir'] %>/tmp/mysql.sock
pid-file=<%= node['mysql']['basedir'] %>/tmp/manager.pid
default-mysqld-path=<%= node['mysql']['basedir'] %>/bin/mysqld

Tuesday, 5 May 2015

Killing Process in Windows


#! C:\Perl64\bin
$| = 1;


@s=`tasklist`;
if ( ! ($ARGV[0]))
                {
                chomp($reads=<STDIN>);
                }
        else
                {
                $reads=$ARGV[0];
                }

print "Usage: $0 processname"  if(! "$reads");


for($i=0;$i<@s;$i++)
        {
        if($s[$i] =~ /$reads/i)
                {
                        @processlist=split(" ",$s[$i]);
                        system("TASKKILL /PID $processlist[1] /F");
                        print "<$processlist[1]>";
                }
        }



print "Usage: $0 processname";




Monday, 23 March 2015

Killing process + perl

#!/usr/bin/perl

@s=`ps aux`;

if(! $ARGV[0] )
    {
    print "Pass the arguement \n\n USAGE: pk processname (ex: firefox)\n";
    exit;
    }

foreach $i (@s)
    {
    if(($i=~/$ARGV[0]/i)&&($i!~m/processkill/i))
        {
        print "Killing $ARGV[0] Process\n";
        @processlist=split(" ",$i);
        system("kill -9 $processlist[1]");
        }
    }




scriptname process_name_to_kill (eg firefox )

Sunday, 22 March 2015

Passing stdin and argument for the same variable perl

#!/usr/bin/perl

print "You have not passed arguement , please enter the value\n" if(! "$ARGV[0]");

$s=$ARGV[0]||<STDIN>;

print $s."\n";




Friday, 20 March 2015

Laptop Low battery alert perl , Voice activated

#!/usr/bin/perl
open(FILE,"/proc/acpi/battery/BAT0/state");

while($line=<FILE>)
        {
        if(($line=~/remain/i)&&($line=~/(.*)(\s+)([0-9]{1,9})(.*)/))
                {
                system('espeak -s 100 "Battery is low , please make charge" > /dev/null 2>&1')  if($3<600);

                system('espeak -s 100 "Machine fully drained, Will be down in 2 minutes" > /dev/null 2>&1 ') if($3<100);
                system('espeak -s 100 "Game over Game over Game over" > /dev/null 2>&1 ')  if($3<70);

                system('sudo init 0') if($3<45);

                }
        }
close(FILE);

Thursday, 12 March 2015

FTP upload script

#!/bin/bash
HOST='cis.insdm.net'
USER='bas0sss9_asssm'
PASSWD='asasa2aa02ss42011'

ftp -n -v $HOST << EOT
ascii
user $USER $PASSWD
prompt
put $1
ls -la
bye
EOT


Usage :-  scriptname "file_to_upload"

Sunday, 1 March 2015

Perl Look behind + look ahead

Look behind:

    open(FILE,"passwd");
while($line=<FILE>)
    {
    if($line=~/(?<=lpd\:\/)bin/)
        {
        print $line."\n";
        }
    }
close(FILE);



daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh


 eptuwya@JDQ08R1:~$ perl passwdple
lp:x:7:7:lp:/var/spool/lpd:/bin/sh



Look Ahead:


open(FILE,"passwd");
    while($line=<FILE>)
        {
        if($line=~/bin(?=\/sync)/)
            {
            print $line."\n";
            }
        }
close(FILE);


root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh


eptuwya@JDQ08R1:~$ perl passwdplepost
sync:x:4:65534:sync:/bin:/bin/sync











Tuesday, 24 February 2015

Gnome restart in linux + perl regex

grestart()
{
ps aux | grep -i session | grep -i ubuntu | grep Ssl | grep -v grep
echo "shall i kill [Y/y]"
read a
case $a in
'y'|'Y')
   perl ~/gnome-killer;;   
'n'|'N')
   echo "Ok ";;
*)
  echo "Invalid Input";;
esac
}


cat ~/gnome-killer

@s=`ps aux`;
while($line=pop(@s))
    {
    if($line=~/[0-9]\:[0-9]{2}\s+gnome-session/)
        {
        @killme=split(/\s/,$line);
        system ("sudo kill -9 $killme[3]");
        }
    }