Java app behind proxy to use http_proxy variable in linux - java

I am thinking of a simple Java appplication (command line) that connects to the internet to download a XML file, the problem is that my Ubuntu is using a proxy to connect to internet with username and password (through http_proxy ="http://<username>:<pwd>#<ip>:<port>" ). So my question is, could it be possible to write a java app to use http_proxy variable? Instead of programmatically setting http proxy and host in every app I will write.

Don't forget the shell variable _JAVA_OPTIONS
export _JAVA_OPTIONS='-Dhttp.proxyHost=cache.com -Dhttp.proxyPort=3128'
For more properties look here:
http://mindprod.com/jgloss/properties.html

You can use this script to automatic enviroment passing to java application
This is an intelligent script, if you enable nmap section, it is detecting proxy up or down status , if it is up status it is using proxy if it is down status it is using direct connection..
With this script you can connect your app with enviroment settings or overwrite enviroment or with proxy service up detection method , the application selects direct or proxy mode
This is an intelligent connection bash shell script
Ofcouse if you don't enable nmap service up/down section, this is an simple proxy enviroment or your overwrite value for your application
It is producing automaticly proxy connection command line then running your java application
This is script's code:
#!/bin/bash
# Author : Kerim BASOL
# Twitter : http://twitter.com/kerimbasol
# URL : http://kerimbasol.com
# Version : 0.1
# Java Proxy support script
# You can use with GNU License
# Which is your runtime jar file
# Please change this as your application's needs
JARFILE="myapp.jar"
#Automaticly import system proxy settings
if [ -n "$http_proxy" ] ; then
echo $http_proxy | grep "#"
if [ $? -eq 0 ]; then # If variable has username and password, its parse method different
PROXY_HOST=$(echo $http_proxy | sed 's/http:\/\/.*#\(.*\):.*/\1/')
PROXY_PORT=$(echo $http_proxy | sed 's/http:\/\/.*#.*:\(.*\)/\1/' | tr -d "/")
USERNAME=$(echo $http_proxy | sed 's/http:\/\/\(.*\)#.*/\1/'|awk -F: '{print $1}')
PASSWORD=$(echo $http_proxy | sed 's/http:\/\/\(.*\)#.*/\1/'|awk -F: '{print $2}')
else # If it doesn't have username and password, its parse method this
PROXY_HOST=$(echo $http_proxy | sed 's/http:\/\/\(.*\):.*/\1/')
PROXY_PORT=$(echo $http_proxy | sed 's/http:\/\/.*:\(.*\)/\1/' | tr -d "/")
fi
fi
# If you want to overwrite system proxy settings
# uncomment these lines as your wish
#PROXY_HOST="127.0.0.1"
#PROXY_PORT="3128"
#USERNAME="kerimbasol"
#PASSWORD="deneme"
# Display usage
if [ $# -gt 0 ] ; then
if [ $1 = "--help" ] ; then
echo "$0 [<proxy-server> <proxy-port> [<username> <password> ] ] "
exit 0
fi
fi
# Command line proxy pass
if [ $# -gt 1 ] ; then
PROXY_HOST=$1
PROXY_PORT=$2
if [ $# -gt 3 ] ; then
USERNAME=$3
PASSWORD=$4
fi
fi
# If you want to use this feature , enables and disables proxy support for proxy service up or down status
# uncomment these line, if you installed nmap
# at ubuntu system you can type this command for this future
# sudo apt-get install nmap
#STATUS=$(nmap -sT $PROXY_HOST -p $PROXY_PORT 2>/dev/null| grep open |awk '{print $2}')
#if [ "$STATUS" != "open" ]; then # If service isn't running, disable proxy support
# PROXY_HOST=""
# PROXY_PORT=""
#fi
CMD="java -cp."
if [ -n "$PROXY_HOST" -a -n "$PROXY_PORT" ] ; then
CMD="java -cp . -Dhttp.proxyHost=$PROXY_HOST -Dhttp.proxyPort=$PROXY_PORT"
if [ -n "$USERNAME" -a -n "$PASSWORD" ]; then
CMD="$CMD -Dhttp.proxyUser=$USERNAME -Dhttp.proxyPassword=$PASSWORD"
fi
fi
# If you want , change this line as your application wish ;)
CMD="$CMD -jar $JARFILE"
eval $CMD

With a current JVM you can pass the proxy host and port using Java properties
java -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080 -Dhttp.noProxyHosts=”localhost|host.mydomain.com” GetURL
See http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

For username and password, what about:
-Dhttp.proxyUser=username -Dhttp.proxyPassword=supersecret

in http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html there is no command to pass proxy username and password to JVM.

Related

Check and run/restart processes, bash [duplicate]

This question already has answers here:
Linux Script to check if process is running and act on the result
(8 answers)
Closed 5 years ago.
I wrote a bash-script to check if a process is running. It doesn't work since the ps command always returns exit code 1. When I run the ps command from the command-line, the $? is correctly set, but within the script it is always 1. Any idea?
#!/bin/bash
SERVICE=$1
ps -a | grep -v grep | grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
echo "`date`: $SERVICE service running, everything is fine"
else
echo "`date`: $SERVICE is not running"
fi
Bash version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
There are a few really simple methods:
pgrep procname && echo Running
pgrep procname || echo Not running
killall -q -0 procname && echo Running
pidof procname && echo Running
This trick works for me. Hope this could help you. Let's save the followings as checkRunningProcess.sh
#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
echo "Running"
else
echo "Not Running"
fi
Make the checkRunningProcess.sh executable.And then use it.
Example to use.
20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running
I tried your version on BASH version 3.2.29, worked fine. However, you could do something like the above suggested, an example here:
#!/bin/sh
SERVICE="$1"
RESULT=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
echo "Running"
else
echo "Not Running"
fi
I use this one to check every 10 seconds process is running and start if not and allows multiple arguments:
#!/bin/sh
PROCESS="$1"
PROCANDARGS=$*
while :
do
RESULT=`pgrep ${PROCESS}`
if [ "${RESULT:-null}" = null ]; then
echo "${PROCESS} not running, starting "$PROCANDARGS
$PROCANDARGS &
else
echo "running"
fi
sleep 10
done
Check if your scripts name doesn't contain $SERVICE. If it does, it will be shown in ps results, causing script to always think that service is running. You can grep it against current filename like this:
#!/bin/sh
SERVICE=$1
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
echo "$SERVICE service running, everything is fine"
else
echo "$SERVICE is not running"
fi
Working one.
!/bin/bash
CHECK=$0
SERVICE=$1
DATE=`date`
OUTPUT=$(ps aux | grep -v grep | grep -v $CHECK |grep $1)
echo $OUTPUT
if [ "${#OUTPUT}" -gt 0 ] ;
then echo "$DATE: $SERVICE service running, everything is fine"
else echo "$DATE: $SERVICE is not running"
fi
Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.
#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if ${#result}> 0
then
echo " Working!"
else
echo "Not Working.....Restarting"
/usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi
#!/bin/bash
ps axho comm| grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
echo "`date`: $SERVICE service running, everything is fine"
else
echo "`date`: $SERVICE is not running"
/etc/init.d/$1 restart
fi
Something like this
Those are helpful hints. I just needed to know if a service was running when I started the script, so I could leave the service in the same state when I left. I ended up using this:
HTTPDSERVICE=$(ps -A | grep httpd | head -1)
[ -z "$HTTPDSERVICE" ] && echo "No apache service running."
I found the problem. ps -ae instead ps -a works.
I guess it has to do with my rights in the shared hosting environment. There's apparently a difference between executing "ps -a" from the command line and executing it from within a bash-script.
A simple script version of one of Andor's above suggestions:
!/bin/bash
pgrep $1 && echo Running
If the above script is called test.sh then, in order to test, type:
test.sh NameOfProcessToCheck
e.g.
test.sh php
I was wondering if it would be a good idea to have progressive attempts at a process, so you pass this func a process name func_terminate_process "firefox" and it tires things more nicely first, then moves on to kill.
# -- NICE: try to use killall to stop process(s)
killall ${1} > /dev/null 2>&1 ;sleep 10
# -- if we do not see the process, just end the function
pgrep ${1} > /dev/null 2>&1 || return
# -- UGLY: Step trough every pid and use kill -9 on them individually
for PID in $(pidof ${1}) ;do
echo "Terminating Process: [${1}], PID [${PID}]"
kill -9 ${PID} ;sleep 10
# -- NASTY: If kill -9 fails, try SIGTERM on PID
if ps -p ${PID} > /dev/null ;then
echo "${PID} is still running, forcefully terminating with SIGTERM"
kill -SIGTERM ${PID} ;sleep 10
fi
done
# -- If after all that, we still see the process, report that to the screen.
pgrep ${1} > /dev/null 2>&1 && echo "Error, unable to terminate all or any of [${1}]" || echo "Terminate process [${1}] : SUCCESSFUL"
I need to do this from time to time and end up hacking the command line until it works.
For example, here I want to see if I have any SSH connections, (the 8th column returned by "ps" is the running "path-to-procname" and is filtered by "awk":
ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g'
Then I put it in a shell-script, ("eval"-ing the command line inside of backticks), like this:
#!/bin/bash
VNC_STRING=`ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g'`
if [ ! -z "$VNC_STRING" ]; then
echo "The VNC STRING is not empty, therefore your process is running."
fi
The "sed" part trims the path to the exact token and might not be necessary for your needs.
Here's my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.
I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been "ssh-copy-id"-ed and are known to the remote host).
It's idempotent in that each proc/command only fires when their $VAR eval's to an empty string.
It appends " | wc -l" to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the "echo" statements so I can re-run and diagnose the state of both connections.
#!/bin/bash
SSH_COUNT=`eval ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g' | wc -l`
VNC_COUNT=`eval ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g' | wc -l`
if [ $SSH_COUNT = "2" ]; then
echo "There are already 2 SSH tunnels."
elif [ $SSH_COUNT = "1" ]; then
echo "There is only 1 SSH tunnel."
elif [ $SSH_COUNT = "0" ]; then
echo "connecting 2 SSH tunnels."
ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10;
ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10;
fi
if [ $VNC_COUNT = "2" ]; then
echo "There are already 2 VNC sessions."
elif [ $VNC_COUNT = "1" ]; then
echo "There is only 1 VNC session."
elif [ $VNC_COUNT = "0" ]; then
echo "launching 2 vnc sessions."
vncviewer.exe localhost:1 &
vncviewer.exe localhost:4 &
fi
This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of "MAGIC" numbers and cheezy hard-coded values but it works, (I think I'm also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.
A solution with service and awk that takes in a comma-delimited list of service names.
First it's probably a good bet you'll need root privileges to do what you want. If you don't need to check then you can remove that part.
#!/usr/bin/env bash
# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1
ALL_SERVICES_STARTED=true
if [ $EUID -ne 0 ]; then
if [ "$(id -u)" != "0" ]; then
echo "root privileges are required" 1>&2
exit 1
fi
exit 1
fi
for service in ${SERVICES//,/ }
do
STATUS=$(service ${service} status | awk '{print $2}')
if [ "${STATUS}" != "started" ]; then
echo "${service} not started"
ALL_SERVICES_STARTED=false
fi
done
if ${ALL_SERVICES_STARTED} ; then
echo "All services started"
exit 0
else
echo "Check Failed"
exit 1
fi
The most simple check by process name :
bash -c 'checkproc ssh.exe ; while [ $? -eq 0 ] ; do echo "proc running";sleep 10; checkproc ssh.exe; done'

Have script detect gnome session

I have a makeself script which I expect to be run as root; It's a desktop installer.
At the end of the script, the software which was recently installed to the filesystem tries to launch in user-space.
This works well using sudo -u $(logname) /path/to/application (or alternately sudo -u $SUDO_USER ... in Ubuntu 16.04) however a critical environmental variable from the user is missing:
GNOME_DESKTOP_SESSION_ID
I need GNOME_DESKTOP_SESSION_ID because the child process belongs to Java and Java uses this environmental variable for detecting the GtkLookAndFeel.
However attempts to use sudo -i have failed.
From some basic tests, the GNOME_DESKTOP_SESSION_ID doesn't appear to be a natural environmental variable when this users logs in. For example, if I CTRL+ALT+F1 to a terminal, env |grep GNOME yields nothing whereas XTerm and gnome-terminal both yield GNOME_DESKTOP_SESSION_ID.
How can I get a hold of this GNOME_DESKTOP_SESSION_ID variable from within the installer script without requiring users to pass something such as the -E parameter to the sudo command?
Note, although GtkLookAndFeel is the primary look and feel for Linux, I prefer not to hard-code the export JAVA_OPTS either, I prefer to continue to fallback onto Oracle's detection techniques for support, longevity and scalability reasons.
Update: In Ubuntu, GNOME_DESKTOP_SESSION_ID lives in /usr/share/upstart/sessions/xsession-init.conf
initctl set-env --global GNOME_DESKTOP_SESSION_ID=this-is-deprecated
Which leads to using initctl get-env to retrieve it. Unfortunately this does not help within a new sudo shell, nor does any (optimistic) attempt at dbus-launch.
It turns out this is a two-step process...
Read the user's UPSTART_SESSION environmental variables from /proc/$pid/environ
Then export UPSTART_SESSION and call initctl --user get-env GNOME_DESKTOP_SESSION_ID
To make this a bit more scalable to other variables, I've wrapped this into a bash helper function. This function should assist fetching other user-environment variables as well. Word of caution, it won't work if the variable's value has a space in the name.
In the below example, only UPSTART_SESSION and GNOME_DESKTOP_SESSION_ID are required to answer the question.
Once sudo_env is called, the next call to sudo -u ... must be changed to sudo -E -u .... The -E will import the newly exported variables for use by a child process.
# Provide user environmental variables to the sudo environment
function sudo_env() {
userid="$(logname 2>/dev/null || echo $SUDO_USER)"
pid=$(ps aux |grep "^$userid" |grep "dbus-daemon" | grep "unix:" |awk '{print $2}')
# Replace null delimiters with newline for grep
envt=$(cat "/proc/$pid/environ" |tr '\0' '\n')
# List of environmental variables to use; adjust as needed
# UPSTART_SESSION must come before GNOME_DESKTOP_SESSION_ID
exports=( "UPSTART_SESSION" "DISPLAY" "DBUS_SESSION_BUS_ADDRESS" "XDG_CURRENT_DESKTOP" "GNOME_DESKTOP_SESSION_ID" )
for i in "${exports[#]}"; do
# Re-set the variable within this session by name
# Careful, this technique won't yet work with spaces
if echo "$envt" | grep "^$i=" > /dev/null 2>&1; then
eval "$(echo "$envt" | grep "^$i=")" > /dev/null 2>&1
export $i > /dev/null 2>&1
elif initctl --user get-env $i > /dev/null 2>&1; then
eval "$i=$(initctl --user get-env $i)" > /dev/null 2>&1
export $i > /dev/null 2>&1
fi
echo "$i=${!i}"
done
}
You need to create a new file on /etc/sudoers.d with this content:
Defaults env_keep+=GNOME_DESKTOP_SESSION_ID
But, there is a problem, if you already are inside sudo, it will not been read again.
So, the complete solution is use sudo inside your script to create this file and then execute your command in another sudo:
#!/bin/bash
# ignore sudo
if [[ -z $SUDO_USER ]]; then
#save current dir
DIR="$(pwd)"
#generate random string (file name compatible)
NEW_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
#create env_keep file
sudo -i -- <<EOF0
echo "Defaults env_keep+=GNOME_DESKTOP_SESSION_ID" > /etc/sudoers.d/"$NEW_UUID"_keep_java_laf
EOF0
sudo -u YOUR_USER -i -- <<EOF
#go to original directory
cd "$DIR"
#execute your java command
java YOUR_COMMAND
EOF
#clean file
sudo rm -f /etc/sudoers.d/"$NEW_UUID"_keep_java_laf
else
echo "sudo not allowed!";exit 1;
fi

jboss_init_redhat is not working

I used Redhat and Jboss 4.2.2 GA for application server.
I have a basic problem that when I try to run
./jboss_init_redhat.sh start
is not working.
Basicly I want to run inside jboss_init_redhat.sh file;
/opt/jboss/bin/run.sh -c X -b 0.0.0.0
This line is working but jboss_init_redhat.sh not working.That's our problem.
I checked all permissions but there is not any permission problem.
jboss_init_redhat.sh is below:
#!/bin/sh
#
# $Id: jboss_init_redhat.sh 60992 2007-02-28 11:33:27Z 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/jboss"}
#define the user under which jboss will run, or use 'RUNASIS' to run as the current user
JBOSS_USER=${JBOSS_USER:-"jboss"}
#make sure java is in your path
JAVAPTH=${JAVAPTH:-"/usr/local/jdk/bin"}
#configuration to use, usually one of 'minimal', 'default', 'all'
JBOSS_CONF=${JBOSS_CONF:-"ikarus"}
#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
If you change JBOSS_USER information to RUNASIS, it should work properly.

How do I run Java as a service on Ubuntu?

So after 2 days (yes I'm a complete rookie when it comes to servers) trying to get this working I give up and turn to SO for help :)
I want to start my java app on start, log to a logfile. That's it :)
start on runlevel [2345]
stop on runlevel [!2345]
#Respawn the process if it crashes
#If it respawns more than 10 times in 5 seconds stop
respawn
respawn limit 10 5
expect fork
script
cd /home/ubuntu/admin/
mvn spring-boot:run > /var/log/upstart/admin.log 2>&1
end script
Running "sudo start admin" works and I get "admin start/running" in console.. No log is created and the java app is not started.. ?
What am I missing?
How do I run Java as a service on Ubuntu?
I don't mean to sidetrack, but I've deployed Java applications on Ubuntu in production since 2010 and had very little success with Upstart. I use init.d scripts and start-stop-daemon. Side bonus: it works on more distros.
Create /etc/init.d/my-java-app:
#!/bin/sh
#
# my-java-app My Java App
#
# chkconfig: - 80 05
# description: Enable My Java Application
#
### BEGIN INIT INFO
# Provides: my-java-app
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: My Java Application
# Short-Description: Enable My Java Application
### END INIT INFO
DESC="my java app"
NAME=my-java-app
PIDFILE=/var/run/$NAME.pid
RUN_AS=ubuntu
WORK_DIR=/home/ubuntu/admin
DAEMON=/usr/bin/mvn
DAEMON_OPTS="spring-boot:run"
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions
do_start() {
start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE \
--background \
--chuid $RUN_AS \
--chdir $WORK_DIR \
--exec $DAEMON -- $DAEMON_OPTS
}
do_stop() {
start-stop-daemon --stop --quiet --pidfile $PIDFILE
if [ -e $PIDFILE ]
then rm $PIDFILE
fi
}
case "$1" in
start)
echo -n "Starting $DESC: $NAME"
do_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME"
do_stop
echo "."
;;
restart)
echo -n "Restarting $DESC: $NAME"
do_stop
sleep 1
do_start
echo "."
;;
status)
status_of_proc -p $PIDFILE "$DAEMON" "$NAME" && exit 0 || exit $?
;;
*)
echo "usage: $NAME {start|stop|restart}"
exit 1
;;
esac
Make it belong to root, make it executable, and set it up to run on startup with:
sudo chown root:root /etc/init.d/my-java-app
sudo chmod 755 /etc/init.d/my-java-app
sudo update-rc.d my-java-app defaults
To start the service you can run:
sudo service my-java-app start
To stop the service you can run:
sudo service my-java-app stop
This is based on a simplified version of the /etc/init.d/skeleton file included by Ubuntu.
The man page for start-stop-daemon is worth looking at if you want to tweak this further.b

Check if jar running from shell

I have a java jar program that I am trying to run on startup of my machine. Ideally, the shells script will check every 60 seconds to assure that the jar is running. How do I check if the jar is running on centos, this does not appear to be working?
My current .sh file:
#!/bin/bash
while [ true ]
do
cnt=`ps -eaflc --sort stime | grep /home/Portal.jar |grep -v grep | wc -l`
if(test $cnt -eq 3);
then
echo "Service already running..."
else
echo "Starting Service"
java -jar /home/Portal.jar >> /dev/null &
fi
sleep 1m
done
I used this for referencing so far.
Depending on what your program does, there may be more or less intelligent ways to check it. For example, if you have some server, it will listen on a port.
Then something like
netstat -an | fgrep tcp | fgrep LISTEN | fgrep :87654 # or whatever your port is
could do the job.
Then there is lsof, which could also detect listening ports.
Finally, you could connect and issue a pseudo request. For example, for a http server, you could use lynx or curl. For a server with a non-stamdard protocol, you can write a small client program whose sole purpose is to connect to the server just to see if it is there.
Store your process id in file and check for this process.
#!/bin/bash
while [ true ]
do
pid=$(cat /tmp/portal.pid)
if [[ -n "$pid" && $(ps -p $pid | wc -l) -eq 2 ]]
then
echo "Service already running..."
else
echo "Starting Service"
java -jar /home/Portal.jar >> /dev/null &
echo $! > /tmp/portal.pid
fi
sleep 1m
done
/tmp will be cleared on restart, all right in this case.
I did the very same scenario a couple of months ago. My task was to ensure a jar distributed java program to run 24/7 on a Linux server.
My program was console-based, started, did something then stopped.
I did a shell script that started, waited to end and then re-started the app in an infinite loop.
I installed runit, created a service and supplied this script as the run script. Works very well.
In general, the shell script ensures that the java program is running and runit ensures that the start script (which is our script) is running.
You find valuable info here: http://smarden.org/runit/faq.html
Rather than putting the process to sleep , I'd rather have it exit and use crontab to run the process every 1 min;which will check if its running or else just stop the script.
#!/bin/sh
declare -a devId=( "/Path/To/TestJar.jar Test1" "/Path/To/TestJar.jar Test2" ) #jarfile with pathname and Test as argument
# get length of an array
arraylength=${#devId[#]}
# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
y=${devId[$i-1]}
cnt=`ps -eaflc --sort stime | grep "$y" |grep -v grep | wc -l`
if [ $cnt = 0 ]
then
java -jar $y& > /dev/null
b=$(basename $y)
echo $b
#DO SOME OPERATION LIKE SEND AN EMAIL OR ADD TO LOG FILE
continue
elif [ $cnt != 0 ]
then
echo 'do nothing'
fi
done
Why do you think $cnt should be equal to 3? Shouldn't it be equal to 1 if the process is already running?
You could use the jps command. It return the JVMs running in the system.
I created following script to monitor my application jar is running or not.
In this case My application jar is running on port 8080
#!/bin/bash
check=$(netstat -an | grep 8080 | wc -l)
if [[ $check -eq 0 ]];then
echo "jar is not running..."
/usr/bin/java -jar /path/to/target/application.jar >> /dev/null &
else
echo "it is running"
fi
I am using cronjob to monitor jar app by executing shell script on every minute.
$ crontab -e
in the end of file
* * * * * /bin/bash monitor-jar.sh /dev/null 2>&1

Categories

Resources