How to set ansible playbook to run with kornshell - ansible

Writing ansible-playbook, to start a kornshell script.
How to set ansible to run kornshell in specific server?
---
- name: Start server manager agent
hosts: 192.168.1.85
become: yes
become_user: jde920
tasks:
- name: Set ksh
shell: ksh (not sure how to set here)
- name: start Agent
async: 10
poll: 0
shell: "./startAgent"
args:
chdir: "/u01/jde_home/SCFHA/bin/"
- name: Wait for 5 seconds
wait_for:
timeout: 5
- name: Start Service
async: 10
poll: 0
#ansible_shell_executable: ksh
shell: "./RunOneWorld.sh"
args:
chdir: "/u01/jdedwards/e920/system/bin32/"
- name: Validate Service is up
tags: JDE_Enterprise
wait_for:
host: "localhost"
port: 6017
delay: 20
timeout: 60
state: started
msg: "JDE Enterprise Service is not Running"
I managed to find the file that set the environment $SYSTEM, following is the code. Script file name is call enterpriseone.sh
# Following has to be replaced in this file:
#
# ORACLE_HOME (if Oracle is installed)
# DB2DIR (if DB2 is installed)
# DB2INSTANCE name of user owning DB2 instance
# File Updated Tue Mar 05 16:37:23 MYT 2019 - TR 9.2.3
OS_NAME=`uname -s`
EVRHOME=/u01/jdedwards/e920
export EVRHOME
DB2INSTANCE=
export DB2INSTANCE
DB2DIR=
export DB2DIR
DB2BASEDIR=
export DB2BASEDIR
ORCL_USER_ACCT=
export ORCL_USER_ACCT
ORACLE_HOME=/u01/oracle/product/12.1.0/client_1
export ORACLE_HOME
ORACLE_SID=e1db
export ORACLE_SID
set +u
SYSTEM=$EVRHOME/system
export SYSTEM
APPDEV=$EVRHOME/appdev
export APPDEV
#
# Location of INI files
JDE_BASE=$EVRHOME/ini
export JDE_BASE
## Set the binary folder to 32 or 64 bit based on the setup configuration
if [ $OS_NAME = "HP-UX" ]; then
BUILDTYPE=$(file $SYSTEM/lib/libjdenet.so | grep 'ELF-64')
else
BUILDTYPE=$(file $SYSTEM/lib/libjdenet.so | grep '64-bit')
fi
if [ -n "$BUILDTYPE" ]; then
BIN_FOLDER=bin64
else
BIN_FOLDER=bin32
fi
PATH=$PATH:$SYSTEM/$BIN_FOLDER
export PATH
ICU_DATA=$SYSTEM/locale/xml/
export ICU_DATA
ACRO_RES_DIR=$SYSTEM/resource/cmap
export ACRO_RES_DIR
PSRESOURCEPATH=$SYSTEM/resource/cidfont:$ACRO_RES_DIR
export PSRESOURCEPATH
#
# Call tools service pack specific environment variable
# setup script. This script is required for running
# the enterprise server. If this script does not exist
# in your $SYSTEM/$BIN_FOLDER directory, the E1 Tools Release
# may need to be updated to a newer version.
if [ -f ${SYSTEM}/$BIN_FOLDER/toolsenv.sh ] ; then
. ${SYSTEM}/$BIN_FOLDER/toolsenv.sh
fi
Below is the actual shell script (RunOneWorld.sh) that I use ansible to call:
## Set the binary folder to 32 or 64 bit based on the setup configuration
OS_NAME=`uname -s`
if [ $OS_NAME = "HP-UX" ]; then
BUILDTYPE=$(file $SYSTEM/lib/libjdenet.so | grep 'ELF-64')
else
BUILDTYPE=$(file $SYSTEM/lib/libjdenet.so | grep '64-bit')
fi
if [ -n "$BUILDTYPE" ]; then
BIN_FOLDER=bin64
else
BIN_FOLDER=bin32
fi
LOGFILE=$SYSTEM/$BIN_FOLDER"/startstop.log"
## Set START_NEW_LOGFILE=1 if you want to rewrite the logfile at each startup
START_NEW_LOGFILE=0
CLEAR_LOGS=1
## Set MULTI_INSTANCE=1 if you are running multiple instances of OneWorld
## under the same Unix user id.
MULTI_INSTANCE=0
set +u
USER=$(whoami)
HOST=$(hostname)
OSTYPE=$(uname)
## On AIX, process id shows up in column 2, it's column 1 on others...
if [ $OSTYPE = "AIX" ]
then
COLUMN=2
else
COLUMN=1
fi
unset SILENT_MODE
if [ "$1" = "-s" ] ; then
SILENT_MODE=1
fi
## In MULTI_INSTANCE mode, we need to be able to find the INI file to get
## certain settings. If we can't, then exit with an error.
if [ "$MULTI_INSTANCE" = "1" ] ; then
MFLAG="-m"
if [ -f ./JDE.INI ] ; then
PORT_NBR=$(grep "^serviceNameListen" ./JDE.INI | sed 's/.*=//')
elif [ -f $JDE_BASE/JDE.INI ] ; then
PORT_NBR=$(grep "^serviceNameListen" $JDE_BASE/JDE.INI | sed 's/.*=//')
else
if [ -z "$SILENT_MODE" ] ; then
print " This script cannot support multiple instances of"
print " OneWorld without access to a JDE.INI file."
print " You must either set the $JDE_BASE environment"
print " variable correctly, or turn off MULTI_INSTANCE"
print " mode in the RunOneWorld.sh script."
print " exiting..."
fi
print " This script cannot support multiple instances of" >> $LOGFILE
print " OneWorld without access to a JDE.INI file." >> $LOGFILE
print " You must either set the $JDE_BASE environment" >> $LOGFILE
print " variable correctly, or turn off MULTI_INSTANCE" >> $LOGFILE
print " mode in the RunOneWorld.sh script." >> $LOGFILE
print " exiting..." >> $LOGFILE
exit 1
fi
fi
#---------------------------------------------------------------------- #
# FUNCTION DEFINITIONS...
#---------------------------------------------------------------------- #
function GetPIDS
{
if [ "$MULTI_INSTANCE" = "1" ]
then
PIDS=$(ps -ef | grep $USER | grep $PORT_NBR | grep -v grep | awk '{print $2}')
PIDS="$(ps -ef | grep $USER | grep $SYSTEM | grep -v grep | awk '{print $2}') $PIDS"
else
PIDS=$(ps -u $USER | grep jdenet | awk '{print $'$COLUMN'}')
fi
if [ "$PIDS" = " " ] ; then
PIDS=""
fi
}
function CheckForProcesses
{
GetPIDS
if [ -n "$PIDS" ] ; then
if [ -z "$SILENT_MODE" ] ; then
print " There are already OneWorld processes"
print " running for this user / instance..."
print " exiting..."
fi
print " There are already OneWorld processes" >> $LOGFILE
print " running for this user / instance..." >> $LOGFILE
print " exiting..." >> $LOGFILE
exit 1
fi
}
function CheckIPC
{
$SYSTEM/$BIN_FOLDER/rmics.sh $MFLAG >> $LOGFILE
if [ ! $? = 0 ] ; then
if [ -z "$SILENT_MODE" ] ; then
print " IPC resource conflict -"
print " You may need to change the startIPCKeyValue in your INI file,"
print " or your JDE_BASE environment variable may be set incorrectly."
print " exiting..."
fi
## (error message already written to $LOGFILE by rmics.sh)
exit 1
fi
}
#---------------------------------------------------------------------- #
# MAIN PROCESSING...
#---------------------------------------------------------------------- #
## First, let's make sure the log file directory is valid - otherwise, all
## of the log messages will disappear.
LOGDIR=$(dirname $LOGFILE)
if [ ! -d $LOGDIR ] ; then
print " Invalid directory name for LOGFILE - "
print " $LOGDIR"
print " You must correct RunOneWorld.sh and retry."
exit 1
fi
if [ "$START_NEW_LOGFILE" = "1" ] ; then
rm $LOGFILE
fi
if [ "$CLEAR_LOGS" = "1" ] ; then
## If the log directory is a link, figure out what it points to...
if [ -L $EVRHOME/log ]; then
REAL_LOGDIR=$(ls -l $EVRHOME/log | awk '{print $NF}')
else
REAL_LOGDIR=$EVRHOME/log
fi
rm -rf $REAL_LOGDIR.prev
mv $REAL_LOGDIR $REAL_LOGDIR.prev
mkdir $REAL_LOGDIR
fi
print "**********************************************************" >> $LOGFILE
if [ ! $? = 0 ] ; then
print " Unable to write to the logfile - "
print " $LOGFILE"
print " You might not have permission to write to this file or directory."
print " Make sure file permissions are set correctly and retry."
exit 1
fi
if [ -z "$SILENT_MODE" ] ; then
print "$(date) Starting JD Edwards OneWorld on $HOST"
fi
print "$(date) Starting JD Edwards OneWorld on $HOST" >> $LOGFILE
CheckForProcesses
if [ ! "$1" = "-n" ] ; then
CheckIPC
fi
print " Starting jdenet_n..." >> $LOGFILE
cd $SYSTEM/$BIN_FOLDER
$SYSTEM/$BIN_FOLDER/jdenet_n > $SYSTEM/$BIN_FOLDER/jdenet_n.log 2>&1 &
sleep 2
GetPIDS
if [ -z "$PIDS" ] ; then
if [ -z "$SILENT_MODE" ] ; then
print " The jdenet_n process did not start..."
print " Check the jdenet_n.log, or the log file associated"
print " with the jdenet_n process id."
fi
print " The jdenet_n process did not start..." >> $LOGFILE
print " Check the jdenet_n.log, or the log file associated" >> $LOGFILE
print " with the jdenet_n process id." >> $LOGFILE
exit 1
fi
print " Running cleanup to check for unfinished jobs..." >> $LOGFILE
$SYSTEM/$BIN_FOLDER/cleanup &
if [ -z "$SILENT_MODE" ] ; then
print "\n$(date) JD Edwards OneWorld startup complete.\n"
fi
print "\n$(date) JD Edwards OneWorld startup complete.\n" >> $LOGFILE
exit 0
SO in order to start the service, I will just do command as follow:
cd $SYSTEM/bin32
./RunOneWorld.sh

For shell module, use the executable parameter instead
- name: Start Service
async: 10
poll: 0
shell: "./RunOneWorld.sh"
args:
chdir: "/u01/jdedwards/e920/system/bin32/"
executable: /bin/ksh

I have changed accordingly to the following, but the script still doesn't run.
---
- name: Start server manager agent
hosts: 192.168.1.85
become: yes
become_user: jde920
tasks:
- name: start Agent
async: 10
poll: 0
shell: "./startAgent"
args:
chdir: "/u01/jde_home/SCFHA/bin/"
- name: Wait for 5 seconds
wait_for:
timeout: 5
- name: Start JDE Enterprise Service
async: 10
poll: 0
shell: "./RunOneWorld.sh"
args:
chdir: "/$SYSTEM/bin32/"
executable: /usr/bin/ksh
- name: Validate JDE Enterprise Service is up
tags: JDE_Enterprise
wait_for:
host: "localhost"
port: 6017
delay: 20
timeout: 60
state: started
msg: "JDE Enterprise Service is not Running"
I tried to manually verified and it runs in the actual server.
$ /usr/bin/ksh /$SYSTEM/bin32/RunOneWorld.sh
Wed Apr 15 14:17:03 +08 2020 Starting JD Edwards OneWorld on CBD2ELENT
Wed Apr 15 14:17:05 +08 2020 JD Edwards OneWorld startup complete.

Related

How to execute ksh script from bash

I currently have a ksh script which invokes another ksh script. The "parent" ksh script needs to be invoked from a bash shell in the context of the ksh shell user. Trying the following throws back this error message
As user root in the bash shell
su - whics -c '/usr/bin/nohup /whics/t99/wv.4gm/wv99b.4gs/wv99b.sh -s 1 -m u -sleep 5 > ./nohup.out &'
/whics/t99/wv.4gm/wv99b.4gs/wv99b.sh[8]: .: wh_setENV.sh: cannot open [No such file or directory]
wh_setENV.sh is actually in /whics/t99/bin
However, when running the below commands in order I do not get this error
server:~ su - whics
server:/whics/t99 cd ./wv.4gm/wv99b.4gs
server:/whics/t99/wv.4gm/wv99b.4gs nohup ./wv99b.sh -s 1 -m u -sleep 5 &
server:/whics/t99/wv.4gm/wv99b.4gs nohup: ignoring input and appending output to `/home/whics/nohup.out'
[1] + Done nohup ./wv99b.sh -s 1 -m u -sleep 5 &
server:/whics/t99/wv.4gm/wv99b.4gs cat /home/whics/nohup.out Mon Sep 17 12:27:40 AEST 2018 : Start wv99b
wv99b.sh
#!/bin/ksh
# Copyright (C) 1992-1997 Wacher Pty. Limited
# Sccsid: %Z% %M%%Y% %Q%%I% %E%
myname=${0##*/} # a useful identifying variable
mydir=${0%$myname} # where this script is
vSFX=${myname##*.}
. wh_setENV.sh # P4813 - when using 4js:WebServices, the $fglidir/lib in LD_LIBRARY_PATH causes problems
test $debugxv && set -xv
#--------------------------------------------------------------------------------------------------------------------------------------#
wv99b_msg() {
vERR="`date` : ${vMSG}"
echo $vERR | tee -a ${vLOG}
}
#--------------------------------------------------------------------------------------------------------------------------------------#
wv99b_sysFragments() {
vSYSFRAGOK="0"
vSYSFRAGMENTS="${vTABNAME}.sysfrags.unl" ; rm -f $vSYSFRAGMENTS
$WH_ISQL $company - <<! 2>/dev/null | sed "/exprtext/d;/^$/d;s/ //g;s/[()]//g" |cut -f1 -d'=' >| ${vSYSFRAGMENTS}
select F.exprtext
from systables S, sysfragments F
where S.tabid > 99
and S.tabtype = "T"
and S.tabname = "${vTABNAME}"
and S.tabid = F.tabid
and S.tabtype = F.fragtype
and F.evalpos = 0
;
!
if [ -s ${vSYSFRAGMENTS} ] ; then
# search for the vCOLUMN in the vSYSFRAGMENTS output
vSYSFRAGOK=`grep -i ${vKEY} ${vSYSFRAGMENTS} 2>/dev/null | wc -l | awk '{print $1}'`
else
vSYSFRAGOK="0"
rm -f ${vSYSFRAGMENTS} # cleanup
fi
}
# MAIN #
vARGS="$#"
vHERE=`pwd`
vLOG="${vHERE}/errlog"
vD=0 # debug indicator
vI=0 # infile indicator
vQ=0 # email indicator
vM=0 # mode indicator
vS=0 # serial indicator
vNO_MULTI=0 # default to false
vNO_PROGI=0 # default to false
vTABLE=0 # default to 0
vSLEEP=5 # default to 0
for i in $vARGS
do
case "$i" in
-debug) vD=$2 ;;
-infile) vI=$2 ;;
-table) vTABLE=$2 ;;
-sleep) vSLEEP=$2 ;;
-no_multi) vNO_MULTI=$2 ;;
-no_progi) vNO_PROGI=$2 ;;
-m) vM=$2 ;;
-q) vQ=$2 ;;
-s) vS=$2 ;;
esac
shift
done
[[ ${vS} -eq 0 ]] && vMSG="-s parameter not supplied" && wv99b_msg && exit 1
vHERE=`pwd`
if [ ${vD} -eq 1 ] ; then
vDEBUG=" -debug 1"
else
vDEBUG=""
fi
if [ ${vI} -eq 0 ] ; then
vINFILE="wv99b.in"
else
vINFILE="${vI}"
fi
# INIT
vWVI="wv99b_I" # the name of the (I)dentify script
vWVIS="${vWVI}_${vS}" # the name of the (I)dentify script PLUS SERIAL
vWVIO="${vWVIS}.unl" # the name of the (I)dentify script
rm -f ${vWVIO}
# Check that transaction-logging is off
# check that vINFILE exists
if [ ! -s "${vINFILE}" ] ; then
vMSG="Error cannot read input file $vINFILE" ; wv99b_msg ; exit 1
fi
# Process only one(1) table
if [ ${vTABLE} != "0" ] ; then
vTABLE_FILTER=" -table ${vTABLE} "
else
vTABLE_FILTER=""
fi
# We need to check if we are running client/server
#
vDB=`echo $company | awk 'BEGIN {FS="#" } { print $1 }'`
vDBSRV=`echo $company | awk 'BEGIN {FS="#" } { print $2 }'`
case X${vDBSRV}X in
XX) vREMOTE_DB="" ;;
*) vREMOTE_DB=" -db ${vDB} -dbsrv ${vDBSRV} " ;;
esac
#_end
vMSG="Start wv99b" ; wv99b_msg
So in the wv99b.sh file, I changed
. wh_setENV.sh
to
. /whics/t99/bin/wh_setENV.sh
However, now I get the error
cannot read input file wv99b.in
I checked wv99b.in and it is in the same directory as 'wv99b.sh' (i.e. /whics/t99/wv.4gm/wv99b.4gs/ )
wh_setENV.sh
#!/usr/bin/ksh
test $debugxv && set -xv
trap door 1 2 3 5 9 15
#---------------------------------------------------------------------#
door() {
echo "`date` ERROR($?) occured in $0" >> $WH/batch.4gm/trap.log
} #end door
#---------------------------------------------------------------------#
# Script to set Environment variables for various scripts
# Stef
# Unix specific
umask 002
: ${WH:="/whics/prod"}
set -a
TERM=xterm
vHERE=`pwd`
TERMCAP=$WH/etc/termcap
vHOST=`hostname | cut -f1 -d'.'`
set +a
#LD_LIBRARY_PATH="$WH/lib.4gm/S_lib:$fglibdir/S_lib" # GUC R481
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$INFORMIXDIR/lib/c++:$INFORMIXDIR/lib/cli:$INFORMIXDIR/lib/client:$INFORMIXDIR/lib/csm:$INFORMIXDIR/lib/dmi"
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$INFORMIXDIR/lib:$INFORMIXDIR/lib/esql:$INFORMIXDIR/lib/tools.$CCODE"
export LD_LIBRARY_PATH
# EOF #
UPDATE: After OP modified/updated the question ...
wv99b.in is referenced in wv99b.sh
you don't provide the path for wv99b.in so ...
if you invoke wv99b.sh from some directory other than /whics/t99/wv.4gm/wv99b.4gs ...
when you run your test [ ! -s "${vINFILE}" ] your script (correctly) determines that "${vINFILE}" is not located in the directory where you invoked wv99b.sh from
Net result ... the original problem with sh_setENV.sh has been fixed but now the same exact problem is occurring for wv99b.in, with the same solution needed here ... invoke wv99b.sh from its home directory or provide the full path to wv99b.in.
ORIGINAL POST:
Expanding on Andre's comment ...
In wv99b.sh you have the following line:
. wh_setENV.sh
This is going to look for wh_setENV.sh in the directory where wv99b.sh is invoked from.
In your original example you've provided the full path to wv99b.sh but the question is ... what directory is that call invoked from? We can tell from the error ...
wh_setENV.sh: cannot open [No such file or directory]
... that wv99b.sh was not invoked from /whics/t99/wv.4gm/wv99b.4gs otherwise it would have found wh_setENV.sh.
From your second example it appears that the full path to wh_setENV.sh is: /whics/t99/wv.4gm/wv99b.4gs/wh_setENV.sh so you have a couple options:
in your initial example make sure you cd /whics/t99/wv.4gm/wv99b.4gs before executing wv99b.4gs
or
update wv99b.4gs to include the full path to the location of sh_setENV.sh, eg:
. /whics/t99/wv.4gm/wv99b.4gs/wh_setENV.sh

Delete first line/chars on Windows Pipe

I'm trying to capture a live tcpdump from a custom designed linux system. The command I'm using so far is:
plink.exe -ssh user#IP -pw PW "shell nstcpdump.sh -s0 -U -w - not port 22 and not host 127.0.0.1" | "C:\Program Files\Wireshark\wireshark" -i -
This will fail since when executing the command on the remote system, this (custom) shell will output "Done" before sending data. I tried to find out a way to remove the "Done" message from the shell but doesn't appear to be any.
So I came up with this (added findstr -V):
plink.exe -ssh user#IP -pw PW "shell nstcpdump.sh -s0 -U -w - not port 22 and not host 127.0.0.1" | findstr -V "Done" | "C:\Program Files\Wireshark\wireshark" -i -
This works more or less fine since I will get some errors and the live capture will stop. I believe it might have something to do with the buffers, but I'm not sure.
Does anyone know of any other method of removing/bypassing the first bytes/chars of the output from plink/remote shell?
[edit]
as asked, nstcpdump.sh is a wrapper for tcpdump. as mentioned before, this system is highly customized. nstcpdump.sh code:
root#hostname# cat /netscaler/nstcpdump.sh
#!/bin/sh
# piping the packet trace to the tcpdump
#
# FILE: $Id: //depot/main/rs_120_56_14_RTM/usr.src/netscaler/scripts/nstcpdump.sh#1 $
# LAST CHECKIN: $Author: build $
# $DateTime: 2017/11/30 02:14:38 $
#
#
# Options: any TCPDUMP options
#
TCPDUMP_PIPE=/var/tmp/tcpdump_pipe
NETSCALER=${NETSCALER:-`cat /var/run/.NETSCALER`}
[ -r ${NETSCALER}/netscaler.conf ] && . ${NETSCALER}/netscaler.conf
TIME=${TIME:-3600}
MODE=${MODE:-6}
STARTCMD="start nstrace -size 0 -traceformat PCAP -merge ONTHEFLY -filetype PIPE -skipLocalSSH ENABLED"
STOPCMD="stop nstrace "
SHOWCMD="show nstrace "
NSCLI_FILE_EXEC=/netscaler/nscli
NSTRACE_OUT_FILE=/tmp/nstrace.out
NS_STARTTRACE_PIDFILE=/tmp/nstcpdump.pid
TRACESTATE=$(nsapimgr -d allvariables | grep tracestate | awk '{ print $2}')
trap nstcpdump_exit 1 2 15
nstcpdump_init()
{
echo "##### WARNING #####"
echo "This command has been deprecated."
echo "Please use 'start nstrace...' command from CLI to capture nstrace."
echo "trace will now start with all default options"
echo "###################"
if [ ! -d $NSTRACE_DIR ]
then
echo "$NSTRACE_DIR directory doesn't exist."
echo "Possible reason: partition is not mounted."
echo "Check partitions using mount program and try again."
exit 1
fi
if [ ! -x $NSCLI_FILE_EXEC ]
then
echo "$NSCLI_FILE_EXEC binary doesn't exist"
exit 1
fi
if [ -e $NSTRACE_OUT_FILE ]
then
rm $NSTRACE_OUT_FILE
echo "" >> $NSTRACE_OUT_FILE
fi
}
nstcpdump_start_petrace()
{
sleep 0.5;
$NSCLI_FILE_EXEC -U %%:.:. $STARTCMD >/tmp/nstcpdump.sh.out
rm -f ${NS_STARTTRACE_PIDFILE}
}
nstcpdump_start()
{
# exit if trace is already running
if [ $TRACESTATE -ne 0 ]
then
echo "Error: one instance of nstrace is already running"
exit 2
fi
nstcpdump_start_petrace &
echo $! > ${NS_STARTTRACE_PIDFILE}
tcpdump -n -r - $TCPDUMPOPTIONS < ${TCPDUMP_PIPE}
nstcpdump_exit
exit 1
}
nstcpdump_exit()
{
if [ -f ${NS_STARTTRACE_PIDFILE} ]
then
kill `cat ${NS_STARTTRACE_PIDFILE}`
rm ${NS_STARTTRACE_PIDFILE}
fi
$NSCLI_FILE_EXEC -U %%:.:. $STOPCMD >> /dev/null
exit 1
}
nstcpdump_usage()
{
echo `basename $0`: utility to view/save/sniff LIVE packet capture on NETSCALER box
tcpdump -h
echo
echo NOTE: tcpdump options -i, -r and -F are NOT SUPPORTED by this utility
exit 0
}
########################################################################
while [ $# -gt 0 ]
do
case "$1" in
-h )
nstcpdump_usage
;;
-i )
nstcpdump_usage
;;
-r )
nstcpdump_usage
;;
-F )
nstcpdump_usage
;;
esac
break;
done
TCPDUMPOPTIONS="$#"
check_ns nstcpdump
#nstcpdump_init
#set -e
if [ ! -e ${TCPDUMP_PIPE} ]
then
mkfifo $TCPDUMP_PIPE
if [ $? -ne 0 ]
then
echo "Failed creating pipe [$TCPDUMP_PIPE]"
exit 1;
fi
fi
nstcpdump_start
Regards

how to run multiple commands on a remote linux server using bash script

I am currently writing the following script that logs into a remote server and runs couple of commands to verify the performance of the server and prints a message based on the output of those commands .But the ssh doesn't work and returns the stats of the server that hosts the script instead .
Script
#!/bin/bash
#######################
#Function to add hosts to the array
#the following function takes the ip addresses provided while the script is run and stores them in an array
#######################
Host_storing_func () {
HOST_array=()
for i in $# ;do
HOST_array+=(${i});
done
#echo ${HOST_array[*]}
}
#######################
#Calling above function
#######################
Host_storing_func "$#"
############################################################
#Collect Stats of Ping,memory,iowait time test function
############################################################
b=`expr ${#HOST_array[*]} - 1 `
for i in `seq 0 $b` ;do
sshpass -f /root/scripts/passwordFile.txt /usr/bin/ssh student35#${HOST_array[${i}]} << HERE
echo `hostname`
iowaittm=`sar 2 2|awk '/^Average/{print $5};'`
if [ $iowaittm > 10 ];then
echo "IO ==> BAD"
else
echo "IO ==> GOOD"
fi
memoryy=`free -m |grep Swap|awk '{if($2 == 0) print 0;else print (($4 / $2 ) * 100)}'`
if [ ${memoryy} < '10' ] ;then
echo "memory ==> good"
elif [[ "${memory}" -ge 0 ]] && [[ "${memory}" -le 10 ]];then
echo "No Swap"
else
echo "memory ==> bad"`enter code here`
fi
ping -w2 -c2 `hostname` | grep "packet loss"|awk -F, '{print $3}'|awk -F% '{print $1}'|sed 's/^ *//'|awk '{if ($1 == 0) print "Yes" ;else print "No"}'
HERE
done
Output : oc5610517603.XXX.com is the name of the source server
[root#oc5610517603 scripts]# ./big_exercise.sh 9.XXX.XXX.XXX 9.XXX.XXX.XXX
Pseudo-terminal will not be allocated because stdin is not a terminal.
oc5610517603.XXX.com
IO ==> GOOD
No Swap
ping: oc5610517603.ibm.com: Name or service not known
Pseudo-terminal will not be allocated because stdin is not a terminal.
oc5610517603.XXX.com
IO ==> GOOD
No Swap
ping: oc5610517603.XXX.com: Name or service not known
thanks for checking the script , I figured out a way to solve the problem
It is the sshpass command that is causing issue , you just have to put the opening HERE in single quotes if you want to use variables with in the HEREdoc but if the variables are calculated before ssh then you don't have to put opening HERE in single quotes
sshpass -f /root/scripts/passwordFile.txt /usr/bin/ssh -T student35#${i} << 'HERE'
after I changed the sshpass command as above my script worked
I have modified your script a bit.
As suggested by #chepner, I am not using the Host_storing_func.
Heredocs for sshpaas are somewhat tricky. You have to escape every back-tick and $ sign in the heredoc.
Notice the - before the heredoc start, it allows you to indent the heredoc body. Also, try to avoid back-ticks when you can. use $(command) instead.
Hope it helps.
#!/bin/bash
#######################
#Function to add hosts to the array
#the following function takes the ip addresses provided while the script is run and stores them in an array
#######################
array=( "$#" )
user="student35"
############################################################
#Collect Stats of Ping,memory,iowait time test function
############################################################
for host in ${array[#]}; do
sshpass -f /root/scripts/passwordFile.txt /usr/bin/ssh -l ${user} ${host} <<-HERE
thishost=\$(hostname)
echo "Current Host -> \$thishost";
iowaittm=\`sar 2 2|awk '/^Average/{print \$5}'\`
if [ \$iowaittm > 10 ]; then
echo "IO ==> BAD"
else
echo "IO ==> GOOD"
fi
memory=\$(free -m | grep Swap | awk '{if(\$2 == 0) print 0;else print ((\$4 / \$2 ) * 100)}')
if [ \${memory} < '10' ] ;then
echo "memory ==> good"
elif [[ "\${memory}" -ge 0 ]] && [[ "\${memory}" -le 10 ]]; then
echo "No Swap"
else
echo "memory ==> bad"\`enter code here\`
fi
ping -w2 -c2 \`hostname\` | grep "packet loss"|awk -F, '{print \$3}'|awk -F% '{print \$1}'|sed 's/^ *//'|awk '{if (\$1 == 0) print "Yes" ;else print "No"}'
HERE
done

notify-send from within a bash script

I'd like to use notify-send from within a bash script that is running in the background to inform the user about the progress of the script. More specifically this is a script that automagically runs when a USB flash drive is inserted and runs a scan with ClamAV.
Specifically at line 30 and line 66. So far, I'm not having any luck. Can someone give me some advice/help? Thanks.
#!/bin/bash
#doOnUSBinsert_0.2.sh
#Author : Totti
# Make it executable by running 'sudo chmod x doOnUSBinsert_0.2.sh'
if ! [ -f /etc/udev/rules.d/80-doOnUSBinsert.rules ]
then # rule not added
cp "$0" /usr/bin/doOnUSBinsert
chmod u x /usr/bin/doOnUSBinsert
# echo 'SUBSYSTEM=="usb", ACTION=="add", RUN ="/path/to/script.sh"' | sudo tee /etc/udev/rules.d/80-clamscan.rules
echo 'SUBSYSTEM=="usb", ACTION=="add", RUN ="/usr/bin/doOnUSBinsert & "' | tee /etc/udev/rules.d/80-doOnUSBinsert.rules
if [ $? -eq 0 ]
then
echo 'Rule Successfully added. See file "/usr/bin/doOnUSBinsert" if you wish to edit the command'
exit 0
else
echo 'ERROR while adding rule'
exit 1
fi
fi
lfile="/tmp/doOnUSBinsert.log" # udev
lfile2="/tmp/clamscanFromUdev.log" # clamscan
lfile3="/tmp/doOnUSBinsert_mount.log" # mount
notify-send "USB SCAN ON INSERT" "Currently scanning with ClamAV"
main ()
{
sleep 12 # let the partitions to mount
#cat /proc/$$/environ | tr '�' 'n' >> /tmp/udevEnvirn.txt
echo "found $ID_SERIAL" >> "$lfile"
cat /etc/mtab | grep "^$part_c" >> "$lfile.3"
if [ "$ID_SERIAL"x = 'x' ]
then
echo "Exiting on empty ID_SERIAL" >> "$lfile"
exit 1
fi
#Eg: ID_SERIAL --> /dev/disk/by-id/usb-sandisk....42343254343543
#i=0
echo 'searching partitions' >> "$lfile"
for partitionPath in $( find /dev/disk/by-id/ -name "*$ID_SERIAL*part*" )
do
echo "current partition = $partitionPath" >> "$lfile"
# part[i ]="$( readlink -f "$partition" )" # Eg Output: /dev/sdb1 , /dev/sdb2
part_c="$( readlink -f $partitionPath )"
mpoint="$( cat /etc/mtab | grep "^$part_c" | awk '{print $2}' )"
echo "partitionPath= $partitionPath, part = $part_c, mountpoint= $mpoint" >> "$lfile"
echo "Scaning --> $mpoint" >> "$lfile.2"
############################################
clamscan -r --bell "$mpoint"/* >> "$lfile.2"
#############################################
done
}
notify-send "USB SCAN ON INSERT" "Finished scanning with ClamAV"
main &
echo ______________________________________ >> "$lfile"
exit 0
I'm pretty new to the linux world, but while looking for a solution for a similar project I found THIS
Tip: An overview on the available icons can be found here. To send
desktop notification from a background script running as root (replace
X_user and X_userid with the user and userid running X respectively):
sudo -u X_user DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/X_userid/bus notify-send 'Hello world!' 'This is an example notification.'
Hope this will help others.
Depending on how you are running the script it may not have access to the display variable. Try running export DISPLAY=:0.0 prior to the command.
If you are running the script as a different user, ie root, then you may also need to run it as su - <logged in user> -c notify-send ... (I usually don't need to do this, but I remember having to at one point - but I cant recall which distro or version I was on at the time.)

Assigning variable in shell script

#!/bin/sh
SUCCESS=0
java -jar sbc.jar &
while [ true ];
do
echo "sleeping"
sleep 5
echo "again"
tail -1 ~/NetBeansProjects/xyz/dist/newlog.log | grep -q "[INFO ] - Stream closed"
if [ $? = 1 ]
then
echo " entered if "
java -jar sbc.jar &
else
echo " did not if "
fi
done
I want to use a better variable than $? to store the result of the previous line because I may need it more than once. The script is intended to check the last line of the file newlog.log for a particualr string and then start sbc.jar again because the string confirms that the program has stopped.
Store it in another variable:
...
tail -1 ~/NetBeansProjects/xyz/dist/newlog.log | grep -q "[INFO ] - Stream closed"
RES=$?
if [ $RES = 1 ]
...

Resources