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 email@example.com # Log into the server screen -r # Attach to the irssi session #(Do stuff) #CTRL+a, CTRL+d to detach irssi exit # Logout of the serverIt's a little different if I want to log in from elsewhere on the internet:
ssh -p PortNumber firstname.lastname@example.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:
- ssh takes in-session commands:
ssh destination "command1; command2"
- ssh has a -t flag, forcing a pseudo-terminal connection (screen needs this to work)
- bash uses basic if/them logic a couple ways.
- 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 email@example.com 'screen -dr pts-0' else: ssh -t -p PortNumber firstname.lastname@example.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 email@example.com 'screen -dr pts-0' || \ ssh -t -p PortNumber firstname.lastname@example.org 'screen -dr pts-0'