shutdown linux server by mail
by emre - 13.03.2025
important note
this is a template for shutting down linux server by mail. it's not recommended to use as is on production environments.
install isync package to get mails.
apt update; apt install -y isync
♦
customize settings by execute nano .mbsyncrc (or with your favorite editor) at ~.
Expunge Both
SyncState *
IMAPAccount <redacteduser>
Host <fqdn of mail service> #mine is mail.zurrak.com
User <redacteduser>@domain.tld
Pass "<redacted>"
SSLType IMAPS
SSLLevel 2
Port 993
IMAPStore user-remote
Account <redacteduser>
MaildirStore user-local
Subfolders Verbatim
Path ~/mail/<redacteduser>
Inbox ~/mail/<redacteduser>/inbox
Channel user-default
Master :user-remote:
Slave :user-local:
Patterns *
Create Both
SyncState *
Sync All
Group user
Channel user-default
♦
put this bash script to somewhere. you'll need its path for service. mine is at ~.
#!/bin/bash
dir="/root/mail/<redacteduser>/inbox/new"
from="<from>@domain.tld"
to="<to>@domain.tld"
command="<mail body text>" #it can be "shutdown" or more secure, "shutdown hbehehe". it's to be grepped so just put what you want to send mail to shutdown.
if [ -z "$(ls -A "$dir")" ]; then
mbsync -a
sleep 3
fi
attempts=3
while [ $attempts -gt 0 ]; do
inbox=$(find "$dir" -type f -mmin -2)
if [ -n "$inbox" ]; then
break
fi
sleep 10
((attempts--))
done
for mail in $inbox; do
if grep -q "$from" "$mail" && grep -q "$to" "$mail" && grep -q "$command" "$mail"; then
rm -rf "$dir"/*
shutdown -h now
fi
done
♦
creating service by nano /etc/systemd/system/shutdownbymail.service. shutdownbymail.service content below.
[Unit]
Description=shutdownbymail
[Service]
User=root
WorkingDirectory=/var/www/html/
ExecStart=/root/shutdownbymail.sh
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
♦
after than that, execute systemctl daemon-reload, systemctl enable shutdownbymail.service and systemctl restart shutdownbymail.service.
♦
now, your shutdown by mail system is ready.
if you have questions: contact