Ubuntu – SSH into a specific directory

ssh

I SSH into a multitude of different servers every day and some of them have different filesystem structures for their websites. Each time I change server, I have to work out where I'm going to get to the files I really want (because it's very rarely that I want to be in ~).

I use Fabric files to automate all my actions (pushing to git, automated SSH to the server to pull from git, restarting the web application, changing dependencies, etc), so I was wondering if I couldn't also tell it that I want to SSH into the right directory so I can run fab ssh and be in a normal SSH session, just in the right place and start working immediately.

This is not about Fabric though; please ignore it. Fabric is just running a batch of commands. My argument is with the ssh command. That's what I'll be telling Fabric to run.

So how I can get ssh to cd into a specific directory on login?

Note: this cannot be a server or user-wide thing. I have multiple websites under one user on some servers so sticking something in ~/.bashrc would not work for me.

Best Answer

  • Well I knew I could run something on login, but I knew it would exit out straight after running. What I now remember is that I can run as much as I like on a remote server. You can just chain the commands together!

    ssh user@server -t "cd /websites/website ; /bin/bash"
    

    Now I can just tell fabric to do that and we're away. Simple.


    I did say it wasn't anything to do with the Fabric but here's the new part of my fabric script too, based on the above:

    def ssh():
        ''' SSH into the remote server at the correct directory '''
        local('ssh -t -p%(port)s %(server)s "cd %(remote_dir)s ; /bin/bash"' % {
            'server': server_host,
            'port': server_port,
            'remote_dir': remote_dir,
        })
    

    I symlink the same script around so the variables (server_host, server_port and remote_dir) change from site to site.

    Because Fabric can handle the outbound connection you can also just do this:

    def ssh():
        ''' SSH into the remote server at the correct directory '''
        run('cd %s ; /bin/bash' % remote_dir)
    

    This does work but the output is prepended with a string from Fabric. This made the prompt over 80 chars long and while I've got tons of resolution, that's too much for me :)

  • Related Question