Shell script to start game servers in screen - shell

I'm trying to modify this very simple shell script I wrote to check if the screens are already active and if so, not create them. For example, if I call this script twice with the start parameter, four screen sessions will be made. I want to prevent that.
#! /bin/sh
# /etc/init.d/css-server
#
case "$1" in
start)
echo "Starting Nullus Imprimis war server..."
screen -A -m -d -S css-war-server /home/css-servers/war-server/css/srcds_run -game cstrike +map de_dust2 +maxplayers 16 -autoupdate -port 2555
echo "Nullus Imprimis war server started"
echo "Starting Nullus Imprimis pub server #1..."
screen -A -m -d -S css-pub-server-1 /home/css-servers/pub-server-1/css/srcds_run -game cstrike +map de_dust2 +maxplayers 32 -autoupdate -port 2666
echo "Nullus Imprimis pub server #1 started"
;;
stop)
echo "Stopping Nullus Imprimis war server..."
screen -S css-war-server -X quit
echo "Nullus Imprimis war server stopped"
echo "Stopping Nullus Imprimis pub server #1..."
screen -S css-pub-server-1 -X quit
echo "Nullus Imprimis pub server #1 stopped"
;;
*)
echo "Usage: service css-servers {start|stop}"
exit 1
;;
esac
exit 0
Also, I want to make the servers run under their own username, in this case css-servers. How can I do that?

To check if a screen is already running, I usually just grep it from screen -ls:
screen -ls | grep -q NAME || ...do something if server is not running...
Or:
if ! screen -ls | grep -q NAME; then
...do something if server is not running...
fi
In order to run this as a different user, I would suggest running the startup script with sudo -u, something like this:
sudo -u css-servers STARTUP_SCRIPT

Related

bash script: to check if Apache server is up and running

I am new to bash scripting and trying to figure out why the below script is outputting that Apache server is not running whereas it is running properly.
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
I'm running it on Ubuntu 14.04.2 LTS
Also, how do I make changes to the script that this can test apache server installed on another machine.
Kindly help
This is a working sample of bash script which check the apache status, restart it automatically if down, and alert by telegram bot within unicode emoji.
#!/bin/bash
telegram=(xxxxx, yyyyyy)
if ! pidof apache2 > /dev/null
then
# web server down, restart the server
echo "Server down"
/etc/init.d/apache2 restart > /dev/null
sleep 10
#checking if apache restarted or not
if pidof apache2 > /dev/null
then
for i in "${telegram[#]}"
do
curl -s -X POST https://api.telegram.org/botxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyy/sendMessage -d chat_id="$i" -d text="`echo -e '\U0001F525'` Apache stoped on Molib Stage. Automatically restarted succesfully."
done
else
for i in "${telegram[#]}"
do
curl -s -X POST https://api.telegram.org/botxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyy/sendMessage -d chat_id="$i" -d text="`echo -e '\U0001F525'` Apache stoped on Molib Stage. Automatically restart failed. Please check manually."
done
fi
fi
Use this:
service apache2 status
Or this:
service --status-all | grep apache2
Instead of httpd try to grep "apache2". To be sure try to check services with the next command and decide the registered name of the apache webserver:
service --status-all
Try and see - simply simplest, most didactic here and well working on Ubuntu 20.04:
catching output of status to bash variable
"if" status includes substring (from "Active:" statement) - do job you wanted
"else" - do another job you defined
#!/bin/bash
servstat=$(service apache2 status)
if [[ $servstat == *"active (running)"* ]]; then
echo "process is running"
else echo "process is not running"
fi
This work perfect in an old Debian. Remember to run with bash and not with sh.
In Centos replace with httpd.
#!/bin/bash
if [ $(/etc/init.d/apache2 status | grep -v grep | grep 'apache2 is running' | wc -l) > 0 ]
then
echo "Process is running."
else
echo "Process is not running."
fi
## Plz run this script .. its working
------------------------------------------------
ps cax | grep httpd
if [ $? -eq 1 ]
then
echo "Process is running."
else if [ $? -eq 0 ]
echo "Process is not running."
fi
fi
----------------------------------------------
This is menu driven one stop shell script in which you can check the firewall,apache or any other webservices ,you can start or stop the services just by choosing the option in below script
echo "welcome please select your options"
read choice
firewall=`sudo systemctl status firewalld`
apache=`sudo systemctl status apache2`
firewall1=`sudo systemctl stop firewalld`
apache1=`sudo systemctl stop apache2`
startrfirewall=`sudo systemctl start firewalld`
startapache=`sudo systemctl start apache2`
case $choice in
1) status of the firewall is $firewall
;;
2) status of apache is $apache
;;
3) echo stop firewall by $firewall1
;;
4) echo stop apache by $apache1
;;
5) echo start firewall by $startrfirewall
;;
6) echo start apache by $startapache
;;
*) echo exit
esac
I put this together based on the above and made so can use other services.
Hope this helps.
#!/bin/bash
# Must be running as root or via sudo permissions to be able to restart
# Put your process name restart command line in
PROCESS_NAME=httpd
if ! pidof $PROCESS_NAME > /dev/null
then
# web server down, restart the server
echo "Server $PROCESS_NAME down"
/usr/sbin/apachectl restart > /dev/null
echo "Tried restart of $PROCESS_NAME. Waiting 10 seconds to settle."
# wait ten
sleep 10
#checking if process restarted or not
if pidof $PROCESS_NAME > /dev/null
then
echo "$PROCESS_NAME was down but is now up."
else
echo "$PROCESS_NAME is still down. Please take some action."
fi
else
echo "Server $PROCESS_NAME up."
fi

golang webapp init.d script hangs

I have a go web app compiled to a single binary that I am trying to manage via init.d. Here is my init.d script:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/my-go-app
DAEMON_ARGS="--logFile /var/log/my-go-app/my-go-app.log"
NAME=my-go-app
DESC=my-go-app
RUNDIR=/var/run/my-go-app
PIDFILE=$RUNDIR/my-go-app.pid
test -x $DAEMON || exit 0
if [ -r /etc/default/$NAME ]
then
. /etc/default/$NAME
fi
. /lib/lsb/init-functions
set -e
case "$1" in
start)
echo -n "Starting $DESC: "
mkdir -p $RUNDIR
touch $PIDFILE
chown ubuntu:ubuntu $RUNDIR $PIDFILE
chmod 755 $RUNDIR
if [ -n "$ULIMIT" ]
then
ulimit -n $ULIMIT
fi
if start-stop-daemon --start --quiet --umask 007 --pidfile $PIDFILE --chuid ubuntu:ubuntu --exec $DAEMON -- $DAEMON_ARGS
then
echo "$NAME."
else
echo "failed"
fi
;;
stop)
echo -n "Stopping $DESC: "
if start-stop-daemon --stop --retry forever/TERM/1 --quiet --oknodo --pidfile $PIDFILE --exec $DAEMON
then
echo "$NAME."
else
echo "failed"
fi
rm -f $PIDFILE
sleep 1
;;
restart|force-reload)
${0} stop
${0} start
;;
status)
echo -n "$DESC is "
if start-stop-daemon --stop --quiet --signal 0 --name ${NAME} --pidfile ${PIDFILE}
then
echo "running"
else
echo "not running"
exit 1
fi
;;
*)
echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload|status}" >&2
exit 1
;;
esac
exit 0
The problem is that when I run service my-go-app start, it just hangs, like this:
ubuntu#ip-10-0-0-40:~$ service my-go-app start
Starting my-go-app:
and never returns. In this state, if I open a separate terminal, I can see that the app is running by checking the log file but there is nothing in /var/run/my-go-app/my-go-app.pid (though the pid file does get created).
Has anyone encountered (and hopefully resolved) this before? How can I run my go app as an init.d daemon?
EDIT:
I was able to get this to work by adding the "-b -m" command line flags to start-stop-daemonwhen starting the service. That line now looks like this:
start-stop-daemon -b -m --start --quiet --umask 007 --pidfile $PIDFILE --chuid ubuntu:ubuntu --exec $DAEMON -- $DAEMON_ARGS
My concern with this approach is the warning in the start-stop-daemon manpage:
-b, --background
Typically used with programs that don't detach on their own. This option will force start-stop-daemon to fork before starting the process, and
force it into the background. WARNING: start-stop-daemon cannot check the exit status if the process fails to execute for any reason. This is
a last resort, and is only meant for programs that either make no sense forking on their own, or where it's not feasible to add the code for
them to do this themselves.
This seems like a bad idea to me, because it sounds like SysV won't know if the process dies. Am I understanding this correctly? Has anyone else tried this approach?
If you are running a system with Upstart you can use this script:
start on runlevel [2345]
stop on runlevel [016] or unmounting-filesystem
# Replace {soft} and {hard} with the soft and hard resource limits you desire
#limit nofile {soft} {hard}
umask 007
setuid ubuntu
setgid ubuntu
exec /usr/bin/my-go-app --logFile /var/log/my-go-app/my-go-app.log
You can also add the following code to your daemon at a point where your application has been started and initialized correctly:
if ("yes" == os.Getenv("MYAPP_RAISESTOP")) {
p, err := os.FindProcess(os.Getpid())
p.Signal(syscall.SIGSTOP)
}
and the following to lines to the above upstart job:
env MYAPP_RAISESTOP="yes"
expect stop
I am sorry if the if () { } is not real Go syntax; I am a C programmer haha (although the stuff inside the () and {} is real, I did a little research :).
Doing this last bit ensures that Upstart will wait until your application is set up correctly before firing off the started event. If no other jobs are waiting for your app, then you do not really need that.
You will need the --background flag if you want to use SysVinit and start-stop-daemon with Go programs.
I suggest using something like Supervisor or Circus instead.
Edit:
This is not strictly true, if your Go program daemonizes its self, the --background flag can be excluded.

SHOUTcast daemon script not functioning properly

I've got a SHOUTcast server running on Ubuntu. The server process is running great, but I can't seem to get the daemon script to function properly. Following a couple tutorials I found I came up with this:
#!/bin/sh
CONFIG="/home/apps/shout32/sc_plex.conf"
DAEMON="/home/apps/shout32/sc_serv"
case "$1" in
start)
echo "Starting SC..."
$DAEMON $CONFIG > /dev/null 2>&1 &
;;
stop)
echo "Stopping SC..."
kill -9 `ps -C sc_serv -o pid --no-headers`
;;
restart)
echo "Rebooting SC..."
kill -9 `ps -C sc_serv -o pid --no-headers`
$DAEMON $CONFIG > /dev/null 2>&1 &
;;
*)
echo "usage: service sc32d {start | stop | restart}"
exit 1
;;
esac
This however does not work. I didn't know what a lot of this meant, so I started to break it down line by line. If I remove the /dev/null stuff - which as I now understand keeps the program running 'silent' in the background - I get this message, and the program closes:
root#streams3:/etc/init.d# service sc32d start
Starting SC...
root#streams3:/etc/init.d# 2013-05-21 14:41:50 E msg:<***> logger could not open file logs/sc_serv.log
2013-05-21 14:41:50 I msg:<***> Logger shutdown
root#streams3:/etc/init.d#
root#streams3:/etc/init.d# ps -C sc_serv
PID TTY TIME CMD
root#streams3:/etc/init.d#
I was still in the process of researching what exactly /dev/null did and why, so I wanted to run those commands with all the /dev/null stuff by hand, which I did, and that's where I got some sort of error code:
root#streams3:/etc/init.d# /home/apps/shout32/sc_serv /home/apps/shout32/sc_plex.conf > /dev/null 2>&1 &
[2] 2261
root#streams3:/etc/init.d#
[2]- Exit 255 /home/apps/shout32/sc_serv /home/apps/shout32/sc_plex.conf > /dev/null 2>&1
root#streams3:/etc/init.d# ps -C sc_serv
PID TTY TIME CMD
Unfortunately from the brief amount of research I did it sounds like 'Exit 225' is like a catch-all error code for codes that are outside of the acceptable range of codes.
The interesting part of the whole issue is this: When I navigate to the /home/apps/shout32/ folder, and run the commands there, without the full path... damn thing works:
root#streams3:/home/apps/shout32# ./sc_serv sc_plex.conf > /dev/null 2>&1 &
[2] 2245
root#streams3:/home/apps/shout32#
root#streams3:/home/apps/shout32# ps -C sc_serv
PID TTY TIME CMD
2245 pts/0 00:00:00 sc_serv
So, something is messing up because the script file is in /etc/init.d/ and not in the folder the application is in? As far as I know I followed every step in the published tutorials for setting up SHOUTcast in Ubuntu and then making a daemon... I don't think I missed anything. I have a feeling the solution is either staring me right in the face or its some sort of obscure permissions thing that's a bit over my head.
But any help would be greatly appreciated!
So, based on an answer below I added cd /home/apps/shout32/ to the START command in my script, also added pwd and ls... to see if we could eliminate the fact that the script couldn't find the /log/ directory.
So now my script is:
CONFIG="/home/apps/shout32/sc_plex.conf"
DAEMON="/home/apps/shout32/sc_serv"
cd /home/apps/shout32/
case "$1" in
start)
echo "Starting SC..."
cd /home/apps/shout32/
pwd
ls
$DAEMON $CONFIG &
;;
stop)
echo "Stopping SC..."
kill -9 `ps -C sc_serv -o pid --no-headers`
;;
restart)
echo "Rebooting SC..."
kill -9 `ps -C sc_serv -o pid --no-headers`
$DAEMON $CONFIG &
;;
*)
echo "usage: service sc32d {start | stop | restart}"
exit 1
;;
esac
I got this:
admin#streams3:/etc/init.d$ service sc32d start
Starting SC...
/home/apps/shout32
changes.txt readme.txt sc_serv_debug.conf
config_builder sc_plex.conf sc_serv_public.conf
control sc_serv sc_serv_relay.conf
docs sc_serv2_linux_07_31_2011.tar sc_serv_simple.conf
logs sc_serv_basic.conf tos.txt
admin#streams3:/etc/init.d$ 2013-06-05 17:52:08 E msg:<***> logger could not open file logs/sc_serv.log
2013-06-05 17:52:08 I msg:<***> Logger shutdown
your second snippet contains logger could not open file logs/sc_serv.log. So it tries to write to a file sc_serv.log which it either expects or wants to create in the directory logs which it expects in the current directory. This also explains that it works when you cd to /home/apps/shout32/ first. I guess there's a file /home/apps/shout32/logs/sc_serv.log.
can you configure the location of that file?
can't you just add some cd ... at the start of the script?

Bash script send enter key or prevent cat hang

I am currently running a Minecraft server in a screen session with this command:
(tail -f /path/to/fifo & cat) | java -Xmx2048M -jar minecraft_server.jar nogui
You can shutdown a minecraft server by sending 'stop' in the server console. I am using the fifo to send commands from other bash scripts, and cat to allow input from the actual Minecraft server console in the screen session.
What happens though, is that if you put the command 'stop' in the actual minecraft console, the server ends up hanging right before it should exit because of the 'cat' command. The only way to get past this, is to press enter again after sending the stop command.
How can I get 'cat' to not cause this to hang?
Edit: The full script.
#!/bin/bash
serverDirectory=/opt/games/minecraft
pidFile=$serverDirectory/server.pid
fifoFile=$serverDirectory/server.fifo
cleanup() {
rm -f $pidFile
rm -f $fifoFile
}
if [ ! -p $fifoFile ]; then
mkfifo $fifoFile && chmod 0777 $fifoFile
fi
echo $$ > $pidFile
# restart server if it stops
while true
do
# how minecraft server should handle an interruption
trap "{ echo 'stop' > $fifoFile ; }" SIGINT
(tail -f $fifoFile & cat) | java -Xmx2048M -jar minecraft_server.jar nogui
echo "Restarting server...."
# if interruption occurs before we restart, stop trying to restart and clean up
trap "{ cleanup ; exit 0 ; }" SIGINT SIGTERM
sleep 5
done
I haven't used a minecraft server, so I don't know if I'm on the right track here, but would this work?
#!/bin/sh
fifo="/path/to/fifo"
mkfifo $fifo
trap "rm -f $fifo" 0 1 2 3 6 15
/path/to/java -Xmx2048M -jar minecraft_server.jar nogui < $fifo &
echo $? > /path/to/minecraft.pid
cat > $fifo
This still doesn't kill off the cat once the server quits, but at least it doesn't block the server. You might want to launch the minecraft server in a function that kills the cat when it exits. I suggest keeping the .pid file for possible future use. :-)

start-stop-daemon works at command line but doesn't work in /etc/init.d script

I'm trying to get a starter script (for a ruby gem called ar_sendmail) working in /etc/init.d/ar_sendmail:
#! /bin/sh
echo "in /etc/init.d/ar_sendmail"
DIR=/home/max/work/e_learning_resource/trunk
PATH=/var/lib/gems/1.8/bin
DAEMON=/var/lib/gems/1.8/bin/ar_sendmail
DAEMON_OPTS="-e production -d --batch-size 100 --delay 150"
NAME=ar_sendmail
DESC=ar_sendmail
PID_FILE=/home/max/work/e_learning_resource/trunk/shared/log/ar_sendmail.pid
test -x $DAEMON || exit 0
set -e
case "$1" in
start)
echo -n "Starting $DESC: "
start-stop-daemon -d $DIR --start --quiet --pidfile $PID_FILE \
--exec $DAEMON -- $DAEMON_OPTS
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
kill -TERM `cat $PID_FILE`
rm $PID_FILE
echo "$NAME."
;;
restart)
echo -n "Restarting $DESC: "
kill -TERM `cat $PID_FILE`
rm $PID_FILE
sleep 1
start-stop-daemon -d $DIR --start --quiet --pidfile \
$PID_FILE --exec $DAEMON -- $DAEMON_OPTS
echo "$NAME."
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|reload}" >&2
exit 1
;;
esac
exit 0
It's blowing up on the start-stop-daemon line, saying "start-stop-daemon: not found". But, when i plug the values into that line manually, and run it on the command line, it works.
My first thought was it was the shebang line but #! /bin/sh should be right shouldn't it? It's definitely the right folder and what i use in my other /etc/init.d scripts.
My second thought was that it's sudo related: i'd been testing start-stop-daemon in non-sudo and running /etc/init.d/ar_sendmail in sudo mode. But, i can run start-stop-daemon fine with sudo as well.
Kind of stumped, any ideas?
As #Dysaster points out, you're overwriting your PATH with this line:
PATH=/var/lib/gems/1.8/bin
Because you're giving the complete pathname for your daemon, I think you probably don't even need to add /var/lib/gems/1.8/bin to your path, unless ar_sendmail needs to execute programs in that directory without knowing their path. (That would sure be unfortunate, but easily fixed with: PATH=/var/lib/gems/1.8/bin:$PATH.)
Add a source /etc/profile to the start of the script, so you get your path setup.

Resources