Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Im working only in a screen session on my vps which runs all the time. When I connect to this server via ssh, I reattach this with a bash alias

alias screenr='screen -r -d'

What I want:

Connecting to the server and automatically reattaching the session.

What I tried:

Adding screen -r to the end of my .bashrc leads into an info message from screen, that I'm already attached to the session.

Any ideas, or did I just missed a parameter on the man page?

share|improve this question
up vote 3 down vote accepted

Instead of your bashrc, try using your ssh config file (~/.ssh/config). You can change it to run a command upon login. For example:

Host some_alias
Hostname                your_vps.dyndns.org
Port                    22
User                    some_user
PermitLocalCommand      yes
LocalCommand            screen -dRR screen_session_name

Then all you have to do is *ssh some_alias* and you'll automatically reattach to your screen session with the name *screen_session_name* (or create it if it doesn't exists).

Edit: By the way, this goes on your local machine, not your server.

share|improve this answer
    
Really nice way, thanks for this! – sascha Jan 2 '12 at 10:53
1  
-1 The LocalCommand executes on the local system, not on the remote system (hence the command name). – Arcege Jan 2 '12 at 12:55

I use the following in my .bash_profile:

# if not running screen, attached to a terminal and is myusername (not run through sudo)
if [ -z "${STY}" -a -t 0 -a X${USER} = Xmyusername ]; then
    # function to re/attach to screen
    reattach () {
        # if Agent Forwarding is active, set up a mechanism to update the socket
        if [ -n "${SSH_AUTH_SOCK}" ]; then
            ln -snf "${SSH_AUTH_SOCK}" "${HOME}/.ssh/agent-screen"
            SSH_AUTH_SOCK="${HOME}/.ssh/agent-screen" export SSH_AUTH_SOCK
        fi
        # replace the login shell with screen
        exec screen -A -D -RR ${1:+"$@"} ;
    }
    # remove any defunct sessions
    screen -wipe
    echo 'starting screen... (type Cntl-C to abort)'
    sleep 5 && reattach
fi

This creates a unique session that I reattach to at login. It waits 5 seconds in case I want just a shell. Change the myusername in the first if clause.

share|improve this answer
    
I like this - a couple notes: 1. A space should be added to: 'Xmyusername ]' 2. Might want to mention to change 'myusername' to the user's actual username. – jmohr Jan 2 '12 at 17:20
    
Thanks; actually, I copy&pasted it from another answer, so I'll have to fix that one as well. – Arcege Jan 2 '12 at 17:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .