Showing posts with label Bash. Show all posts
Showing posts with label Bash. Show all posts

Wednesday, April 21, 2010

Parallel execution of command in BASH

This script can be used for parallel execution of any command or shell script for faster execution of that command. Say you have a program called prog which process some jpg files. Then you do

parallel -j 3 prog *.jpg

Here 3 prog program will run simultanously
or
parallel -j 3 "prog -r -A=40" *.jpg
to pass args to prog.

Furthermore, -r allows even more sophisticated commands by replacing asterisks in the command string by the argument:
parallel -j 6 -r "convert -scale 50% * small/small_*" *.jpg
I.e. this executes convert -scale 50% file1.jpg small/small_file1.jpg for all the jpg files. This is a real-life example for scaling down images by 50% (requires imagemagick).
Finally, here’s the script. It can be easily manipulated to handle different jobs, too. Just write your command between #DEFINE COMMAND and #DEFINE COMMAND END.

Here is the parallel program
#!/bin/bash
NUM=0
QUEUE=""
MAX_NPROC=2 # default
REPLACE_CMD=0 # no replacement by default
USAGE="A simple wrapper for running processes in parallel.
Usage: `basename $0` [-h] [-r] [-j nb_jobs] command arg_list
  -h  Shows this help
 -r  Replace asterix * in the command string with argument
 -j nb_jobs  Set number of simultanious jobs [2]
 Examples:
  `basename $0` somecommand arg1 arg2 arg3
  `basename $0` -j 3 \"somecommand -r -p\" arg1 arg2 arg3
  `basename $0` -j 6 -r \"convert -scale 50% * small/small_*\" *.jpg"

function queue {
 QUEUE="$QUEUE $1"
 NUM=$(($NUM+1))
}

function regeneratequeue {
 OLDREQUEUE=$QUEUE
 QUEUE=""
 NUM=0
 for PID in $OLDREQUEUE
 do
  if [ -d /proc/$PID  ] ; then
   QUEUE="$QUEUE $PID"
   NUM=$(($NUM+1))
  fi
 done
}

function checkqueue {
 OLDCHQUEUE=$QUEUE
 for PID in $OLDCHQUEUE
 do
  if [ ! -d /proc/$PID ] ; then
   regeneratequeue # at least one PID has finished
   break
  fi
 done
}

# parse command line
if [ $# -eq 0 ]; then #  must be at least one arg
 echo "$USAGE" >&2
 exit 1
fi

while getopts j:rh OPT; do # "j:" waits for an argument "h" doesnt
    case $OPT in
 h) echo "$USAGE"
  exit 0 ;;
 j) MAX_NPROC=$OPTARG ;;
 r) REPLACE_CMD=1 ;;
 \?) # getopts issues an error message
  echo "$USAGE" >&2
  exit 1 ;;
    esac
done

# Main program
echo Using $MAX_NPROC parallel threads
shift `expr $OPTIND - 1` # shift input args, ignore processed args
COMMAND=$1
shift

for INS in $* # for the rest of the arguments
do
 # DEFINE COMMAND
 if [ $REPLACE_CMD -eq 1 ]; then
  CMD=${COMMAND//"*"/$INS}
 else
  CMD="$COMMAND $INS" #append args
 fi
 echo "Running $CMD" 

 $CMD &

 #Change:
 #$CMD &

 #To:
 #eval “$CMD &”

 #If you want to do things like:
 #par.sh ‘tr -d ” ” * > $(basename * .txt)-stripped.txt’ *.txt

 #Without the eval it’ll treat > and $(basename…) as arguments to tr.


 # DEFINE COMMAND END

 PID=$!
 queue $PID

 while [ $NUM -ge $MAX_NPROC ]; do
  checkqueue
  sleep 0.4
 done
done
wait # wait for all processes to finish before exit

Source is at 
http://pebblesinthesand.wordpress.com/2008/05/22/a-srcipt-for-running-processes-in-parallel-in-bash/

Saturday, March 20, 2010

Bash commands from Java: Good way

A string can be executed in the standard java way:
def command = """ping -c1 -W1 hostname""" // Create the String
def proc = command.execute() // Call *execute* on the string
proc.waitFor() // Wait for the command to finish

// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

Tuesday, August 18, 2009

Automatic FTP

Here is a way to automate FTP through script.

#!/bin/sh
stty -echo
read -p "FTP Password: " ftpsecret; echo
stty echo

ftp -n 201.54.111.157 <quote USER myuser
quote PASS $ftpsecret
cd the/directory
binary
hash
ls
mget *
bye
END_SCRIPT

Chopping with BASH

We can use a form of variable expansion to select a specific substring, based on a specific character offset and length. Try typing in the following lines under bash:

$ EXCLAIM=cowabunga
$ echo ${EXCLAIM:0:3}
cow
$ echo ${EXCLAIM:3:7}
abunga

This form of string chopping can come in quite handy; simply specify the character to start from and the length of the substring, all separated by colons.


$ MYVAR=foodforthought .jpg
$ echo ${MYVAR##*fo}
rthought.jpg
$ echo ${MYVAR#*fo}
odforthought.jpg



In the first example, we typed ${MYVAR##*fo}. What exactly does this mean? Basically, inside the ${ }, we typed the name of the environment variable, two ##s, and a wildcard ("*fo"). Then, bash took MYVAR, found the longest substring from the beginning of the string "foodforthought.jpg " that matched the wildcard "*fo", and chopped it off the beginning of the string.

The second form of variable expansion shown above appears identical to the first, except it uses only one "#" -- and bash performs an almost identical process. It checks the same set of substrings as our first example did, except that bash removes the shortest match from our original string, and returns the result. So, as soon as it checks the "fo" substring, it removes "fo" from our string and returns "odforthought.jpg" .

$ MYFOO="chickensoup. tar.gz"
$ echo ${MYFOO%%.*}
chickensoup
$ echo ${MYFOO%.*}
chickensoup.tarAs you can see, the % and %% variable expansion options work identically to # and ##, except they remove the matching wildcard from the end of the string. Note that you don't have to use the "*" character if you wish to remove a specific substring from the end:

MYFOOD="chickensoup "
$ echo ${MYFOOD%%soup}
chicken

In this example, it doesn't matter whether we use "%%" or "%", since only one match is possible.

Wednesday, February 18, 2009

Shell Script To Rename File Name To Lowercase

#!/bin/bash
# Write a shell script that changes the name of the file passed as argument
# to lowercase.
# -------------------------------------------------------------------------
# Copyright (c) 2003 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------

file="$1"
if [ $# -eq 0 ]
then
echo "$(basename $0) file"
exit 1
fi

if [ ! $file ]
then
echo "$file not a file"
exit 2
fi

lowercase=$(echo $file | tr '[A-Z]' '[a-z]'])

if [ -f $lowercase ]
then
echo "Error - File already exists!"
exit 3
fi

# change file name
/bin/mv $file $lowercase

Shell Script To Read File Date - Last Access / Modification Time

#!/bin/bash
# Write a shell script to display / read file date / time in following format:
# Time of last access
# Time of last modification
# Time of last change
# -------------------------------------------------------------------------
# Copyright (c) 2007 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
FILE="$1"

# make sure we got file-name as command line argument
if [ $# -eq 0 ]
then
echo "$0 file-name"
exit 1
fi

which stat > /dev/null

# make sure stat command is installed
if [ $? -eq 1 ]
then
echo "stat command not found!"
exit 2
fi

# make sure file exists
if [ ! -e $FILE ]
then
echo "$FILE not a file"
exit 3
fi

# use stat command to get info
echo "Time of last access : $(stat -c %x $FILE)"
echo "Time of last modification : $(stat -c %y $FILE)"
echo "Time of last change : $(stat -c %z $FILE)"

Shell script to find all programs and scripts with setuid bit set on

#!/bin/bash
# Shell script to find all programs and scripts with setuid bit set on.
# If your system ever cracked (aka hacked) then system has this kind of binary
# installed; besides the normal setuuid scripts/programs
#
# *TIP*
# User directory /home and webroots such as /www canbe mounted with
# nosuid option.
#
# Copyright (c) 2005 nixCraft project.
# This script is licensed under GNU GPL version 2.0 or above
# For more info, please visit:
# http://cyberciti.biz/shell_scripting/bmsinstall.php
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
#SPATH="/usr/local/etc/bashmonscripts"
#INITBMS="$SPATH/defaults.conf"
#[ ! -f $INITBMS ] && exit 1 || . $INITBMS

[ $# -eq 1 ] && : || die "Usage: $($BASENAME $0) directory" 1

DIRNAME="$1"
$FIND $DIRNAME -xdev -type f -perm +u=s -print

Shell script to find all world-writable files and directories on Linux / UNIX system

#!/bin/bash
# Shell script to find all world-writable files and directories on Linux or
# FreeBSD system
#
# TIP:
# Set 'umask 002' so that new files created will not be world-writable
# And use command 'chmod o-w filename' to disable world-wriable file bit
#
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# For more info, please visit:
# http://cyberciti.biz/shell_scripting/bmsinstall.php
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
#SPATH="/usr/local/etc/bashmonscripts"
#INITBMS="$SPATH/defaults.conf"
#[ ! -f $INITBMS ] && exit 1 || . $INITBMS

[ $# -eq 1 ] && : || die "Usage: $($BASENAME $0) directory" 1

DIRNAME="$1"
$FIND $DIRNAME -xdev -perm +o=w ! \( -type d -perm +o=t \) ! -type l -print

Monitor UNIX / Linux Server Disk Space with Shell Script

#!/bin/sh
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free avilable) percentage
# of space is >= 90%
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# Linux shell script to watch disk space (should work on other UNIX oses )
# SEE URL: http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html
# set admin email so that you can get email
ADMIN="me@somewher.com"
# set alert level 90% is default
ALERT=90
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
#echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $ALERT ]; then
echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
mail -s "Alert: Almost out of disk space $usep" $ADMIN
fi
done

Shell Script accept password using read commnad

#!/bin/bash
# Script accept password using read commnad
# Not *very secure*, this script is for learning purpose only
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
PASS="abc123"
read -s -p "Password: " mypassword
echo ""
[ "$mypassword" == "$PASS" ] && echo "Password accepted" || echo "Access denied"

Script to update user password in batch mode

#!/bin/bash
# Script to update user password in batch mode
# You must be a root user to use this script
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# /root is good place to store clear text password
FILE="/root/batch.passwd"

# get all non-root user account
# By default on most linux non-root uid starts
# from 1000
USERS=$(awk -F: '{ if ( $3 > 1000 ) print $1}' /etc/passwd)

# create file with random password
echo "Generating file, please wait..."

# overwrite file, this is bash specific a better solution is cat > $FILE
>$FILE

for u in $USERS
do
p=$(pwgen -1 -n 8) # create random password
echo "$u:$p" >> $FILE # save USERNAME:PASSWORD pair
done
echo ""
echo "Random password and username list stored in $FILE file"
echo "Review $FILE file, once satisfied execute command: "
echo "chpasswd < $FILE"

# Uncomment following line if you want immediately update all users password,
# be careful with this option, it is recommended that you review $FILE first
# chpasswd < $FILE

Shell Script to read source file and copy it to target file

#!/bin/bash
# Shell to read source file and copy it to target file. If the file
# is copied successfully then give message 'File copied successfully'
# else give message 'problem copying file'
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------

echo -n "Enter soruce file name : "
read src
echo -n "Enter target file name : "
read targ

if [ ! -f $src ]
then
echo "File $src does not exists"
exit 1
elif [ -f $targ ]
then
echo "File $targ exist, cannot overwrite"
exit 2
fi

# copy file
cp $src $targ

# store exit status of above cp command. It is use to
# determine if shell command operations is successful or not
status=$?

if [ $status -eq 0 ]
then
echo 'File copied successfully'
else
echo 'Problem copuing file'
fi

Menu Driven Shell Script

A menu driven Shell script which has following options
# Contents of /etc/passwd
# List of users currently logged
# Prsent handling directory
# Exit
# As per option do the job
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------

while :
do
clear
echo " M A I N - M E N U"
echo "1. Contents of /etc/passwd"
echo "2. List of users currently logged"
echo "3. Prsent handling directory"
echo "4. Exit"
echo -n "Please enter option [1 - 4]"
read opt
case $opt in
1) echo "************ Conents of /etc/passwd *************";
more /etc/passwd;;
2) echo "*********** List of users currently logged";
who | more;;
3) echo "You are in $(pwd) directory";
echo "Press [enter] key to continue. . .";
read enterKey;;
4) echo "Bye $USER";
exit 1;;
*) echo "$opt is an invaild option. Please select option between 1-4 only";
echo "Press [enter] key to continue. . .";
read enterKey;;
esac
done

Script to convert numbers into equivalent words

#!/bin/bash
# Shell script to read a number and write the number in words. Use case
# control structure. For example 12 should be print as one two
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------

echo -n "Enter number : "
read n

len=$(echo $n | wc -c)
len=$(( $len - 1 ))

echo "Your number $n in words : "
for (( i=1; i<=$len; i++ ))
do
# get one digit at a time
digit=$(echo $n | cut -c $i)
# use case control structure to find digit equivalent in words
case $digit in
0) echo -n "zero " ;;
1) echo -n "one " ;;
2) echo -n "two " ;;
3) echo -n "three " ;;
4) echo -n "four " ;;
5) echo -n "five " ;;
6) echo -n "six " ;;
7) echo -n "seven " ;;
8) echo -n "eight " ;;
9) echo -n "nine " ;;
esac
done

# just print new line
echo ""

Script To Count Number Of Files In Each Subdirectories

#!/bin/bash
# Write a script that will count the number of files in each of your subdirectories.
# -------------------------------------------------------------------------
# Copyright (c) 2001 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------

START=$HOME

# change your directory to command line if passed
# otherwise use home directory
[ $# -eq 1 ] && START=$1 || :

if [ ! -d $START ]
then
echo "$START not a directory!"
exit 1
fi

# use find command to get all subdirs name in DIRS variable
DIRS=$(find "$START" -type d)

# loop thought each dir to get the number of files in each of subdir
for d in $DIRS
do
[ "$d" != "." -a "$d" != ".." ] && echo "$d dirctory has $(ls -l $d | wc -l) files" || :
done

Finding ALL Superuser ( root ) Accounts under UNIX

Find all root power account using below command

grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}'

Shell script for search for no password entries and lock all accounts

#!/bin/bash
# Shell script for search for no password entries and lock all accounts
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# Set your email
ADMINEMAIL="admin@somewhere.com"

### Do not change anything below ###
#LOG File
LOG="/root/nopassword.lock.log"
STATUS=0
TMPFILE="/tmp/null.mail.$$"

echo "-------------------------------------------------------" >>$LOG
echo "Host: $(hostname), Run date: $(date)" >> $LOG
echo "-------------------------------------------------------" >>$LOG

# get all user names
USERS="$(cut -d: -f 1 /etc/passwd)"

# display message
echo "Searching for null password..."
for u in $USERS
do
# find out if password is set or not (null password)
passwd -S $u | grep -Ew "NP" >/dev/null
if [ $? -eq 0 ]; then # if so
echo "$u" >> $LOG
passwd -l $u #lock account
STATUS=1 #update status so that we can send an email
fi
done
echo "========================================================" >>$LOG
if [ $STATUS -eq 1 ]; then
echo "Please see $LOG file and all account with no password are locked!" >$TMPFILE
echo "-- $(basename $0) script" >>$TMPFILE
mail -s "Account with no password found and locked" "$ADMINEMAIL" < $TMPFILE
# rm -f $TMPFILE
fi

Note: http://bash.cyberciti.biz/security/script-to-lock-all-passwordless-accounts/