Saturday, September 24, 2011

Access your 24-hour IRC client/logbot from anywhere

I use irssi (IRC client) running on a 24/7 server to maintain my IRC presence. When I want to connect to IRC, I ssh into the server, and attach into the running IRC session.

ssh me@myserver.local   # Log into the server
screen -r            # Attach to the irssi session
#(Do stuff)
#CTRL+a, CTRL+d to detach irssi
exit                 # Logout of the server
It's a little different if I want to log in from elsewhere on the internet:
ssh -p PortNumber me@myserver.dyndns.org    # Log into the server
screen -r            # Attach to the irssi session
#(Do stuff)
#CTRL+a, CTRL+d to detach irssi
exit                 # Logout of the server


Here's one way to simplify it:

  1. ssh takes in-session commands:ssh destination "command1; command2"
  2. ssh has a -t flag, forcing a pseudo-terminal connection (screen needs this to work)
  3. bash uses basic if/them logic a couple ways.
  4. determine the network using the 'route' command


So you can set up an ssh command like ssh -t me@myserver 'screen -dr pts-0' to connect to the server and then the screen session. (I already knew that my screen session was at pts-0; it tells you when you detach). When you detach from the screen session (CTRL+a, CTRL+d), the ssh session closes automatically.


One more piece of the puzzle is my network logic - I connect differently if on the LAN or out in the wider world. I use route | grep -q myserver.local to determine if I'm on the home network or not (return is '0' if home network, '1' if internet). Of course, your server name will vary.


The easy, logical result:

LocalNetwork=$(route | grep -q myserver.local)
if $LocalNetwork; then
   ssh -t me@myserver.local 'screen -dr pts-0'
else:
   ssh -t -p PortNumber me@myserver.dyndns.org 'screen -dr pts-0'
fi

We can simplify this even further using bash logical expressions instead of if/then/else statements. It's a single line, but more cryptic:

route | grep -q myserver.local && ssh -t me@myserver.local 'screen -dr pts-0' || \
ssh -t -p PortNumber me@myserver.dyndns.org 'screen -dr pts-0'

No comments: