Shell Script failing to run a command - linux

I have a debian server set up with mounted drives from google drive - these sometimes get unmounted, so I have made a script to check for, and remount, unmounted drives.
The script will check against a file in the mounted directory and if it's missing it will attempt to remount the drive.
It will succesfully check all mounts, but is only able to remount "plexdrive" and "plexlib" it fails to mount "decrypt".
There is nothing wrong with the mounting command as it works fine outside of the script.
The script in question:
#!/bin/bash
## Small hack that makes this script work in cronjob
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home22/krealle/check.rclone.mount
## Logfile
LOGFILE=~/log/check-mounts.log
## Variables
Errors=0
## create $LOGFILE
if [ ! -f $LOGFILE ]; then
touch $LOGFILE
echo "INFO: Logfile created." >> $LOGFILE
fi
echo "" >> $LOGFILE
echo "$(date "+%d/%m/%Y %T")" >> $LOGFILE
## Ultimate Check - Smaller log file!
if [[ -f /home22/krealle/mounts/plexdrive/plexdrive_mounted ]] && [[ -f /home22/krealle/mounts/plexdrive-decrypt/mounted ]] && [[ -f /home22/krealle/PlexMedia/PlexLib/mounted ]]; then
echo "INFO: Errors found: $Errors - skipping individual checks." >> $LOGFILE
exit
fi
## check plexdrive mount
if [[ -f /home22/krealle/mounts/plexdrive/plexdrive_mounted ]]; then
echo "INFO: *Plexdrive* Mountcheck successful." >> $LOGFILE
else
echo "ERROR: *Plexdrive* Drive not mounted remount in progress." >> $LOGFILE
## first unmount broken/busy remotes.
fusermount -zu /home22/krealle/mounts/plexdrive
## Mount Plexdrive.
screen -S plexdrive.s: -d -m ./plexdrive -o allow_other -v 4 /home22/krealle/mounts/plexdrive
if [[ -f /home22/krealle/mounts/plexdrive/plexdrive_mounted ]]; then
echo "INFO: *Plexdrive* Remount successful." >> $LOGFILE
else
((Errors++))
echo "CRITICAL: *Plexdrive* Remount failed." >> $LOGFILE
fi
fi
## check decrypt mount
if [[ -f /home22/krealle/mounts/plexdrive-decrypt/mounted ]]; then
echo "INFO: *Plexdrive-Decrypt* Mountcheck successful." >> $LOGFILE
else
echo "ERROR: *Plexdrive-Decrypt* Drive not mounted remount in progress." >> $LOGFILE
## first unmount broken/busy remotes.
fusermount -zu /home22/krealle/mounts/plexdrive-decrypt
## Mount Plexdrive-decrypt.
screen -S rclone.decrypt: -d -m rclone mount --read-only --allow-non-empty --allow-other --buffer-size 128M -v plexdrive2: /home22/krealle/mounts/plexdrive-decrypt
if [[ -f /home22/krealle/mounts/plexdrive-decrypt/mounted ]]; then
echo "INFO: *Plexdrive-Decrypt* Remount successful." >> $LOGFILE
else
((Errors++))
echo "CRITICAL: *Plexdrive-Decrypt* Remount failed." >> $LOGFILE
fi
fi
## check plexlib mount
if [[ -f /home22/krealle/PlexMedia/PlexLib/mounted ]]; then
echo "INFO: *PlexLib* Mountcheck successful." >> $LOGFILE
else
echo "ERROR: *PlexLib* Drive not mounted remount in progress." >> $LOGFILE
## first unmount broken/busy remotes.
fusermount -zu /home22/krealle/PlexMedia/PlexLib
## Mount PlexLib.
unionfs-fuse -o cow,allow_other,direct_io,nonempty,auto_cache,sync_read /home22/krealle/PlexMedia/Local=RW:/home22/krealle/mounts/plexdrive-decrypt=RO /home22/krealle/PlexMedia/PlexLib
if [[ -f /home22/krealle/PlexMedia/PlexLib/mounted ]]; then
echo "INFO: *PlexLib* Remount successful." >> $LOGFILE
else
((Errors++))
echo "CRITICAL: *PlexLib* Remount failed." >> $LOGFILE
fi
fi
echo "Total errors: $Errors " >> $LOGFILE
My script is based on the one found here.

Related

systemd service works different then running the .sh file from user shell trying run a VNC startup script with noVNC

I want to run a .sh file with a systemd service. Let's explain it a little bit. If I go to cd /home/ubuntu I can run ./vnc_startup.sh. This file creates a VNC connection and starts noVNC. Then I go to the browser open the address and login. I can run every command like as example rosrun rviz rviz because I have installed ROS.
If I use this service, it will not work:
cat /etc/systemd/system/novnc.service
[Unit]
After=NetworkManager.service time-sync.target
[Service]
Type=forking
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu
TimeoutStartSec=infinity
TimeoutStopSec=infinity
ExecStartPre=/bin/rm -f /home/ubuntu/no_vnc_startup.log
ExecStartPre=/bin/rm -f /home/ubuntu/vnc_startup.log
ExecStartPre=/bin/rm -f /home/ubuntu/wm.log
ExecStartPre=/bin/rm -f /home/ubuntu/wm_startup.log
ExecStart=/bin/bash -c "source /etc/environment; /home/ubuntu/vnc_startup.sh"
ExecStopPost=/bin/rm -f /home/ubuntu/no_vnc_startup.log
ExecStopPost=/bin/rm -f /home/ubuntu/vnc_startup.log
ExecStopPost=/bin/rm -f /home/ubuntu/wm.log
ExecStopPost=/bin/rm -f /home/ubuntu/wm_startup.log
[Install]
WantedBy=multi-user.target
I also tried it with systemctl --user start novnc.service and put the file inside /usr/lib/systemd/user instead of sudo systemctl start novnc.service and /etc/systemd/system/novnc.service.
Following workaround will work in the noVNC environment: I can open a Terminal. I can see ubuntu#hostname:~$. So it seems to be the right user and I am in the right working directory. Before running as example rosrun rviz rviz I have to run sudo su ubuntu. And then it works. If I had run ./vnc_startup.sh instead of running this script with systemd it works directly without the workaround with sudo su ubuntu.
Hard to explain. I hope you can understand me.
systemctl --user show-environment
HOME=/home/ubuntu
LANG=de_DE
LOGNAME=ubuntu
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
SHELL=/bin/bash
USER=ubuntu
XDG_RUNTIME_DIR=/run/user/1001
The command printenv makes clear that maybe the DISPLAY=:0 is missing, so I tried it with adding
export DISPLAY=:0
xset q
And I also added Environment=XAUTHORITY=/home/ubuntu/.Xauthority:
[Unit]
After=NetworkManager.service time-sync.target
[Service]
Type=forking
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu
Environment=XAUTHORITY=/home/ubuntu/.Xauthority
TimeoutStartSec=infinity
TimeoutStopSec=infinity
ExecStartPre=/bin/rm -f /home/ubuntu/no_vnc_startup.log
ExecStartPre=/bin/rm -f /home/ubuntu/vnc_startup.log
ExecStartPre=/bin/rm -f /home/ubuntu/wm.log
ExecStartPre=/bin/rm -f /home/ubuntu/wm_startup.log
ExecStart=/bin/bash -c "source /etc/environment; export DISPLAY=:0; xset q; /home/ubuntu/vnc_startup.sh"
ExecStopPost=/bin/rm -f /home/ubuntu/no_vnc_startup.log
ExecStopPost=/bin/rm -f /home/ubuntu/vnc_startup.log
ExecStopPost=/bin/rm -f /home/ubuntu/wm.log
ExecStopPost=/bin/rm -f /home/ubuntu/wm_startup.log
[Install]
WantedBy=multi-user.target
Here my log files:
cat no_vnc_startup.log
New 'shlServer01:1 (ubuntu)' desktop is shlServer01:1
Starting applications specified in /home/ubuntu/.vnc/xstartup
Log file is /home/ubuntu/.vnc/shlServer01:1.log
r settings:
- Listen on :6901
- Flash security policy server
- Web server. Web root: /home/ubuntu/noVNC
- No SSL/TLS support (no cert file)
- proxying from :6901 to localhost:5901
Navigate to this URL:
http://shlServer01:6901/vnc.html?host=shlServer01&port=6901
Press Ctrl-C to exit
192.168.0.6 - - [15/Dec/2021 15:16:56] 192.168.0.6: Plain non-SSL (ws://) WebSocket connection
192.168.0.6 - - [15/Dec/2021 15:16:56] 192.168.0.6: Version hybi-13, base64: 'False'
192.168.0.6 - - [15/Dec/2021 15:16:56] 192.168.0.6: Path: '/websockify'
192.168.0.6 - - [15/Dec/2021 15:16:56] connecting to: localhost:5901
cat vnc_startup.log
Killing Xvnc process ID 63164
Xvnc process ID 63164 already killed
cat wm.log
/usr/bin/startxfce4: X server already running on display :0
xfce4-session: Cannot open display: .
▒xfce4-session --help▒ eingeben, um mehr ▒ber die Verwendung zu erfahren.
cat wm_startup.log
------------------ startup of Xfce4 window manager ------------------
No protocol specified
xset: unable to open display ":0"
No protocol specified
xset: unable to open display ":0"
No protocol specified
xset: unable to open display ":0"
No protocol specified
xrdb: Resource temporarily unavailable
xrdb: Can't open display ':0'
No protocol specified
No protocol specified
/usr/bin/startxfce4: X server already running on display :0
xfce4-session: Cannot open display: .
▒xfce4-session --help▒ eingeben, um mehr ▒ber die Verwendung zu erfahren.
What surprises me is that this is not the error. The error messages also come when I start the script from the terminal and then it works.
The vnc_startup.sh looks like following:
#!/bin/bash
### every exit != 0 fails the script
set -e
## print out help
help (){
echo "
OPTIONS:
-w, --wait (default) keeps the UI and the vncserver up until SIGINT or SIGTERM will received
-s, --skip skip the vnc startup and just execute the assigned command.
example: docker run consol/centos-xfce-vnc --skip bash
-d, --debug enables more detailed startup output
e.g. 'docker run consol/centos-xfce-vnc --debug bash'
-h, --help print out this help
Fore more information see: https://github.com/ConSol/docker-headless-vnc-container
"
}
if [[ $1 =~ -h|--help ]]; then
help
exit 0
fi
# should also source /home/ubuntu/generate_container_user
source /home/ubuntu/.bashrc
# add `--skip` to startup args, to skip the VNC startup procedure
if [[ $1 =~ -s|--skip ]]; then
echo -e "\n\n------------------ SKIP VNC STARTUP -----------------"
echo -e "\n\n------------------ EXECUTE COMMAND ------------------"
echo "Executing command: '${#:2}'"
exec "${#:2}"
fi
if [[ $1 =~ -d|--debug ]]; then
echo -e "\n\n------------------ DEBUG VNC STARTUP -----------------"
export DEBUG=true
fi
## correct forwarding of shutdown signal
cleanup () {
kill -s SIGTERM $!
exit 0
}
trap cleanup SIGINT SIGTERM
## write correct window size to chrome properties
/home/ubuntu/chrome-init.sh
## resolve_vnc_connection
VNC_IP=$(hostname -i)
## change vnc password
echo -e "\n------------------ change VNC password ------------------"
# first entry is control, second is view (if only one is valid for both)
mkdir -p "/home/ubuntu/.vnc"
PASSWD_PATH="/home/ubuntu/.vnc/passwd"
if [[ -f $PASSWD_PATH ]]; then
echo -e "\n--------- purging existing VNC password settings ---------"
rm -f $PASSWD_PATH
fi
if [[ $VNC_VIEW_ONLY == "true" ]]; then
echo "start VNC server in VIEW ONLY mode!"
#create random pw to prevent access
echo $(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 20) | vncpasswd -f > $PASSWD_PATH
fi
echo "ubuntu" | vncpasswd -f >> $PASSWD_PATH
chmod 600 $PASSWD_PATH
## start vncserver and noVNC webclient
echo -e "\n------------------ start noVNC ----------------------------"
if [[ $DEBUG == true ]]; then echo "/home/ubuntu/noVNC/utils/launch.sh --vnc localhost:5901 --listen 6901"; fi
/home/ubuntu/noVNC/utils/launch.sh --vnc localhost:5901 --listen 6901 &> /home/ubuntu/no_vnc_startup.log &
PID_SUB=$!
echo -e "\n------------------ start VNC server ------------------------"
echo "remove old vnc locks to be a reattachable container"
vncserver -kill :1 &> /home/ubuntu/vnc_startup.log \
|| rm -rfv /tmp/.X*-lock /tmp/.X11-unix &> /home/ubuntu/vnc_startup.log \
|| echo "no locks present"
echo -e "start vncserver with param: VNC_COL_DEPTH=24, VNC_RESOLUTION=1280x1024\n..."
if [[ $DEBUG == true ]]; then echo "vncserver :1 -depth 24 -geometry 1280x1024"; fi
vncserver :1 -depth 24 -geometry 1280x1024 &> /home/ubuntu/no_vnc_startup.log
echo -e "start window manager\n..."
/home/ubuntu/wm_startup.sh &> /home/ubuntu/wm_startup.log
## log connect options
echo -e "\n\n------------------ VNC environment started ------------------"
echo -e "\nVNCSERVER started on DISPLAY= :1 \n\t=> connect via VNC viewer with $VNC_IP:5901"
echo -e "\nnoVNC HTML client started:\n\t=> connect via http://$VNC_IP:6901/?password=...\n"
if [[ $DEBUG == true ]] || [[ $1 =~ -t|--tail-log ]]; then
echo -e "\n------------------ /home/ubuntu/.vnc/*:1.log ------------------"
# if option `-t` or `--tail-log` block the execution and tail the VNC log
tail -f /home/ubuntu/*.log /home/ubuntu/.vnc/*:1.log
fi
if [ -z "$1" ] || [[ $1 =~ -w|--wait ]]; then
wait $PID_SUB
else
# unknown option ==> call command
echo -e "\n\n------------------ EXECUTE COMMAND ------------------"
echo "Executing command: '$#'"
exec "$#"
fi
The wm_startup.sh looks like this:
#!/usr/bin/env bash
### every exit != 0 fails the script
set -e
echo -e "\n------------------ startup of Xfce4 window manager ------------------"
### disable screensaver and power management
xset -dpms &
xset s noblank &
xset s off &
/usr/bin/startxfce4 --replace > /home/ubuntu/wm.log &
sleep 1
cat /home/ubuntu/wm.log
And it should not be important but the launch.sh file fom noVNC looks like this:
#!/usr/bin/env bash
# Copyright 2016 Joel Martin
# Copyright 2016 Solly Ross
# Licensed under MPL 2.0 or any later version (see LICENSE.txt)
usage() {
if [ "$*" ]; then
echo "$*"
echo
fi
echo "Usage: ${NAME} [--listen PORT] [--vnc VNC_HOST:PORT] [--cert CERT] [--ssl-only]"
echo
echo "Starts the WebSockets proxy and a mini-webserver and "
echo "provides a cut-and-paste URL to go to."
echo
echo " --listen PORT Port for proxy/webserver to listen on"
echo " Default: 6080"
echo " --vnc VNC_HOST:PORT VNC server host:port proxy target"
echo " Default: localhost:5900"
echo " --cert CERT Path to combined cert/key file"
echo " Default: self.pem"
echo " --web WEB Path to web files (e.g. vnc.html)"
echo " Default: ./"
echo " --ssl-only Disable non-https connections."
echo " "
exit 2
}
NAME="$(basename $0)"
REAL_NAME="$(readlink -f $0)"
HERE="$(cd "$(dirname "$REAL_NAME")" && pwd)"
PORT="6080"
VNC_DEST="localhost:5900"
CERT=""
WEB=""
proxy_pid=""
SSLONLY=""
die() {
echo "$*"
exit 1
}
cleanup() {
trap - TERM QUIT INT EXIT
trap "true" CHLD # Ignore cleanup messages
echo
if [ -n "${proxy_pid}" ]; then
echo "Terminating WebSockets proxy (${proxy_pid})"
kill ${proxy_pid}
fi
}
# Process Arguments
# Arguments that only apply to chrooter itself
while [ "$*" ]; do
param=$1; shift; OPTARG=$1
case $param in
--listen) PORT="${OPTARG}"; shift ;;
--vnc) VNC_DEST="${OPTARG}"; shift ;;
--cert) CERT="${OPTARG}"; shift ;;
--web) WEB="${OPTARG}"; shift ;;
--ssl-only) SSLONLY="--ssl-only" ;;
-h|--help) usage ;;
-*) usage "Unknown chrooter option: ${param}" ;;
*) break ;;
esac
done
# Sanity checks
which netstat >/dev/null 2>&1 \
|| die "Must have netstat installed"
netstat -ltn | grep -qs ":${PORT} .*LISTEN" \
&& die "Port ${PORT} in use. Try --listen PORT"
trap "cleanup" TERM QUIT INT EXIT
# Find vnc.html
if [ -n "${WEB}" ]; then
if [ ! -e "${WEB}/vnc.html" ]; then
die "Could not find ${WEB}/vnc.html"
fi
elif [ -e "$(pwd)/vnc.html" ]; then
WEB=$(pwd)
elif [ -e "${HERE}/../vnc.html" ]; then
WEB=${HERE}/../
elif [ -e "${HERE}/vnc.html" ]; then
WEB=${HERE}
elif [ -e "${HERE}/../share/novnc/vnc.html" ]; then
WEB=${HERE}/../share/novnc/
else
die "Could not find vnc.html"
fi
# Find self.pem
if [ -n "${CERT}" ]; then
if [ ! -e "${CERT}" ]; then
die "Could not find ${CERT}"
fi
elif [ -e "$(pwd)/self.pem" ]; then
CERT="$(pwd)/self.pem"
elif [ -e "${HERE}/../self.pem" ]; then
CERT="${HERE}/../self.pem"
elif [ -e "${HERE}/self.pem" ]; then
CERT="${HERE}/self.pem"
else
echo "Warning: could not find self.pem"
fi
# try to find websockify (prefer local, try global, then download local)
if [[ -e ${HERE}/websockify ]]; then
WEBSOCKIFY=${HERE}/websockify/run
if [[ ! -x $WEBSOCKIFY ]]; then
echo "The path ${HERE}/websockify exists, but $WEBSOCKIFY either does not exist or is not executable."
echo "If you intended to use an installed websockify package, please remove ${HERE}/websockify."
exit 1
fi
echo "Using local websockify at $WEBSOCKIFY"
else
WEBSOCKIFY=$(which websockify 2>/dev/null)
if [[ $? -ne 0 ]]; then
echo "No installed websockify, attempting to clone websockify..."
WEBSOCKIFY=${HERE}/websockify/run
git clone https://github.com/novnc/websockify ${HERE}/websockify
if [[ ! -e $WEBSOCKIFY ]]; then
echo "Unable to locate ${HERE}/websockify/run after downloading"
exit 1
fi
echo "Using local websockify at $WEBSOCKIFY"
else
echo "Using installed websockify at $WEBSOCKIFY"
fi
fi
echo "Starting webserver and WebSockets proxy on port ${PORT}"
#${HERE}/websockify --web ${WEB} ${CERT:+--cert ${CERT}} ${PORT} ${VNC_DEST} &
${WEBSOCKIFY} ${SSLONLY} --web ${WEB} ${CERT:+--cert ${CERT}} ${PORT} ${VNC_DEST} &
proxy_pid="$!"
sleep 1
if ! ps -p ${proxy_pid} >/dev/null; then
proxy_pid=
echo "Failed to start WebSockets proxy"
exit 1
fi
echo -e "\n\nNavigate to this URL:\n"
if [ "x$SSLONLY" == "x" ]; then
echo -e " http://$(hostname):${PORT}/vnc.html?host=$(hostname)&port=${PORT}\n"
else
echo -e " https://$(hostname):${PORT}/vnc.html?host=$(hostname)&port=${PORT}\n"
fi
echo -e "Press Ctrl-C to exit\n\n"
wait ${proxy_pid}
Suggesting to simply your /etc/systemd/system/novnc.service service unit with a single script for ExecStart command and a single script for ExecStop
/etc/systemd/system/novnc.service
[Unit]
After=NetworkManager.service time-sync.target
[Service]
Type=forking
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu
Environment=XAUTHORITY=/home/ubuntu/.Xauthority
TimeoutStartSec=infinity
TimeoutStopSec=infinity
ExecStart=/bin/bash -c "/home/ubuntu/servic_vnc_startup.sh"
ExecStop=/bin/bash -c "/home/ubuntu/servic_vnc_shutdown.sh"
[Install]
WantedBy=multi-user.target
/home/ubuntu/servic_vnc_startup.sh
#!\bin\bash
source /home/ubuntu/.bash_profile
source /etc/environment
export DISPLAY=:0
xset q;
rm -f /home/ubuntu/{no_vnc_startup.log,vnc_startup.log,wm.log,wm_startup.log}
/home/ubuntu/vnc_startup.sh
/home/ubuntu/servic_vnc_shutdown.sh
#!\bin\bash
source /home/ubuntu/.bash_profile
source /etc/environment
export DISPLAY=:0
xset q;
pkill -9 -f "/home/ubuntu/vnc_startup.sh"
rm -f /home/ubuntu/{no_vnc_startup.log,vnc_startup.log,wm.log,wm_startup.log}
Debugging
Login as user ubuntu.
Run /home/ubuntu/servic_vnc_startup.sh from command line.
If fails, fix it till it is successful.
Then try running /home/ubuntu/servic_vnc_startup.sh as user noboby:
sudo -u nobody "/home/ubuntu/servic_vnc_startup.sh"
User nobody has no shell and no environment context, as is the systemd service /etc/systemd/system/novnc.service.
If user nobody can run /home/ubuntu/servic_vnc_startup.sh then the /etc/systemd/system/novnc.service service unit can do as well.
Do same testing pattern with /home/ubuntu/servic_vnc_shutdown.sh
Lessons to learn:
Simplify service unit as much as possible.
Pull all scripting to a single shell script. Debug single shell script.
Avoid debugging handling service unit once deployed. Instead debug and modify called script.
Use user nobody user, to debug script to run without environment context and without shell.

run jar-file on startup linux

I've used a standard bash-startup script for autostarting my Teamspeak Server - which works perfectly. Now I've done the same for the JTS3 Server Mod, problem: It's a .jar-file and doesn't start. If I run the .jar/startscript manually it works just fine.
Here's the script in /etc/init.d/
#!/bin/bash
### BEGIN INIT INFO
# Provides: jts3servermod
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: JTS3 Server Mod
### END INIT INFO
# INIT Script by www.SysADMINsLife.com
######################################
# Customize values for your needs: "User"; "DIR"
USER="ts"
DIR="/home/ts/JTS3ServerMod"
###### Teamspeak 3 server start/stop script ######
case "$1" in
start)
su $USER -c "${DIR}/jts3servermod_startscript.sh start"
;;
stop)
su $USER -c "${DIR}/jts3servermod_startscript.sh stop"
;;
restart)
su $USER -c "${DIR}/jts3servermod_startscript.sh restart"
;;
status)
su $USER -c "${DIR}/jts3servermod_startscript.sh status"
;;
*)
echo "Usage: {start|stop|restart|status}" >&2
exit 1
;;
esac
exit 0
of course it is linked in the runlevel-folders with update-rc.d jts3servermod defaults.
the servermod startscript (jts3servermod_startscript.sh) is:
#!/bin/sh
# JTS3ServerMod Linux start script
# Created by Stefan "Stefan1200" Martens
# The author of this script is not responsible for any damage or data loss!
JAVA_COMMANDLINE_PARAMETERS="-mx30M" # You can add java arguments here, like the -mx30M argument!
JTS3SERVERMOD_COMMANDLINE_PARAMETERS="" # You can add JTS3ServerMod arguments here, like the -config and -log argument!
BINARYPATH="$(pwd)" # This have to point to the JTS3ServerMod directory!
# Don't change the lines below, if you are not a sh script expert!
cd "${BINARYPATH}"
BINARYNAME="JTS3ServerMod.jar"
ROOTUID="0"
case "$1" in
java)
if which java >/dev/null 2>&1 ; then
echo "Java is already installed:"
java -version
else
if [ "$(id -u)" -ne "$ROOTUID" ] ; then
echo "Start this script as root to start the automatic installation of the Java runtime environment."
echo "You can also read the system requirements of the JTS3ServerMod in the readme.txt file for a manual installation of the Java runtime environment."
exit 6
else
read -p "Do you wish to install the Java runtime environment? (y/n) " yn
case $yn in
[Yy]* ) installJava; break;;
* ) echo "Aborted!"; exit 6;;
esac
fi
fi
;;
start)
if ! which java >/dev/null 2>&1 ; then
echo "The JTS3ServerMod needs the Java runtime environment installed to run!"
echo "Start this script with the java argument as root to start the automatic installation of the Java runtime environment:"
echo "$0 java"
echo "You can also read the system requirements of the JTS3ServerMod in the readme.txt file for a manual installation of the Java runtime environment."
exit 6
fi
if [ "$(id -u)" -eq "$ROOTUID" ] ; then
echo "For security reasons it is prefered not to run the JTS3ServerMod as root!"
fi
if [ -e jts3servermod.pid ]; then
if ( kill -0 $(cat jts3servermod.pid) 2> /dev/null ); then
echo "The JTS3ServerMod is already running, try restart or stop!"
exit 1
else
echo "jts3servermod.pid found, but no JTS3ServerMod running. Possibly your previously started JTS3ServerMod crashed!"
echo "Please view the logfile for details."
rm -f jts3servermod.pid
fi
fi
echo "Starting the JTS3ServerMod..."
if [ -e "$BINARYNAME" ]; then
java ${JAVA_COMMANDLINE_PARAMETERS} -jar ${BINARYNAME} ${JTS3SERVERMOD_COMMANDLINE_PARAMETERS} > /dev/null &
PID=$!
ps -p ${PID} > /dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "JTS3ServerMod could not start!"
else
echo $PID > jts3servermod.pid
echo "JTS3ServerMod started, for details please view the log file!"
fi
else
echo "Could not find the file $BINARYNAME, aborting!"
exit 5
fi
;;
stop)
if [ -e jts3servermod.pid ]; then
echo -n "Stopping the JTS3ServerMod.."
if ( kill -TERM $(cat jts3servermod.pid) 2> /dev/null ); then
c=1
while [ "$c" -le 120 ]; do
if ( kill -0 $(cat jts3servermod.pid) 2> /dev/null ); then
echo -n "."
sleep 1
else
break
fi
c=$(($c+1))
done
fi
if ( kill -0 $(cat jts3servermod.pid) 2> /dev/null ); then
echo "JTS3ServerMod is not shutting down cleanly - killing!"
kill -KILL $(cat jts3servermod.pid)
else
echo "done"
fi
rm -f jts3servermod.pid
else
echo "No JTS3ServerMod running (jts3servermod.pid is missing)!"
exit 7
fi
;;
restart)
$0 stop && $0 start || exit 1
;;
status)
if [ -e jts3servermod.pid ]; then
if ( kill -0 $(cat jts3servermod.pid) 2> /dev/null ); then
echo "JTS3ServerMod is running!"
else
echo "JTS3ServerMod seems to have died!"
fi
else
echo "No JTS3ServerMod running (jts3servermod.pid is missing)!"
fi
;;
*)
echo "Usage: ${0} {start|stop|restart|status|java}"
exit 2
esac
exit 0
I also tried to write an own simple script for only starting the jar and catching the pid and writing it into a file.
None of these scripts wanted to start my .jar file during the startup.
As you can see, the first script is a template for starting Teamspeak Servers during boot. I only replaced some stuff with my Server Mod paths and scripts and put into /etc/init.d/ (chmod 755 was executed of course).
Maybe some of you have other approaches to solve that strange circumstances.
I don't know if the problem was solved in the meantime, but while experimenting with the same issue. I figured out that the script could not find the jar file. So I added:
#!/bin/sh
# JTS3ServerMod Linux start script
# Created by Stefan "Stefan1200" Martens
# The author of this script is not responsible for any damage or data loss!
cd "$(dirname "$0")"
...
At the beginning of the jts3servermod_startscript.sh to ensure that the "working directory" is correct.
BTW - My init script:
jts-bot
#!/bin/sh
### BEGIN INIT INFO
# Provides: jts-bot
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: JTS3-Bot for TeamSpeak
### END INIT INFO
USER="teamspeak"
DIR="/home/teamspeak/JTS3ServerMod"
###### JTS3ServerMod start/stop script ######
case "$1" in
start)
su $USER -c "${DIR}/jts3servermod_startscript.sh start"
;;
stop)
su $USER -c "${DIR}/jts3servermod_startscript.sh stop"
;;
restart)
su $USER -c "${DIR}/jts3servermod_startscript.sh restart"
;;
status)
su $USER -c "${DIR}/jts3servermod_startscript.sh status"
;;
*)
echo "Usage: -bash {start|stop|restart|status}" >&2
exit 1
;;
esac
exit 0

Bash Detect Mounted Folder as Directory

I am creating this bashs script that has a folder path, passed as a paramter.
And if it detects that paramter is a directory, then it uses it as a path for script work.
But for some reason, it denies treating this folder path as a directory.
Which has befuddled me to no end.
This is a mounted external 3tb hard drive, works fine, no issues, what so ever.
But is mounted as /media/wdmybook/
I have this testing script to help me debug and identify the problem.
#!/bin/bash
DIR="/media/wdmybook/folder"
if grep -qs '$DIR' /proc/mounts; then
echo "It's mounted."
else
echo "It's not mounted."
fi
if [ ! -d "$DIR" ]; then
echo "Directory does not exist!"
elif [ "$DIR" != -d ]; then
echo "Not a Directory"
else
echo "Path is okay"
fi
But everytime I run it, it detects the path as an invalid directory, and it is not mounted.
So what am I missing or not seeing?
Is this a permissions issue?
I am running this on Debian Wheezy XFCE.
You should rewrite your if condition to something like that:
if [ ! -e "$DIR" ]; then
echo "Directory does not exist!"
elif [ ! -d "$DIR" ]; then
echo "Not a Directory"
else
echo "Path is okay"
fi
For details see man test

unix sftp issue

I am not posting entire code here but part of it.Below code giving errors.I am trying to store all sftp commands and then performing actual sftp.
export SFTP_BATCH_FILE='/var/tmp/SFTP_BATCH_FILE'
#------------------------------------------------------------------------
# Create sftp script
#------------------------------------------------------------------------
rm -f $SFTP_BATCH_FILE
echo "lcd $SOURCE_FILE_DIRECTORY " > $SFTP_BATCH_FILE
echo "cd $DESTINATION_FILE_DIRECTORY " >> $SFTP_BATCH_FILE
if [ -z $FILE_TO_UPLOAD_TESTD ] then
echo "put $FILE_TO_UPLOAD_TESTD " >> $SFTP_BATCH_FILE
fi
if [ -z $FILE_TO_UPLOAD_TESTDF ] then
echo "put $FILE_TO_UPLOAD_TESTDF " >> $SFTP_BATCH_FILE
fi
echo "bye" >> $SFTP_BATCH_FILE
#------------------------------------------------------------------------
# Do sftp
#------------------------------------------------------------------------
echo " Before SFTP " >> $LOG_FILE
if [[ -z $ FILE_TO_UPLOAD && -z $ FILE_TO_UPLOAD1 ]] then
echo “No files to transfer” >> $LOG_FILE
mv $LOG_FILE $LOG_DIRECTORY
exit 1
else
echo “Attempting to connect to Remote Server $REMOTE_SERVER_PROD” >> $LOG_FILE
/usr/bin/sftp –v -oPort=$SFTP_PORT -b $SFTP_BATCH_FILE $SOURCE_FUNCTIONAL_ID#$REMOTE_SERVER_PROD >> $LOG_FILE 2 >> $LOG_FILE
fi
Errors i am getting:
rm: /var/tmp/SFTP_BATCH_FILE is a directory
test.ksh[89]: /var/tmp/SFTP_BATCH_FILE: cannot create
test.ksh[90]: /var/tmp/SFTP_BATCH_FILE: cannot create
Regards,
Chai
The clue is in the error message
rm: /var/tmp/SFTP_BATCH_FILE is a directory
As the directory is still there your subsequent commands cannot create the SFTP_BATCH_FILE file.
rm -f cannot remove directories. Use rm -rf instead.
Edit:
Just to clarify, -r is recursive meaning that directories are delete as well, -f is force which means that nonexistent files/directories don't cause an error and the command doesn't prompt.

check if file exists on remote host with ssh

I would like to check if a certain file exists on the remote host.
I tried this:
$ if [ ssh user#localhost -p 19999 -e /home/user/Dropbox/path/Research_and_Development/Puffer_and_Traps/Repeaters_Network/UBC_LOGS/log1349544129.tar.bz2 ] then echo "okidoke"; else "not okay!" fi
-sh: syntax error: unexpected "else" (expecting "then")
In addition to the answers above, there's the shorthand way to do it:
ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists" || echo "File does not exist";
-q is quiet mode, it will suppress warnings and messages.
As #Mat mentioned, one advantage of testing like this is that you can easily swap out the -f for any test operator you like: -nt, -d, -s etc...
Test Operators: http://tldp.org/LDP/abs/html/fto.html
Here is a simple approach:
#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no username#192.168.1.2'
FILE_NAME=/home/user/file.txt
SSH_PASS='sshpass -p password-for-remote-machine'
if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
then
echo "File exists"
else
echo "File does not exist"
fi
You need to install sshpass on your machine to work it.
Can't get much simpler than this :)
ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
# your file exists
fi
As suggested by dimo414, this can be collapsed to:
if ssh host "test -e /path/to/file"; then
# your file exists
fi
one line, proper quoting
ssh remote_host test -f "/path/to/file" && echo found || echo not found
You're missing ;s. The general syntax if you put it all in one line would be:
if thing ; then ... ; else ... ; fi
The thing can be pretty much anything that returns an exit code. The then branch is taken if that thing returns 0, the else branch otherwise.
[ isn't syntax, it's the test program (check out ls /bin/[, it actually exists, man test for the docs – although can also have a built-in version with different/additional features.) which is used to test various common conditions on files and variables. (Note that [[ on the other hand is syntax and is handled by your shell, if it supports it).
For your case, you don't want to use test directly, you want to test something on the remote host. So try something like:
if ssh user#host test -e "$file" ; then ... ; else ... ; fi
Test if a file exists:
HOST="example.com"
FILE="/path/to/file"
if ssh $HOST "test -e $FILE"; then
echo "File exists."
else
echo "File does not exist."
fi
And the opposite, test if a file does not exist:
HOST="example.com"
FILE="/path/to/file"
if ! ssh $HOST "test -e $FILE"; then
echo "File does not exist."
else
echo "File exists."
fi
ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists"
The above will run the echo command on the machine you're running the ssh command from. To get the remote server to run the command:
ssh -q $HOST "[[ ! -f $FILE_PATH ]] && touch $FILE_PATH"
Silent check if file exist and perform if not
if ! ssh $USER#$HOST "test -e file.txt" 2> /dev/null; then
echo "File not exist"
fi
You can specify the shell to be used by the remote host locally.
echo 'echo "Bash version: ${BASH_VERSION}"' | ssh -q localhost bash
And be careful to (single-)quote the variables you wish to be expanded by the remote host; otherwise variable expansion will be done by your local shell!
# example for local / remote variable expansion
{
echo "[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'" |
ssh -q localhost bash
echo '[[ $- == *i* ]] && echo "Interactive" || echo "Not interactive"' |
ssh -q localhost bash
}
So, to check if a certain file exists on the remote host you can do the following:
host='localhost' # localhost as test case
file='~/.bash_history'
if `echo 'test -f '"${file}"' && exit 0 || exit 1' | ssh -q "${host}" sh`; then
#if `echo '[[ -f '"${file}"' ]] && exit 0 || exit 1' | ssh -q "${host}" bash`; then
echo exists
else
echo does not exist
fi
I wanted also to check if a remote file exist but with RSH. I have tried the previous solutions but they didn't work with RSH.
Finally, I did I short function which works fine:
function existRemoteFile ()
{
REMOTE=$1
FILE=$2
RESULT=$(rsh -l user $REMOTE "test -e $FILE && echo \"0\" || echo \"1\"")
if [ $RESULT -eq 0 ]
then
return 0
else
return 1
fi
}
On CentOS machine, the oneliner bash that worked for me was:
if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi
It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.
This also works :
if ssh user#ip "[ -s /path/file_name ]" ;then
status=RECEIVED ;
else
status=MISSING ;
fi
#its simple
if [[ "`ssh -q user#hostname ls /dir/filename.abc 2>dev/null`" == "/dir/filename.abc" ]]
then
echo "file exists"
else
echo "file not exists"
fi

Resources