Saturday, 12 December 2009

Getting back in

Here are two useful snippets of bash code which may come in handy when doing stuff over the network.

This first one checks whether the code is already inside a screen session. If not, it tries to attach itself to the desired screen (given by "name"). If that fails, it runs itself again but inside a screen.

if [ -z "$STY" ]; then
# Not in screen, does one already exist?
screen -dr name
if [ "$?" -eq "1" ]; then
# Create new screen
screen -S name "$0"
exit 0

This next snippet is a bit like the 15 second countdown when you change your screen resolution. If things are broken to the point where you can't acknowledge the script, it will revert (or take some other action).

echo "NOTICE: Something will happen in 10 seconds UNLESS ctrl-c is pressed!!!"
echo -n "Time remaining: 10"
for i in {9..0}; do
sleep 1
echo -e -n "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bTime remaining: 0$i"
echo -e "\nReverting now"

You can combine the two snippets in something like a firewall script. If you are doing any kind of editing, then you probably want to be inside screen in case you get disconnected. If your changes go horribly wrong and you lose connection to the host, then your revert_code_goes_here script can undo some of the damages.

A word of caution

Be careful when running sudo or root terminals inside a user's screen session. If someone manages to break in with a normal user, it might be as simple as attaching to a screen session to get root on that box.

No comments:

Post a Comment