Try Tuts+ Premium, Get Cash Back!
SSH: What and How

SSH: What and How

Tutorial Details
  • Applications Used: SSH, Shell
  • Difficulty: Intermediate
  • Completion Time: 30 Minutes

Many web developers use SSH (“Secure Shell”) on a daily basis to manage their servers, back up files, work remotely, and a myriad of other tasks. Today, I’ll explain what SSH is, do a brief history review, and, lastly, teach you how to set it up on your remote server or even your local network. Let’s get started!


A Starting Explanation

If you’re reading this, it’s likely that you’re at least somewhat acquainted with Terminal (or on Windows, something like Cygwin). If so, then you will understand this quick functional explanation of SSH.

SSH is essentially using a network connection to get into Terminal on another computer.

If you aren’t familiar with Terminal, there are a lot of explanations and beginner’s guides to Terminal, both here on Nettuts+ and elsewhere. The power of SSH is reliant on its simplicity; by offering you access to the Terminal of another machine, SSH cuts to the chase and gives you full control over a remote machine. If you understand the power of Terminal and its direct connection to the inner workings of your local machine, then you understand the power of SSH!


A Brief History

SSH was developed in its infant state in 1995. The primary developer, Tatu Ylonen, developed it as the first secure way to administrate a remote UNIX system. Previous to SSH, the only tools that existed sent information like passwords in clear text.


So, How Do I Use It?

There are a million guides out there on how to get set up with SSH. We will specifically cover one method today. First things first, you’ll want to make sure you have SSH on your system.

  • Mac – A version of OpenSSH comes preinstalled.
  • Windows – Follow a guide like this one or this one to get Cygwin and the “openssh” package installed.
  • Linux – OpenSSH is highly likely to be installed already, but if it isn’t, you can follow the same guide to get it installed.

To determine if SSH is installed, run `which ssh`. If Terminal returns something along the lines of /usr/bin/ssh, then you’re good to go! Otherwise, follow one of these guides to get it installed.

In this article, I will assume the version you are using is OpenSSH; there are some configuration differences that depend on your version of SSH. We will be explaining how to set up a Mac to connect to a MediaTemple server through a single SSH command. Once you have SSH installed on your machine, you will need to make sure your target host has SSH enabled. SSH runs over port 22 by default; you can use a command line tool like nmap to ping your server to determine if port 22 is accepting incoming connections, like this:

sudo nmap -sS hostname.com

Of course, you probably have access to the administrative interface for the server. Make sure you look through the options and enable SSH. On a Mediatemple server, this configuration is located under the Server Control panel. Mediatemple SSH is accessible by using root@primarydomain.com. You can add users to the account, but for the sake of keeping things simple, we will use root@primarydomain.com.

Once SSH is enabled (and you have set a root password in your server admin), you can run the following line to SSH into your server.

	ssh root@primarydomain.com
	

…where primarydomain.com is your MediaTemple primary domain. You will then be prompted for your password (which is the root password you set in the control panel). If you are not using MediaTemple, you can SSH directly to the IP address of your server as well.

If using shared hosting, it is likely that you will not be logging in as root. Instead, you will log in with a user account name. For example, if you are using a service like Site5, you may log in with a username at a subdomain, like this:

	ssh username@malta.site5.com
	

Ultimately, these configurations will depend on your specific web server company. Refer to your host’s documentation for more information.

Once you are “shelled in”, you can execute commands and traverse the file system within Terminal. Depending upon on your level of access, you may be able to install things on your server using apt-get or wget commands. You can manage your Apache server, edit configuration files with a Terminal-based text editor, view error logs, clear caches, view files directly on a server to make sure they are the correct version, and plenty of other lower-level system administration tasks. Now, what if you wanted to do more, faster with SSH?


How Do I Use It… Better?

There are a ton powerful things that SSH opens you up to. We will skip a few of them (as quite a few are more sysadmin-related, like tunneling). But we will go over a few useful tricks.

Super-quick Log-in

You’re thinking to yourself, “seems like there should be a faster way to do this.” You’re right. And there is. Instead of having to remember your domain, password, and username for every server, you can set up a few configurations that will allow you to speed up the process to something along these lines.

	ssh myserver
	

With the right configuration, you could run this, and without having to enter any passwords, IP addresses, or long domain names, you’re in! Again, we will assume you are logging into a MediaTemple server. First, we will generate ssh keys. This is basically a set of encrypted keys that live in ~/.ssh on your local machine. You have a “public” key and a “private” key. So, first things first, open a new Terminal window and create the .ssh folder in your home directory.

	mkdir ~/.ssh

Next you will generate your keys with the following line. (This comes directly from MediaTemple’s documentation.)

	ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -C "Comment about your key goes here."

This line will generate an ssh key of type rsa, with 2048 bits (for security), at the file location specified, with the comment specified. You will be promprted for a password, but it isn’t mandatory or necessary; not providing a password will enable you to automatically log in. The RSA type is for SSH protocol version 1. Type DSA is for protocol version 2. Check with your web server to find out which version they are using. Once your keys are generated, you will then run this to make sure your SSH configurations are set to the right permissions.

chmod 700 ~/.ssh && chmod 600 ~/.ssh/*

Next, you will upload your public key to your server. There are quite a few ways to do this; this way comes from MediaTemple’s docs as well.

cat ~/.ssh/id_rsa.pub | ssh root@example.com 'cat - >> ~/.ssh/authorized_keys'

This code is echoing your id_rsa.pub through a `|` (pipe) into the next command, which is an SSH into root@example.com, where you will run an echo and concatenation of what you piped in the first command. It sounds a bit complicated, so there are a few alternative ways to handle this. Essentially, you are going to want no line breaks and your public key on its own line in a file, called authorized_keys on your server in the ~/.ssh/ directory. So, if this is the first or only key you want on your server, you could run this command to copy it directly to that location.

scp ~/.ssh/id_rsa.pub root@example.com:.ssh/authorized_keys

This line is essentially saying, “copy this first file through SSH to the server at this location relative to my current home directory.”

Once your authorized_keys contains your public key, you can attempt to login to the server with ssh username@example.com. If you put your public key in the root user directory’s SSH configuration files, you will be able to login directly to root. You will be asked about a rsa fingerprint; go ahead and allow this action. It adds the server you are connecting to to a known_hosts file. This file can be used for a lot of different things, but particularly to secure yourself against what is called a “man-in-the-middle” attack. If you’d like to read a little more about this, check out this explanation.

If you can successfully log into your server, as if you had entered a password, your keys are working properly. The next step is to add a couple of lines for a shortcut to a configuration file on your machine . Open ~/.ssh/config in your favorite text editor (create it if it doesn’t exist) and add the following:

Host shortname
HostName somehost.com
User username

Where “shortname” is a nickname for the server you want to log into. For instance, “Host myserver” would allow me to do ssh myserver. The HostName is your server location, and of course the User is your username. You may have User root at this spot. Once this file is saved, you should be able to run a simple command to log into your server, like this:

ssh shortname

Git Without a Hub

Please Note: this section requires a bit of familiarity with Git.

You can use SSH to set up your own Git repos on your server! This is useful for companies who don’t want to expose their code on GitHub for whatever reason, and it’s great to be able to push directly from a local machine to a Git repo on your own server.

To set this up, make sure Git is installed on both the host and your local machine. You may have to go through your web server company to have Git installed. Next, run git init on your server in the location that you want your Git repo to be. Of course, you can do this a hundred different ways, but if you prefer to not have a bare repository, you can use branches to push to from your local machine. Here is a common workflow.

	ssh user@example.com
	cd /path/to/repo
	git init
	git checkout -b staging
	git checkout master
	# disconnect from shell session using ctrl-d
	cd /local/repo
	git init
	git add .
	git commit -am "some message"
	git remote add origin user@example.com:/path/to/repo
	git checkout -b staging
	git push origin staging
	ssh user@example.com
	cd /path/to/repo
	git merge staging

Essentially what is happening here is you are logging into the server, changing to the desired repo path, creating a repository and adding a “staging” branch which you can push to from your local machine. Then, you are creating your local repo and a corresponding “staging” branch on your local machine, and adding files to track to the repo. Next comes an initial commit. You are then adding the remote repository as an alias of “origin”. Next, you are pushing the local staging branch to the “origin” alias’s staging branch. Finally, you are ssh’ing back into the server and merging the “staging” branch with the default “master” branch.

SFTP > FTP

You can also use SSH-powered FTP (file transfer protocol), which is essentially a more secure (encrypted) version of FTP that runs over port 22 (rather than the default FTP port 21). Most FTP clients support SFTP as well. FileZilla (for Windows) and Fetch (for Mac) are two popular (and free) SFTP/FTP clients.

Easy Access to Your Server Almost Anywhere

As long as you are around a computer that is connected to the internet, has a Terminal, and has SSH installed (any Mac connected to WiFi, for instance), you can get access to your server, via SSH. That’s the best part. You don’t require any configuration (assuming you haven’t set up any restrictions that require a matching pubkey), you can log in with your username and password from practically anywhere. There are even SSH clients for iOS and other mobile devices. This is a very powerful feature of SSH that is only paralleled in portability by browser-based applications.

A Local Code Repo

Hopefully you can see the power of SSH in a daily development cycle.

Let’s imagine that you and a few buddies are working on some code together. Let’s also say you have a local computer that you have full control over that you use as a development LAMP server with a few VM’s installed on it. You can use SSH locally to move files to and from your computer and the development machine. You can even set up a local Git (or svn, or Mercurial) repo, powered by SSH to keep everything in check. Perhaps you could even make the development machine the only machine that is connected to the remote server via SSH, so that the code has to go through a specific staging process before it can be put into production. The backbone of all of these actions is SSH!

Hopefully you can see the power of SSH in a daily development cycle, especially for teams using version control. As I noted previously, there is plenty of documentation and a myriad of other network-level tools based on or reliant upon SSH that will give you more control and power over your development process and your server. Who knows? Maybe, one day, you could double as a sysadmin after all!


Some Other Helpful Links

Here are some other helpful links to get you started with SSH. It’s been around for a while, so there is plenty of documentation floating around.

Thanks for reading!

Tags: terminal
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://timshomepage.net Timothy Warren

    No mention of the easy option for Windows: PuTTY?
    http://www.chiark.greenend.org.uk/~sgtatham/putty/

  • http://daveismyname.com Dave

    I may have missed something but at what point do you provide/store the server password?

    • Peter Hanley

      It depends on the client you use, but protocol-wise the password is sent after the secure communication is established, so in a unix terminal you type ssh username@server.tld, and once the secure connection is established the remote server will prompt you for your password.

      But a lot of GUI clients have you input the password when you enter the other connection details.

  • MG

    Thanks for the great command on how to copy your pub key to the authorized_keys via SSH.

  • http://whiteboard.is Jonathan Cutrell

    Timothy: Good point! Everything we have in these examples is fully unix compatible, so Cygwin is generally a good idea, but PuTTY is definitely a good option for SSH on Windows.

    Dave: You don’t actually store a server password. You provide it after doing ssh name@server.com. At this point, you will be prompted for a password if you haven’t generated a pubkey to put in the server’s authorized_keys file. If you are wanting automatic login, you’ll have to make sure you put your public key in the authorized_keys file in your server’s ssh folder.

    Also, you’ll need to make sure your server supports public key authentication and that it is enabled, if you’re having trouble – something your provider can tell you. This is a very common default configuration, though, so contact your sysadmin if it doesn’t work for you.

    • http://daveismyname.com Dave

      OK just to be clear I need to login to my server before running the commands in the tutorial? very new to SSH but aware it’s something I need to learn.

      • http://whiteboard.is Jonathan Cutrell

        You will need to open terminal and run these commands from your local machine. While you can SSH from your server to another computer, it is likely that you won’t do that for simple development unless your company has a firewall set up to keep the ports to an internal server closed off except to a set of predefined computers (or other similar security measures).

        It all depends on what you’re trying to do. Any specific questions as to when you should run what commands?

  • http://daveismyname.com Dave

    Im using my local machine I was following the instruction for the section “How Do I Use It… Better?” it threw me as it didn’t mention logging onto the server before hand.

    • http://whiteboard.is Jonathan Cutrell

      I can see how you’d get confused there – not all of those commands are run from the server, and not all of them are run from your local machine. For instance, the Git work sequence is a little of both, but all in order, with the disconnect command added in.

      The command `ssh ` at any point is talking about initiating a secure shell session (say that five times fast!) from your local machine to the “shortname” host machine.

  • http://localhost Atachi

    Thou shalt not use CTRL+D, but type exit instead.
    CTRL+D is a really dirty way to kill something and should only be used if your connection is frozen.

    And really, not mentioning PuTTY when talking about ssh on windows is really bad – most programs are based on it (FileZilla, WinSCP) and IMO also a better implementation than OpenSSH’s version – even on linux.

    Also, the terminal example commands should be more readable. Like have the prompt in front to show which machine the command is on (even if it’s just local> and remote>). This would in itself explain a lot what the ssh command actually does. (Wasn’t that the intention of the article?)

    Please note, that this is intended as constructive pointers for future articles and not as random rant.

    • http://whiteboard.is Jonathan Cutrell

      Thanks for the pointers! I’ll take them to heart.

    • http://whiteboard.is Jonathan Cutrell

      If you don’t mind – could you explain (for everyone’s sake) why CTRL+D is a dirty way to disconnect? What does it do exactly that is different from typing exit?

      • http://localhost Atachi

        It kills the process / connection.

        Depending on the implementation it “may” send a kill to the server to terminate the session, but it may also not do that. In a worst case scenario that can lead to zombie sessions on the server.

        Not really a good reason in itself, but its still better to properly exit as there may be some logout script on the server doing cleanups or other stuff when exiting a session.

  • oll

    You can also use
    ssh-copy-id jsmith@example.com
    which does the same as : cat ~/.ssh/id_rsa.pub | ssh jsmith@example.com ‘cat – >> ~/.ssh/authorized_keys’

    • http://whiteboard.is Jonathan Cutrell

      Ah nice – what system is this implemented on? I did a quick check and it’s not available in my Terminal (Mac OS).

      • oll

        Yes, indeed. It’s apparently only provided by Linux distribution of OpenSSH (I know that it’s available for both Debian/Ubuntu and Fedora/RedHat distribs).

        Apparently, it should also work for Mac :
        http://www.devthought.com/2009/09/19/get-ssh-copy-id-in-mac-os-x/

        Feel free to give it a try. It’s a really usefull script, especially for setting the appropriate rights on folders and files (openssh is pretty strict about it and it’s often a boring task to remember them precisely when you does it only once or two per year)

  • http://www.imstillreallybored.com Josh Bedo

    I also use PuTTY but I find myself using GIt Bash more and more just because of how simple and fast it is once you learn the commands.

  • Adam Short

    No mention of tunneling? SSH tunneling is one of its more useful features. Access resources on a remote machine as if they were on your own machine, using a neatly encrypted tunnel, what could be cooler?

  • Angel

    Great tutorial!.

    Is this utility a replacement for wget? if not, Could you help us with a tutorial on how to setup and use wget?

    Thank you very much!!.

    • Fery Ardiant

      Hi Angel. what system that you use. if you’re on Windows you can get wget for Windows here.. on Linux simply sudo aptitude install wget (on Debian base distro) or yum install wget (on Redhat base distro) via terminal. for mac, ummm sorry i’m not mac user..

      looking for how to use wget check here.

      CMIIW

  • http://www.seelooh.com Chris

    Thank you for this article a ton! I had to deal with this at work for the first time and I was at a brick wall, no clue what to do (our main tech guy was out) great introduction and how it all works. I appreciate this article a ton!

  • Daniel

    Very nice tut!

    Re: git remote repo

    To setup a clean (empty) repo and avoid ‘tree’ errors, use the –bare switch:

    git –bare init

    This will allow you to push immediately without any prior commits or branches.

  • Fery Ardiant

    Hi! thanks for the tutorial..

    i never using PUTTY (just didn’t want to try it, hehe)
    just using WinGIt or MSysGit that come with SSH.

  • Dal

    I’m using SecureCRT for that.

  • jbitautas

    Hi Jonathan, this is a great article about SSH. I have a question for you (or anyone else that may know) that I haven’t been able to find a definite answer on yet. I’m considering setting up a git on my hosting server and I was curious if doing so would cause any kind of conflicts with using my git on Github from my computer’s terminal?

  • virtual tour provider

    Thanks for sharing wonderful Post I’m using SecureCRT for that.. It is just awesome.

  • http://www.facebook.com/ch.umair Ch Umair Tarar

    “If you are using a local shell terminal and you ssh to you local computer using your local user name (e.g. aqadeer@10.11.21.157 on my Linux box), does it ask for your password? Please write the ssh command you used below” this was the question posted by my teacher, i dont know what that is