How to run a Shell Script before shutdown on CentOS - linux

I want to send an email when the system is going to shutdown to an email ID. I have CentOS 6.4. Below is my Script.
cat /ect/init.d/sendshtmail
#!/bin/bash
EMAIL="example#example.com"
SHUTDOWNSUBJECT="["`hostname`"] - System Shutdown"
SHUTDOWNBODY="This is an automated message to notify you that "`hostname`" is shutting down.
LOCKFILE=/var/lock/subsys/SystemEmail
echo "${SHUTDOWNBODY}" | mutt -s "${SHUTDOWNSUBJECT}" ${EMAIL}
It has the appropriate permission. While running it manually it's working perfectly. I have just symlinked it to /etc/rc0.d/ folder. By issuing below command.
ln -s /etc/init.d/sendshtmail /etc/rc0.d/K00sendshtmail
But the script is not sending any email during shutdown. Thanks in Advance.

Place your shell script in /etc/init.d with executable permission and symlink name should start with K##. If you want to execute your script at first place immediately after shut down then name it with K00scriptname. Script started will K will be executed first based on ascending order then script with S.
ln -s /etc/init.d/script /etc/rc0.d/K00scriptname
Shutdown command will send the stop signal to script, your script (K00scriptname) should have stop function like example
stop()
{
echo "executing scriptname"
"Your script logic"
}
case "$1" in
stop)
stop
;;
esac
Most important, K00scriptname will execute only if there would be lock file present in /var/lock/subsys folder, so do "touch /var/lock/subsys/scriptname" then check by doing shutdown.

Try to set executable permissions for your script. Sometimes you need to do that to activate it.
chmod 755 /etc/init.d/sendshtmail
Also try to use absolute paths for your command, while quoting the other variable as well.
echo "${SHUTDOWNBODY}" | /usr/bin/mutt -s "${SHUTDOWNSUBJECT}" "${EMAIL}"
Another attempt is to switch your user to your current user e.g.
echo "${SHUTDOWNBODY}" | su -l -c "/usr/bin/mutt -s \"${SHUTDOWNSUBJECT}\" \"${EMAIL}\"" yourusername

ln -s /etc/init.d/sendshtmail /etc/rc0.d/S01sendshtmail
The symlink name should begin with a S - for Start (K for Kill)
The two-digit specifies the order of execution for your script, the lowest numbered being execute first.

Related

inotifywait shell script run as daemon

I have a script that watches a directory (recursively) and performs a command when a file changes. This is working correctly when the monitoring flag is used as below:
#!/bin/sh
inotifywait -m -r /path/to/directory |
while read path action file; do
if [ <perform a check> ]
then
my_command
fi
done
However, I want to run this on startup and in the background, so naïvely thought I could change the -m flag to -d (run inotifywait as daemon, and include an --outfile location) and then add this to rc.local to have this run at startup. Where am I going wrong?
Well .... with -d it backgrounds itself and outputs ONLY to outfile, so your whole pipe & loop construct is moot, and it never sees any data.
Incron is a cron-like daemon for inotify events.
Just need to use incrontab and an entry for your task:
/path/to/directory IN_ALL_EVENTS /usr/local/bin/my-script $# $# $%
And /local/bin/my-script would be:
#! /bin/bash
local path=$1
local action=$2
local file=$3
if [ <perform a check> ]
then
my_command
fi
You need to add a single & to the end of command in your /etc/rc.local
Putting a single & at the end of a command means Run this program in the background so the user can still have input.

Execute shell script whithin another script prompts: No such file or directory

(I'm new in shell script.)
I've been stuck with this issue for a while. I've tried different methods but without luck.
Description:
When my script attempt to run another script (SiebelMessageCreator.sh, which I don't own) it prompts:
-bash: ./SiebelMessageCreator.sh: No such file or directory
But the file exists and has execute permissions:
-rwxr-xr-x 1 owner ownergrp 322 Jun 11 2015 SiebelMessageCreator.sh
The code that is performing the script execution is:
(cd $ScriptPath; su -c './SiebelMessageCreator.sh' - owner; su -c 'nohup sh SiebelMessageSender.sh &' - owner;)
It's within a subshell because I first thought that it was throwing that message because my script was running in my home directory (When I run the script I'm root and I've moved to my non-root home directory to run the script because I can't move my script [ policies ] to the directory where the other script resides).
I've also tried with the sh SCRIPT.sh ./SCRIPT.sh. And changing the shebang from bash to ksh because the SiebelMessageCreator.sh has that shell.
The su -c 'sh SCRIPT.sh' - owner is necessary. If the script runs as root and not as owner it brokes something (?) (that's what my partners told me from their experience executing it as root). So I execute it as the owner.
Another thing that I've found in my research is that It can throw that message if it's a Symbolic link. I'm really not sure if the content of the script it's a symbolic link. Here it is:
#!/bin/ksh
BASEDIRROOT=/path/to/file/cpp-plwsutil-c
ore-runtime.jar (path changed on purpose for this question)
java -classpath $BASEDIRROOT com.hp.cpp.plwsutil.SiebelMessageCreator
exitCode=$?
echo "`date -u '+%Y-%m-%d %H:%M:%S %Z'` - Script execution finished with exit code $exitCode."
exit $exitCode
As you can see it's a very siple script that just call a .jar. But also I can't add it to my script [ policies ].
If I run the ./SiebelMessageCreator.sh manually it works just fine. But not with my script. I suppose that discards the x64 x32 bits issue that I've also found when I googled?
By the way, I'm automating some tasks, the ./SiebelMessageCreator.sh and nohup sh SiebelMessageSender.sh & are just the last steps.
Any ideas :( ?
did you try ?
. ./SiebelMessageCreator.sh
you can also perform which sh or which ksh, then modify the first line #!/bin/ksh

How to pipe postfix input to a specific script with user and path?

How can I pipe emails for a specific user to a script AND that script to be ran with a specific user's login.
I have this in my /etc/postfix/master.cf file:
my_transport unix - n n - 50 pipe
flags=R user=deploy argv=/srv/www/myscript
My script prints $PATH and whoami to a file and this is what I get
PATH=/usr/bin:/bin
whoami = deploy
If I run sudo su - deploy and run echo "PATH=$PATH" and echo "whoami = $(whoami)" I get
PATH=/home/deploy/.rbenv/shims:/home/deploy/.rbenv/bin:/home/deploy/.rbenv/shims:/home/deploy/.rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
whoami = deploy
How do I make postfix run myscript as deploy user but with it's real path, not the short one.
Thank you!
I made a dirty hack with a new script that I use to call my old script
PATH=/home/deploy/.rbenv/bin:/home/deploy/.rbenv/shims:$PATH
source "$1"
exit $?
More info in this diff
Hope this will be useful to somebody else :D

Arch Linux / systemd - prevent any kind of shutdown/rebboot

I'm running Arch-based Manjaro Linux and wrote myself a little update program, that starts every 7 hours and runs completely in the background. This update program is started by systemd.
What I wanna know is: How can I prevent any system shutdown/reboot during the time this program runs no matter if the user just wants to turn it off or any program wants to do so.
The best would be, if any shutdown/reboot action wouldn't be cancelled but delayed instead, so when the update program has finished its run, the shutdown/reboot continues.
My systemd parts are:
uupgrades.timer
[Unit]
Description=UU Upgrades Timer
[Timer]
OnBootSec=23min
OnUnitActiveSec=7h
Unit=uupgrades.target
[Install]
WantedBy=basic.target
uupgrades.target
[Unit]
Description=UU Upgrades Timer Target
StopWhenUnneeded=yes
and in the folder uupgrades.target.wants
uupgrades.service
[Unit]
Description=UU Update Program
[Service]
Nice=19
IOSchedulingClass=2
IOSchedulingPriority=7
ExecStart=/usr/bin/uupgrades
How can I achieve this?
If a user with sufficient permissions to reboot the server or manipulate processes wants to stop or reboot the machine you cant stop them. That's just how linux works. You should set up permissions and accounts such that no other users have root permissions or permissions sufficient to manipulate the process or user that the process is running as.
When I want to block myself from rebooting or shutdown, I alias my usual shutdown and reboot aliases to beep;beep;beep;.
In multiuser environments you could move the reboot, shutdown etc. binaries and move them back, when shutdown should be allowed again.
You could also temporarily move an executable shell script outputting information about the postponed shutdown possibility in place of the corresponding binaries. This script could set a flag, if a shutdown was requested.
Q&D example script:
#!/usr/bin/env bash
echo "preventing reboot"
BACKUPBINARY_REBOOT=$(mktemp);
mv /bin/reboot $BACKUPBINARY_REBOOT;
FLAGFILE=$(mktemp);
echo '#!/usr/bin/env bash' > /bin/reboot;
echo '# original reboot binary was moved to'"$BACKUPBINARY_REBOOT" >> /bin/reboot;
echo 'echo request-reboot > '"$FLAGFILE" >> /bin/reboot;
echo 'echo reboot is prevented, your request will trigger later' >> /bin/reboot;
chmod 666 "$FLAGFILE";
chmod +x /bin/reboot;
echo "postponed reboot - press enter to allow it again and make up for requested reboot";
read;
mv "$BACKUPBINARY_REBOOT" /bin/reboot;
if grep -q request-reboot "$FLAGFILE"; then
rm $FLAGFILE;
/bin/reboot;
fi
You can add another systemd service at /usr/lib/systemd/system-shutdown/ which will be run at shutdown, and have it check if your update script is running, and if so, cancel or delay the shutdown.

How to execute a script when xfce session ends

Is it possible to run a script/command when the xfce session stops ?
See http://mail.xfce.org/pipermail/xfce/2012-November/031694.html - There, Erik Habicht suggested creating a wrapper script in /usr/local/bin/xfce4-session (or another dir that precedes the dir where xfce4-session is installed, /usr/bin in your PATH). This way, you do not have to change /usr/bin/X11/xfce4-session, so it can be updated independently.
#!/bin/bash
# Add your own pre-session logic here
/usr/bin/xfce4-session
# Add your own logout logic here
then
$ chmod +x /usr/local/bin/xfce4-session
It's not perfect (depends on PATH order) but may be more palatable.
(Note: I promoted my comment to an answer.)
Change the /usr/bin/xfce4-session executable with a shell script which runs the original xfce4-session and your logout script if xfce4-session finished.
# mv /usr/bin/xfce4-session /usr/bin/xfce4-session.orig
The new /usr/bin/xfce4-session file:
#!/bin/bash
/usr/bin/xfce4-session.orig
echo "my logout script" > /tmp/testfile
Don't forget to set the execute permissions:
# chmod a+x /usr/bin/xfce4-session
(Tested on Debian Squeeze.)
I'd prefer solution that does not touch system directories or files and will run the logout hook within current user session and its privilledges.
below is my solution:
create ~/.local/bin/xfce4-session-logout script with the following contents:
#!/bin/bash
PRELOGOUT=${HOME}/scripts/pre-logout.sh
RESULT=RES_`echo -e "logout\nrestart\nshutdown\nsuspend" | zenity --height=250 --list --title "Logout from $USER" --column "What do You want to do?"`
case $RESULT in
RES_logout)
[ -x $PRELOGOUT] && $PRELOGOUT
/usr/bin/xfce4-session-logout --fast --logout
;;
RES_restart)
[ -x $PRELOGOUT] && $PRELOGOUT
/usr/bin/xfce4-session-logout --fast --reboot
;;
RES_shutdown)
[ -x $PRELOGOUT] && $PRELOGOUT
/usr/bin/xfce4-session-logout --fast --halt
;;
RES_suspend)
/usr/bin/xfce4-session-logout --suspend
;;
*)
exit 1
;;
esac
and make it executable:
chmod u+x ~/.local/bin/xfce4-session-logout
Now, put whatever You need to be executed at logout action to ~/scripts/pre-logout.sh and make it executable
chmod u+x ~/scripts/pre-logout.sh
after relogin, either menu > logout button or Alt+f3: "logout" will bring simple dialog for leaving the current session
Note: pressing Alt+F4 does not work with it, but maybe some black belted xfce4 users will provide some suggestion
I validated the answer above since it does not involve new code writing.
I however found another way to proceed : create a X11 program which would be launched at session startup : it could execute custom scripts when the X session is closed
Note : the drawback is that the used scripts could not connect to X windows so this solution may, depending on the need, execute the script too late.

Resources