7 ms·
Simplify your life with an SSH config file
- icebraining 14y agoA great option to enable for servers where you're constantly SSHing to (either opening a shell or pushing a repo) is ControlMaster, which lets you multiplex a single connection and cut down on the initial connection time (including authentication).
- VBprogrammer 14y agoSyntax for anyone looking for it: Host * ControlMaster auto ControlPath ~/.ssh/cm_socket/%r@%h:%p
- icebraining 14y agoI'm an apologist of RTFMP, which is why I didn't include it ;)
- SkyMarshal 14y agoIt's generally appreciated anyway, since man pages don't always have examples [1]: $> man controlmaster No manual entry for controlmaster $> man ssh|grep -i controlmaster required before slave connections are accepted. Refer to the description of ControlMaster in ssh_config(5) for details. ControlMaster description of ControlPath and ControlMaster in ssh_config(5) for details. $> man ssh_config|grep -i controlmaster ControlMaster with ControlMaster set to “no” (the default). These sessions will try to reuse the master instance's network connection rather than Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background (waiting for [1]: http://www.reddit.com/r/fossworldproblems/comments/v7hi1/man_pages_without_examples_piss_me_off/ http://www.reddit.com/r/fossworldproblems/comments/v7hi1/man...
- ebroder 14y agoIf you have a new enough ssh client, I'd personally recommend setting ControlPersist yes. This fixes the UI wart where your first ssh connection to a server has to stay open for the duration of all your others (or your others all get forcibly disconnected). It's not perfect. If the name of a server changes but you already have a control socket, it'll use the socket and connect to the old server. And it also takes it a while to pick up networking changes that break your connectivity, though I've hacked around that with a script I keep running in the background (Linux only, at the moment; requires gir1.2-networkmanager-1.0): #!/usr/bin/python import os from gi.repository import GLib, NMClient def active_connections_changed(*args): for sock in os.listdir(os.path.expanduser('~/.ssh/sockets')): os.unlink(os.path.join(os.path.expanduser('~/.ssh/sockets'), sock)) c = NMClient.Client.new() c.connect('notify::active-connections', active_connections_changed) GLib.MainLoop().run() There's some contention with my coworkers about whether ControlPersist is actually desirable given the tradeoffs, but I personally think it's a huge improvement.
- jperras 14y agoOh wow, this is great. I had no idea that existed. Thanks!
- nnq 14y ago...quick and to the point article explaining it, and comments to get you going further with it: http://www.debian-administration.org/articles/290 http://www.debian-administration.org/articles/290 (I know, it sucks when RTFMP gets you into a sort of dead end...)
- cmer 14y agoI now use Mosh exclusively over ssh. It's great on slow connections as well as on fast ones. For example, I can start an ssh connection at home on my laptop, drive to the office and resume like nothing ever happened. One of the best discoveries of the past year for me. http://mosh.mit.edu/ http://mosh.mit.edu/
- jacobr 14y agoThe nice thing is that most ssh config settings are also used by mosh.
- beagle3 14y agoI haven't heard of Mosh before, so I can't comment (I'll try it soon), but I just watned to point out that ssh+screen (or ssh+tmux) gives you exactly the same, and is an apt-get/yum-install/pacman-S away. From reading about mosh, it seems to require a UDP connection, thus non-trivial routing. I forward ssh connections through ssh tunnels (sometime multiple layers), and it works great. Can mosh do that?
- wch 14y agoIt's not quite the same to use ssh + screen/tmux. mosh resumes automatically (no need to log in again), and it also will show your keystrokes as you type them, even if the remote machine hasn't yet received them and then sent back to your local machine the updated text. This "buffered" text is displayed with an underline and when your computer receives communication from the server, it gets updated to the correct text. This makes the terminal feel a lot more responsive, in my experience. mosh can also be installed with apt-get, at least in Ubuntu.
- cmer 14y agoThis. I love the predictive typing feature when I ssh oversees. For this feature alone it's worth using Mosh.
- beagle3 14y agoI'll try it for the predictive text ... but, what do you mean "you don't have to login again"? I use a public key login on ssh (so login is invisible), and you can set up your ssh command line in your config file to do so, e.g. I often use ssh beagle3@remote.host -t 'screen -x || screen' And it works beautifully. (I'm heavy screen user, so even if I switch to mosh, there will be screen underneath...)
- skylan_q 14y agoI was very pleased when I discovered this. I was thrilled when I discovered that Emacs tramp mode makes use of this! :D
- Newky 14y agoGood article, especially the LocalForward config was new to me. One real usage that is invaluable for me, is the fact that the config is used for SVP also. This saves a lot of typing. With a key based login set up, copying files to a server is a matter of scp file dev:~/
- icebraining 14y agoUsually $HOME is the default path, so you don't even need the ~/, this works fine: scp file dev:
- sneak 14y agoThis overlooks ProxyCommand, the single most useful reason for using an ssh config file. e.g.: Host internal-*.example.net ProxyCommand ssh -T external.example.net 'nc %h %p' Basically, specify as ProxyCommand whatever command needs to be run to give you i/o to the remote sshd - in this case, sshing to a bastion host and running netcat. This allows me to do, for example: ssh internal-dev.example.net Which will (in background) ssh to the bastion host external.example.net. I can even do port forwards to internal hosts using -L or LocalForward directives. It's a huuuuge timesaver. ssh even automatically replaces %h and %p in the ProxyCommand with a host and port, though you can of course replace those tokens with static values if it works better. (Also, note above that one can use wildcards in Host declarations.)
- ceejayoz 14y agoThat is freaking awesome.
- jperras 14y agoAh, very cool. I remember stumbling upon ProxyCommand in some SSH docs, but didn't really see an immediate use for it. Thanks!
- mrud 14y agoYou can also use ssh -W [1] instead of relying on nc, i.e: Host madeup Host internal_name ProxyCommand ssh external.example.net -W %h:22 [1] - http://manpages.debian.net/cgi-bin/man.cgi?query=ssh&apropos=0&sektion=0&manpath=Debian+6.0+squeeze&format=html&locale=en http://manpages.debian.net/cgi-bin/man.cgi?query=ssh&apr...
- stock_toaster 14y agoNote there appears to be a bug where the use of ControlPersist breaks the use of '-W'. You end up with 'bad packet'. openssh-6.0 release notes has this: * sshd(8): unbreak stdio forwarding when ControlPersist is in use; bz#1943 I haven't tested to see if that resolves the issue yet though (on osx which of course does not have 6.0). However, the netcat version works fine.
- swalberg 14y agoIf you add the following to your .bash_profile, you'll get command line completion of your hosts: function _ssh_completion() { perl -ne 'print "$1 " if /^[Hh]ost (.+)$/' ~/.ssh/config } complete -W "$(_ssh_completion)" ssh
- jperras 14y agoI use ZSH, which if configured properly will also do this for you. Huge timesaver when I need to connect to a half-dozen hosts.
- paxswill 14y agoThe standard bash_completion[0] package includes SSH host completion. [0] http://bash-completion.alioth.debian.org/ http://bash-completion.alioth.debian.org/
- lallouz 14y agoOh man, I have been thinking about this problem for a while now. Glad to see the start of some simple solutions to make this more bearable.
- deleted 14y ago[deleted]
- ef4 14y ago> Personally, I use quite a few public/private keypairs for the various servers and services that I use, to ensure that in the event of having one of my keys compromised the dammage is as restricted as possible. If you keep all those private keys on the same machine and tend to load them all into ssh-agent frequently, then there's little point in that. People forget that keypairs are not like passwords -- if Github gets compromised, nobody can do anything with the public key you gave them. Unless you treat the keys very differently (like having a special key that you rarely ever decrypt), there's no reason to have more than one per device.
- jperras 14y ago> People forget that keypairs are not like passwords – if Github gets compromised, nobody can do anything with the public key you gave them. Oh, I'm well aware of the difference between a public/private asymmetric encryption scheme and a symmetric one. My concerns are more along the lines of my laptop/desktop being stolen, or my home being robbed and my backup disks/USB keys being taken, or even my computer being seized at the US border. There are ways to mitigate those concerns (e.g. full-disk encryption), but I'm very much a proponent of defence-in-depth whenever possible. I should probably clarify that in the post itself, so that readers aren't misled as to the reasoning behind password-protecting your private keys.
- apawloski 14y agoI don't think I understand you here. Are you not keeping these different keys on the same machine?
- adanto6840 14y agoI've run into a few local networks that have routers, or other network security appliances, that are configured in such a way where my SSH connection would get dropped after XX seconds of inactivity. Placing the following wildcard entry in my SSH config resolved the issue for those times when I had to use one of these networks... # Set Global KeepAlive to avoid timeouts Host * ServerAliveInterval 240
- lostapathy 14y agoCaveat, though, is that this will force connections to break if you have a transient network outage that SSH could otherwise cope with. Which can be annoying if you're somewhere with a flaky connection. Putting it on the specific hosts you need rather than globally keeps it from causing you grief anywhere you don't need it.
- beagle3 14y agoWhile that's true, it tries 3 times (default) before it gives up - so, setting to 240 would require 12 minutes of no connection before disconnecting. In any environment that I've been working in recently, if I lose connection for more than 5 minutes, I've lost it for far longer - I might as well break and reconnect anyway.
- jperras 14y agoAuthor here. Glad to see that this post was useful; I wrote it a while ago when I realized that people weren't password-protecting their Github private keys because it was "too complicated". I've been meaning to start writing again, and my post showing up on the HN front page is a pretty good motivator. Thanks for that, everyone :-).
- bonobo 14y agoNice article. If only I had seen this last week, it would have saved me some time. I was trying to configure multiple github accounts last week, but I don't have enough experience with ssh. ...but now that I did manage to configure it, I wonder if it was really necessary. Github has a nice identity control, I think it was foolish of me to think I needed both a personal and a work account.
- Tobu 14y agoYeah, IdentityFile + IdentitiesOnly is useful for those hosts.
- mememememememe 14y agoBut this is known for years. I've been using this since the second week of using Linux.
- h2s 14y agoGood old HN, where a building a website with Twitter Bootstrap on Heroku's free tier makes you a startup founder, and learning to use one the oldest and most basic features of one of the simplest packages in your operating system makes you a hacker.
- the_mitsuhiko 14y agoI wish the damn thing would support DNS. We have a bunch of servers to SSH into and I have to use the fully qualified domain name unless I want to hardcode all of them (and there are too many).
- switch007 14y agoWhat damn thing? .ssh/config? 'Host foo' and the domain in the list in the 'search' option in /etc/resolv.conf works fine for me.
- evanm 14y agoBeen doing this for some time now—getting my precious seconds back one login at a time.
- notatoad 14y agoi just switched over from using bash aliases (as described in the article) to an SSH config file last week. The best thing for me is that it doesn't just make ssh easier to use, it makes all the ssh family of tools easier. scp, sshfs, rsync etc all suddenly require less typing to use.
- js2 14y agoman ssh_config
- trotsky 14y agono one ever uses kerberos outside of windows shops anymore?
- ojiikun 14y agoA "rather large online retailer based in Seattle" is a Linux shop and started using Kerberos for ssh to excellent results a few years back. Once properly set up, the ability to ssh around between Linux and Windows boxen is just pure bliss. Once you're kerberized, just click an ssh: link in a Nagios report and boom, you're on the host.
- nnq 14y agoConsidering the large percent Linux users frequently using SSH, I'd stick a link to this (and to http://www.debian-administration.org/articles/290 http://www.debian-administration.org/articles/290) in all newbie targeted Linux tutorials... I just hate the world for letting me live without this knowledge for close to a year since diving into Linux.
- ftwinnovations 14y agoGreat tips but this one in my opinion is pure gold http://blogs.perl.org/users/smylers/2011/08/ssh-productivity-tips.html http://blogs.perl.org/users/smylers/2011/08/ssh-productivity...
- grobot 14y agoI find myself wishing ~/.ssh/config had include statements, so I could mix and match blocks which are only useful on certain networks / in certain contexts.
- carlosantelo 14y agoTry my fugly script, http://cmad.github.com/sshfu/ http://cmad.github.com/sshfu/ you can do imports for example, and things like inside public_place or home { host web address 192.168.10.1 gw office_fw } otherwise { host web address 192.168.10.1 user $MY_USER } or whatever like host .... agent yes port 8
- newman314 14y agoI really wish this was an as-shipped feature with OpenSSH. Even if it is the config file being able to have multiple Hostnames to try for a Host. That way I can just specify two hostnames/IP addresses to try and ssh can automagically do the right to to get to an internal machine depending if I am at home or work.
- darkarmani 14y agoOn a Mac I used to use Marco Polo to detect my location and it would change my symlinks to ~/.ssh/config. You can use Marco Polo to detect SSIDs or various other changes.
- easy_rider 14y agoHere's another reason why. For specific hosts, ssh can sometimes feel terribly slow, especially with connecting, and especially on a mac! Host -host-name-here- GSSAPIAuthentication no GSSAPIKeyExchange no Fixes this issue. source: http://hints.macworld.com/article.php?story=20111020115417965 http://hints.macworld.com/article.php?story=2011102011541796...
- liveoneggs 14y agoyou can setup port forwards on-the-fly with ~C ~? shows the few things you can do over the admin channel of ssh. ~ $ ~? Supported escape sequences: ~. - terminate connection (and any multiplexed sessions) ~B - send a BREAK to the remote system ~C - open a command line ~R - Request rekey (SSH protocol 2 only) ~^Z - suspend ssh ~# - list forwarded connections ~& - background ssh (when waiting for connections to terminate) ~? - this message ~~ - send the escape character by typing it twice (Note that escapes are only recognized immediately after newline.)
- jerf 14y agoA few other useful things about SSH aliases, especially w.r.t. not just using shell aliases: They set you up with a layer of indirection that you can change later. Git-svn doesn't like having the URL to the SVN server changed, but if you set up a git alias to "svn" instead, when the SVN server moves for some reason you won't have to do anything except change the svn alias contents. You can also share the resulting tree between multiple people easily because they can plop in their own "svn" alias that uses their own user instead. In general you can safely reference the SSH alias in any number of places (beyond just shell scripts) and know that you can trivially change the alias later without having to change all those things. There are many things that will use SSH, but won't accept any parameters, or will accept only a small subset. Emacs can use SSH to access remote file systems by opening "/ssh:username@ip:port:/file", but it will only take username, ip, and port (AFAIK). With SSH aliases, you have the full power of SSH available to you, so you can use all these other nifty things people are talking about. I've also been using ddd to remotely debug perl lately and that pretty much seems to demand 'ssh host' with passwordless login and nothing else.