Tutorial

Initial Server Setup with Ubuntu 14.04

Initial Server Setup with Ubuntu 14.04
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

Introduction

When you first create a new Ubuntu 14.04 server, there are a few configuration steps that you should take early on as part of the basic setup. This will increase the security and usability of your server and will give you a solid foundation for subsequent actions.

Step One — Root Login

To log into your server, you will need to know your server’s public IP address and the password for the “root” user’s account. If you have not already logged into your server, you may want to follow the first tutorial in this series, How to Connect to Your Droplet with SSH, which covers this process in detail.

If you are not already connected to your server, go ahead and log in as the root user using the following command (substitute the highlighted word with your server’s public IP address):

  1. ssh root@SERVER_IP_ADDRESS

Complete the login process by accepting the warning about host authenticity, if it appears, then providing your root authentication (password or private key). If it is your first time logging into the server, with a password, you will also be prompted to change the root password.

About Root

The root user is the administrative user in a Linux environment that has very broad privileges. Because of the heightened privileges of the root account, you are actually discouraged from using it on a regular basis. This is because part of the power inherent with the root account is the ability to make very destructive changes, even by accident.

The next step is to set up an alternative user account with a reduced scope of influence for day-to-day work. We’ll teach you how to gain increased privileges during the times when you need them.

Step Two — Create a New User

Once you are logged in as root, we’re prepared to add the new user account that we will use to log in from now on.

This example creates a new user called “demo”, but you should replace it with a user name that you like:

  1. adduser demo

You will be asked a few questions, starting with the account password.

Enter a strong password and, optionally, fill in any of the additional information if you would like. This is not required and you can just hit “ENTER” in any field you wish to skip.

Step Three — Root Privileges

Now, we have a new user account with regular account privileges. However, we may sometimes need to do administrative tasks.

To avoid having to log out of our normal user and log back in as the root account, we can set up what is known as “super user” or root privileges for our normal account. This will allow our normal user to run commands with administrative privileges by putting the word sudo before each command.

To add these privileges to our new user, we need to add the new user to the “sudo” group. By default, on Ubuntu 14.04, users who belong to the “sudo” group are allowed to use the sudo command.

As root, run this command to add your new user to the sudo group (substitute the highlighted word with your new user):

  1. gpasswd -a demo sudo

Now your user can run commands with super user privileges! For more information about how this works, check out this sudoers tutorial.

The next step in securing your server is to set up public key authentication for your new user. Setting this up will increase the security of your server by requiring a private SSH key to log in.

Generate a Key Pair

If you do not already have an SSH key pair, which consists of a public and private key, you need to generate one. If you already have a key that you want to use, skip to the Copy the Public Key step.

To generate a new key pair, enter the following command at the terminal of your local machine (ie. your computer):

  1. ssh-keygen

Assuming your local user is called “localuser”, you will see output that looks like the following:

ssh-keygen output
Generating public/private rsa key pair. Enter file in which to save the key (/Users/localuser/.ssh/id_rsa):

Hit return to accept this file name and path (or enter a new name).

Next, you will be prompted for a passphrase to secure the key with. You may either enter a passphrase or leave the passphrase blank.

Note: If you leave the passphrase blank, you will be able to use the private key for authentication without entering a passphrase. If you enter a passphrase, you will need both the private key and the passphrase to log in. Securing your keys with passphrases is more secure, but both methods have their uses and are more secure than basic password authentication.

This generates a private key, id_rsa, and a public key, id_rsa.pub, in the .ssh directory of the localuser’s home directory. Remember that the private key should not be shared with anyone who should not have access to your servers!

Copy the Public Key

After generating an SSH key pair, you will want to copy your public key to your new server. We will cover two easy ways to do this.

Note: The ssh-copy-id method will not work on DigitalOcean if an SSH key was selected during Droplet creation. This is because DigitalOcean disables password authentication if an SSH key is present, and the ssh-copy-id relies on password authentication to copy the key.

If you are using DigitalOcean and selected an SSH key during Droplet creation, use option 2 instead.

Option 1: Use ssh-copy-id

If your local machine has the ssh-copy-id script installed, you can use it to install your public key to any user that you have login credentials for.

Run the ssh-copy-id script by specifying the user and IP address of the server that you want to install the key on, like this:

  1. ssh-copy-id demo@SERVER_IP_ADDRESS

After providing your password at the prompt, your public key will be added to the remote user’s .ssh/authorized_keys file. The corresponding private key can now be used to log into the server.

Option 2: Manually Install the Key

Assuming you generated an SSH key pair using the previous step, use the following command at the terminal of your local machine to print your public key (id_rsa.pub):

  1. cat ~/.ssh/id_rsa.pub

This should print your public SSH key, which should look something like the following:

id_rsa.pub contents
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBGTO0tsVejssuaYR5R3Y/i73SppJAhme1dH7W2c47d4gOqB4izP0+fRLfvbz/tnXFz4iOP/H6eCV05hqUhF+KYRxt9Y8tVMrpDZR2l75o6+xSbUOMu6xN+uVF0T9XzKcxmzTmnV7Na5up3QM3DoSRYX/EP3utr2+zAqpJIfKPLdA74w7g56oYWI9blpnpzxkEd3edVJOivUkpZ4JoenWManvIaSdMTJXMy3MtlQhva+j9CgguyVbUkdzK9KKEuah+pFZvaugtebsU+bllPTB0nlXGIJk98Ie9ZtxuY3nCKneB+KjKiXrAvXUPCI9mWkYS/1rggpFmu3HbXBnWSUdf localuser@machine.local

Select the public key, and copy it to your clipboard.

Add Public Key to New Remote User

To enable the use of SSH key to authenticate as the new remote user, you must add the public key to a special file in the user’s home directory.

On the server, as the root user, enter the following command to switch to the new user (substitute your own user name):

  1. su - demo

Now you will be in your new user’s home directory.

Create a new directory called .ssh and restrict its permissions with the following commands:

  1. mkdir .ssh
  2. chmod 700 .ssh

Now open a file in .ssh called authorized_keys with a text editor. We will use nano to edit the file:

  1. nano .ssh/authorized_keys

Now insert your public key (which should be in your clipboard) by pasting it into the editor.

Hit CTRL-X to exit the file, then Y to save the changes that you made, then ENTER to confirm the file name.

Now restrict the permissions of the authorized_keys file with this command:

  1. chmod 600 .ssh/authorized_keys

Type this command once to return to the root user:

  1. exit

Now you may SSH login as your new user, using the private key as authentication.

To read more about how key authentication works, read this tutorial: How To Configure SSH Key-Based Authentication on a Linux Server.

Step Five — Configure SSH Daemon

Now that we have our new account, we can secure our server a little bit by modifying its SSH daemon configuration (the program that allows us to log in remotely) to disallow remote SSH access to the root account.

Begin by opening the configuration file with your text editor as root:

  1. nano /etc/ssh/sshd_config

Next, we need to find the line that looks like this:

/etc/ssh/sshd_config (before)
PermitRootLogin yes

Here, we have the option to disable root login through SSH. This is generally a more secure setting since we can now access our server through our normal user account and escalate privileges when necessary.

Modify this line to “no” like this to disable root login:

/etc/ssh/sshd_config (after)
PermitRootLogin no

Disabling remote root login is highly recommended on every server!

When you are finished making your changes, save and close the file using the method we went over earlier (CTRL-X, then Y, then ENTER).

Step Six – Reload SSH

Now that we have made our change, we need to restart the SSH service so that it will use our new configuration.

Type this to restart SSH:

  1. service ssh restart

Now, before we log out of the server, we should test our new configuration. We do not want to disconnect until we can confirm that new connections can be established successfully.

Open a new terminal window on your local machine. In the new window, we need to begin a new connection to our server. This time, instead of using the root account, we want to use the new account that we created.

For the server that we showed you how to configure above, you would connect using this command. Substitute your own user name and server IP address where appropriate:

  1. ssh demo@SERVER_IP_ADDRESS

Note: If you are using PuTTY to connect to your servers, be sure to update the session’s port number to match your server’s current configuration.

You will be prompted for the new user’s password that you configured. After that, you will be logged in as your new user.

Remember, if you need to run a command with root privileges, type “sudo” before it like this:

  1. sudo command_to_run

If all is well, you can exit your sessions by typing:

  1. exit

Where To Go From Here?

At this point, you have a solid foundation for your server. You can install any of the software you need on your server now.

If you are not sure what you want to do with your server, check out the next tutorial in this series for Additional Recommended Steps for New Ubuntu 14.04 Servers. It covers things like basic firewall settings, NTP, and swap files. It also provides links to tutorials that show you how to set up common web applications. You may also want to check out this guide to learn how to enable fail2ban to reduce the effectiveness of brute force attacks.

If you just want to explore, take a look at the rest of our community to find more tutorials. Some popular ideas are configuring a LAMP stack or a LEMP stack, which will allow you to host websites.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: New Ubuntu 14.04 Server Checklist

When creating a new Ubuntu 14.04 server, there are some basic steps that you should take to ensure that your server is secure and configured properly. This tutorial series covers connecting to your server and general security best practices, and provides links to articles that will help you start running your own web server or application.

Tutorial Series: Introduction to Nginx and LEMP on Ubuntu 14.04

This tutorial series helps sysadmins set up a new web server using the LEMP stack, focusing on Nginx setup with virtual blocks. This will let you serve multiple websites from one Droplet.

You’ll start by setting up your Ubuntu 14.04 server and end with multiple virtual blocks set up for your websites. An Nginx configuration guide is included at the end for reference.

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
136 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

When I try to restart the SSH server after some modifications I get this error:

WARNING: Usage of “server” is deprecated, it has been renamed to “rspserver”! Starting service Echo… Echo Server - Version 1.0

General Parameters: Pool Handle = EchoPool Reregistration Interval = 30.000s Local Addresses = { all } Runtime Limit = off Policy Settings Policy Type = RoundRobin Load Degradation = 0.000% Load DPF = 0.000% Weight = 0 Weight DPF = 0.000% 20-Apr-2014 01:51:53.0852: P3130.7f57bfb19780@stuff rserpoolsocket.c:354 doRegistration() 20-Apr-2014 01:51:53.0857: Error: (Re-)Registration failed: no registrar available Registration: Identifier = $62292d97

Plus, my shell prompt become’s locked and I have to reconnect.

This is with a fresh copy of Ubuntu 14.04 installed minutes ago.

Fred

It seems that denyhosts is marked unmaintained for 14.04.

This comment has been deleted

    This comment has been deleted

      I think you meant to say under Step Four:

      “replacing “demo” with the user you created:”

      Andrew SB
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 21, 2014

      @Dustin Fixed. Thanks for catching that!

      Andrew SB
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 21, 2014

      @Rick Roberts: Right, denyhosts has been dead upstream for awhile, and Ubuntu and Debian have decided to stop providing it. Check out:

      http://askubuntu.com/questions/433924/package-denyhosts-in-ubuntu-trusty-tahr-is-deleted-temporary-or-forever

      You should use fail2ban. I’ll remove the link to denyhosts above. Thanks!

      If anyone following step 5 gets stuck with a “Connection refused” error (like I did), there may be a typo in your config file. While still logged in as root in your other terminal window, you can run the following to test the ssh config file for issues:

      sshd -T

      If there is an issue with a config file, it will tell you which one and on what line.

      If you logged out for some reason, you can use DO’s console access to log in and fix any issues.

      Cheers

      Thanks for posting this!! (sshd -T) I had a typo myself Allowuser should of been Allowusers and I couldn’t see it. This was driving me mad as everything looked correct the ssh service would start but I couldn’t get anything from netstat or ps. I kept looking at my configs just couldn’t see the typo lol! I read your post and went oh, ran the command and bam there it was! thwarted by a single character haha!

      Thanks again great very happy :)

      Thank you! Luckily I came across your post as soon as I encountered the issue.

      I have followed this tutorial and it is all working, but now I have followed the sftp tutorial too and it keeps checking port 22. With this tutorial I changed that port “to something in between 1025 and 65536”, so my question is: how do I know get SFTP to work?

      Justin Ellingwood
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 2, 2014

      Piet:

      If you’ve changed the port that SSH operates on, you can tell the sftp command or your file transfer client the new port you selected.

      If you are running from the command line, you can specify a non-default port like this. If the port you selected is 4444, the command would look like:

      sftp -P 4444 username@server.com

      If you are using an (S)FTP client to connect to the server, you can input the new port in the options. For instance, in Filezilla, there is a field on the right-hand side labeled “Port” as you can see here:

      https://i.imgur.com/4FBl4vX.png

      Let us know if that works for you or not.

      I may be missing something, but if the point is to make it more secure by removing roots access, and giving another user the permissions… haven’t we just chased our own tail?

      We’re exactly where we started, except that it’s now also a username they need to know.

      Andrew SB
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 5, 2014

      @drphilbobaggins: Having to guess the username is surprisingly helpful when it comes to server security. Run a server for long enough, and you’ll see many brute force attempts to SSH into the root account. So if you don’t want to disable the root user, at least create a new user and set PermitRootLogin to no in your SSH configuration.

      I am using putty to log into my server, I followed the tutorial, added user changed port and log in with putty under new settings I now receive the message: “server refused our key”

      I am then prompted for pass, for the new user I enter it and gain access. I am not sure what I have missed in the tutorial that is stopping the SSH key from authenticating.

      This authenticated when it was on default 22 and login as root.

      Went through this guide perfectly without any problem. Thank you for the write up Justin.

      It works, searched for putty tutorials, I had to add my public key for my new user /.ssh/authorized_keys and chmod 700 and 600

      Please add in the tutorial username ALL=(ALL) NOPASSWD: ALL for those that dont want to type password for sudo each time. It is not practical to type password each time thanks

      Kamal Nasser
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 13, 2014

      @adsf: I wouldn’t recommend doing that. It’s insecure to leave sudo access unprotected, it’s actually more secure to type out your password every one in a while.

      Kamal Nasser
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 28, 2016

      This comment has been deleted

        @adsf: If typing the password is an annoyance for you, type “sudo su” to temporarily log in as root. This is a much better option than leaving sudo access unprotected.

        When I use FileZilla and try delete index.php from /var/www/html/ I get - permission denied. How send sudo to ftp-client?

        Kamal Nasser
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 27, 2014

        @timothybernerslee: You can’t use sudo or connect as root using FTP. Use SFTP instead – it’s much more secure (while the name is very similar to “FTP”, it’s not related to the FTP protocol at all): <a href=“https://www.digitalocean.com/community/articles/how-to-use-filezilla-to-transfer-and-manage-files-securely-on-your-vps”>https://www.digitalocean.com/community/articles/how-to-use-filezilla-to-transfer-and-manage-files-securely-on-your-vps</a>.

        Make sure your user has write permissions to index.php so you can delete it: <pre>sudo chown youruser /var/www/html/index.php</pre>

        After going through these steps I’m finding that ssh access is requiring a password to login (using the new user btw and not root as that is of course disabled) , in this case ssh keys were setup during droplet creation, is there another step to take to rectify this so no password is required for ssh with this new user?

        Note: initially root@droplet-ip ssh is working out of the box with no password required on this same laptop/droplet combo.

        Thanks!

        I had the same problem and it has been solved.

        Apparently, the “authorized_keys” file’s owner need to be the account username, NOT root. Login as root to change the file’s owner “chown user:user authorized_keys” will solve the problem.

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 12, 2014

        You need to make sure that your public key is in the authorized_keys file for your user. Run: <pre> cat ~/.ssh/id_rsa.pub | ssh user@your.ip.address “cat >> ~/.ssh/authorized_keys” </pre>

        I got the Public Key in section 4. How can I obtain my private key? That not mentioned here and its a most confusing things newbies like me.

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 11, 2014

        @bijuoosmail Running the ssh-keygen command will produce two files. Your private key, id_rsa, which should stay on your local computor, and a public key that is copied to the server id_rsa.pub

        @astarr yes its definitely in there, I’ve tried all kinds of combinations, like taking all other keys out of authorized_keys and leaving only the public key from the new pair I create, but still only the ssh login will work that is setup via DO droplet creation, no other key pair works, still requires password. Also permissions of the authorized_keys file are as they should be.

        Anything else I could be missing?

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 13, 2014

        In your <code>/etc/ssh/sshd_config</code> file did you add an <code>AllowUsers</code> line? If so make sure your user is listed.

        Thanks @astarr I eventually figured a way to get it working, I had to do the following: <pre> eval ssh-agent -s ssh-add ~/.ssh/bitbucketkey </pre> and add this line… <pre> IdentityFile ~/.ssh/bitbucketkey </pre> to ~/.ssh/config

        Not sure if all of it is necessary, but following various error messages these steps resolved them and has got things working!

        Hello! I’m really REALLY new Ubuntu user. I’m trying to do this procedure to make wordpress work on my pc (I got Ubuntu 14.04 LTS), yet when I do the first step (ssh root@server_ip_address) i got this message: ssh: connect to host 192.168.1.5 port 22: Connection refused Don’t have any clue what that’s it means… so… please… some help… Thank you very much!!! :-)

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 23, 2014

        @manuel.fernando.camperos: Are you trying to install Wordpress locally to your PC? If so, then you don’t need to use SSH. SSH is a way to securely connect to a remote computer. Most articles on installing Wordpress will assume that you are installing it to a server remotely.

        @astarr Thank you for your answer!! Yes that’s exactly what I’m trying to do. On the “How To Install Wordpress on Ubuntu 14.04” tutorial on step four they used “the same account that we set up during the initial server setup guide, which we called demo.” So I thought It was something important that I had to do… Isn’t? Once again thank you for your comments. :-)

        Changing the port, looking at the comments, seems to cause a lot of trouble to users and provides absolutely no additional security.

        May I suggest removing that section or at least strongly indicate that it’s for the overly paranoid?


        Authentication:

        LoginGraceTime 120 PermitRootLogin without-password StrictModes yes


        Mine looks like the above, it doesn’t just say:

        PermitRootLogin yes

        So how should it be changed?

        @gp+digitalocean

        Of course it provides additional security, do I want to target servers that I first have to sniff out the ssh port on? Or would it be easier to get the idiots who keep it at the default?

        Yes it causes problems, if you want something that “just works” get an apple product, it’s caused me hours and hours of frustration too, but each time I learn something new. Imagine how hard things would be if you were using windows for the first few times? But most of us go into the device manager or command prompt like pros and troubleshoot and fix things easily.

        What ports, IPs and protocols we listen for

        Port 2027

        Use these options to restrict which interfaces/protocols sshd will bind to

        I’m using the above port and it won’t let me connect, I can connect fine under port 22. There is a step missing here?? I’ve had this server up for 10min so I haven’t done anything with IPtables.

        How do we tell it to not use port 22 anymore and use our chosen port instead (4444 in the article)?

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 22, 2014

        @SaM5246:

        PermitRootLogin without-password
        

        Means that you can only login to the root account using ssh key pairs. That’s a pretty secure setting, but to disable root login completely set:

        PermitRootLogin no
        

        You need to both update the port in your server configuration and pass it to the ssh command: ssh -p 4444 demo@server_ip_address Also, remember to restart the ssh server after making configuration changes: service ssh restart

        I had to do the following to prevent needing to enter a password when I logged in as the new user

        From my local machine;

        cat ~/.ssh/id_rsa.pub | ssh NEW_USERNAME@IP-ADDRESS-HERE "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"
        

        Replace NEW_USERNAME with the user you created at the top of this tutorial and IP-ADDRESS-HERE with your droplet’s IP address. Naturally, you’ll need to have created the public key on your local machine beforehand (you can do that by following this tutorial : https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys–2

        On my VPS with another company running Ubuntu 14.04 it took me to VIM when I used the visudo command. If that happens to you just remember the commands below. For the most part I use “nano” to edit files which is what is assumed in this tutorial.

        Hit the Escape key; that goes into command mode. Then you can type

        :q to quit
        :q! to quit without saving
        :wq to write and quit
        :x to write and quit
        :qa to quit all
        

        Now I know why, nano was not installed ;) If you wish to follow the tutorial above exactly and don’t have “nano” just do the following

        sudo apt-get update

        sudo apt-get install nano

        After i’ve changed user, i can’t open var/log/apache2 (Permission Denied) .“root” is owner. I’ve changed permissions to 755 but i think this solution is insecure. Can you suggest more reliable solution? Thank you.

        I don’t have permission to write/save in existing files with the new user. Aren’t we giving all the permissions to that user with ALL=(ALL:ALL) ALL? I’m confussed.

        Nice tutorial. Everything worked as stated for me. Thanks.

        With this setup I am no longer able to upload or edit files over sftp with Filezilla even though I can connect with my new user name and port and view files. Additionally, there are now some directories that I am not able to view the files for. This must be something to do with permissions yet I specified them as directed using:

        demo ALL=(ALL:ALL) ALL

        What else could it be?

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 2, 2014

        anagram: Your new user has not been given write access to the system files, but it has been given sudo access. This means that while the account itself does not have access, the user can precede commands with sudo to execute them with elevated privileges.

        As for connecting with Filezilla or a similar client, you are connecting using SFTP, which utilizes the SSH protocol to allow file transfer. However, sudo is not available when connecting through sftp. If you must modify system files or upload content to restricted locations, you will have to authenticate as the root user or upload them to a directory you have access to and then later move them over to the appropriate location by logging in through SSH.

        jellingwood: Then the best option would be to not restrict the root user until after all settings have been configured on the server and the site has been setup and files have been moved over from a previous host.

        Is there any way to give your new profile these elevated privileges so SFTP on the new profile works the same as the root profile?

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 2, 2014

        The idea behind making and utilizing a new account is that operating as the root user is dangerous. If you give your new account the same access as root, you will then have two accounts with unrestricted access, which means that you have significantly hindered your security.

        If you need to upload files to a web directory, one option is to give ownership of the directory to your new user account using the chown command. The general syntax is:

        chown <username>:<username> <file_or_directory>
        

        If you wish to give ownership over all of the files and subdirectories within a directory, you’ll have to add the -R flag to recursively assign the new ownership:

        chown -R <username>:<username> <file_or_directory>
        

        Use these commands with care, and probably only at your web root. If you need to modify configuration files, you should log in using SSH.

        jellingwood: Thanks. Giving access to the web root is really what I was thinking of.

        Hi, everytime I log into console I make sure to get the latest updates:

        sudo apt-get update
        

        Since I’m a newbie, I don’t know if the updates are automatically applied to the existing server or do I need to do something to install those updates? I’m currently on nginx(LEMP) with Zendopcache. Thanks in advance!

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 4, 2014

        Okidoki:

        The command that you listed updates your local package cache. Basically, it makes sure that your system has an up-to-date list of the most current packages. It does not actually download or install any new versions.

        To update your server, you can use sudo apt-get upgrade. This will upgrade all of the packages on your system that do not depend on new packages. If you would like to upgrade all of the packages including those that might need some additional packages, you can type sudo apt-get dist-upgrade.

        Regardless of which version of the above you choose, you should always run sudo apt-get update beforehand so that your system has the latest information about the available packages.

        Hope that helps.

        Jellingwood: Thank you so much! I’ll use sudo apt-get dist-upgrade from now on after sudo apt-get update

        Cool. Great tutorial mate!

        Thank you so much for this. I love DO!

        Step 5 AllowUsers demo where in the file do you put that is it directly below PermitRootLogin ???

        Cheers

        Mal

        Kamal Nasser
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 19, 2014

        You can add it wherever you want, but I personally would prefer adding it to the very bottom of the file.

        Thanks for this guide—it provides some useful and essential tips. During the process of setting up my first Droplet, I’ve discovered a couple of points that I believe are worth mentioning.

        Default timezone

        The default timezone is set to America/New_York, which may not suit everyone (if they’re not in New York, users’ local timezones or UTC may work better). I’d suggest adding a step that includes this command to update the timezone:

        dpkg-reconfigure tzdata
        

        Sudo permissions for the new user

        There is no need to use visudo to explicitly specify sudo permissions for the new non-root user—by default, Ubuntu servers are configured to grant these to any user in the sudo system group. So the same effect can be achieved by simply adding the ‘demo’ user to that group:

        usermod -a -G sudo demo
        

        Cheers, John

        Im just getting

        Read from socket failed: Operation timed out
        

        When i try to reconnect to my server through the new port. Made sure everything is the same as the rest of the steps so no idea whats gone wrong and google has failed me.

        Anyone got any ideas?

        Kamal Nasser
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 30, 2014

        Have you restarted ssh after setting the new port?

        sudo service ssh restart
        

        Perhaps this has been said before, but editing the sudoers file isn’t really the best idea. There is already a group set up for this purpose! Do not run visudo; run this instead:

        usermod -aG sudo <username>

        This will add sudo privileges to the user without editing a volatile file.

        Thanks a lot for the guide.

        A definite must for Ubuntu servers. :)

        Regards

        Nice tutorial!

        One question though: What’s the practical difference between setting PermitRootLogin no and sudo passwd -l which essentially locks the root account?

        I mean apart from switching to root with “su” or “sudo -s”.

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 10, 2014

        The difference between the two is that locking the account with sudo passwd -l will prevent any password-based logins to the account, but will not do anything to prevent logging in with an SSH key.

        On the other hand, the PermitRootLogin no in the sshd_config file will stop both password and key-base logins, but only through SSH. For instance, on DigitalOcean, you could still log into the root account if going through the web console, because that does not rely on SSH.

        If you truly want to lock the account from both directions, you can employ both of these techniques.

        I forgot about the SSH key login, thanks for clarification!

        I am new to the cloud world. I wanted to setup a LEMP server in Amazon EC2. Do you think these steps are required for that? I see that Amazon already restricts root usage and expects you to use the user named ‘ubuntu’. Hence this question.

        Kamal Nasser
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 16, 2014

        You can just skip steps 3 & 4 and follow the rest. :)

        I followed all the steps above. Disabled root login and Allowing only a non root user to login. But when I fire Putty to test and try logging using ‘root’, I am still allowed. Why?

        I am using SSH keys to login.

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 28, 2014

        @nspeaks: If you disabled the root account and are still able to login as root, it may indicate that your settings were not applied.

        Did you restart the sshd service by typing this?

        sudo service ssh restart
        

        Help please, I followed this tutorial and this one: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-14-04. The result: sudo does not work anymore and ssh denies me access. My attempt was to just setup wordpress on digital ocean and ubuntu.

        I am a ubuntu and wordpress beginner and I thought i was fine because the tutorial says beginner under “difficulty”. And now nothing works and I’m worried i broke something bigger by following this tutorial.

        • My setup used to work, and I was able to log into ssh with root@myservername, enter my password and i was in
        • Then I followed the commands here and set up the new user ‘demo’ (i even kept that name). The first fail was that logging in with this new user demo@myservername on the new port 4444 failed. it told me access denied. Even root@myservername denies me access now, from both port 22 (because i had changed it to 4444) and from port 4444.
        • I also ran this command from the other tutorial in the link above i mentioned, under Step Four: sudo chown -R demo:www-data * And now first of all i cannot login, and second is that comes up: sudo: error in /etc/sudo.conf, line 0 while loading plugin `sudoers_policy' sudo: fatal error, unable to load plugins

        and it also said something with “uid has to be 0”

        I cannot reproduce the errors from yesterday because i cannot even login today, after i signed out the first time.

        Please help!!! I’m super desperate.

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 28, 2014

        @miriamneubauer: I’m sorry to be the bearer of bad news, but unfortunately, it looks like you made a mistake that is pretty much unrepairable. You will almost certainly have to start over.

        In the WordPress article, instead of changing the directory ownership of the /var/www/html directory, it looks like you may have changed the permissions of a huge portion of, or perhaps your entire server.

        This command:

        sudo chown -R demo:www-data *
        

        Operates on the directory level, so it must be preceded by a directory change to the location that you would like to modify. This is done directly above that command with this line:

        cd /var/www/html
        

        It looks like either you did not type this directory change command, or that there was an error that prevented you from changing to the specified directory. Because of this, subsequently, when you used the chown command, it targeted a much larger scope than the command was intended to.

        The best option at this point is to start over completely with a fresh server. Again, sorry that you ran into these problems, and I hope you have better luck on your next attempt.

        @jellingwood thanks for the fast reply! when you say “start with a fresh server”, do you mean i have to restart the wordpress&ubuntu&digitalocean installation and get a new dropplet on DO? Or does it mean something along the lines of completely reconfiguring my computer?

        I cannot retrace at this point if I was or was not in the right directory. For the future, I think this could be made more clearly in the tutorial :D as the tutorial says it’s for beginners. There should be some clear warning or stop-sign to double-tripe check that you are in the correct directory BEFORE entering such a potentially devastating command like

        Looking forward to your reply, Miriam

        I’m able to set create a new user but am having no luck changing port numbers. I’ve followed all steps but always end up having to access via DO’s console and reset the port number back to 22.

        Also, for some reason, now even root access is denied when using putty. It prompts me with “Access Denied”, even though I’m able to login as root user in DO’s console.

        Hi there,

        Thanks for the tutorial! Just a quick heads-up here: it seems that a lot of the code snippets are improperly escaped. Lots of <pre> tags and such showing through. :)

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 11, 2014

        Should be all fixed now. Thanks!

        Looks good. Thanks! :)

        The formatting is broken, code snippets have html tags in them

        Andrew SB
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 11, 2014

        There was a small problem with our Markdown renderer. Should be good now. Thanks!

        Hi ,

        I have tried to automate some of the initial server setup via a script. Hopefully it will be helpful. https://github.com/jsinix/scripts/commit/51c7bf99fd25d00e0451e2780650d7ffb82fd899

        Take care

        after I set-upped my ssh port to 1994, and then unfortunately I suddenly got disconnected from the internet before I check the login, and then when I tried to login, it kept giving me “Operation timed out” how can I solve this now ?

        Thanks,

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 2, 2014

        @abdullah.alfaqeir: If you are using DigitalOcean, you can login using your password from the DigitalOcean console in the Control Panel. If your server is hosted elsewhere, you will have to find another way to log in.

        I changed my default ssh port, and in testing it could not ssh to the the new port. Checked my log in /var/log/syslog showed a bunch of lines with [UFW BLOCK] , due to ufw not being setup with the new ssh port. see www.digitalocean.com/community/tutorials/additional-recommended-steps-for-new-ubuntu-14-04-servers

        sudo ufw allow 4444/tcp
        

        Going through this, I noted that the use of exit to return to root is deprecated in favor of logout.

        When I opened ssh config file there was no line as PermitRootLogin yes

        There is line as 'UserPrevilageSeperate . Is it the same thing?

        Justin Ellingwood
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 23, 2014

        @samp: No, the UsePrivilegeSeparation setting is different.

        If you don’t a PermitRootLogin line, you can feel free to add it to the file. Be careful with the spelling and case.

        This comment has been deleted

          I’ve been through the tutorial several times over, still no luck logging in without supplying my regular password. As suggested in the comments I added AllowUsers demo to the /etc/ssh/sshd_config file on the server, substituting my own login name for demo.

          I also tried adding AuthorizedKeysFile %h/.ssh/authorized_keys to the config as well but this actually bars me from logging in as demo altogether giving me a Permission denied (publickey,password).

          Not sure where else to go.

          I finally got public key authentication working, but I don’t understand why my fix works. I ended up leaving /etc/ssh/sshd_config at its defaults, but instead of trying to give my key pair a custom name I let ssh-keygen use the default names id_rsa and id_rsa.pub. Since I want public key authentication for root as well I’ll have to do some more digging to get additional custom key names working.

          EDIT: I didn’t realize the file name id_rsa was so critical. I found the -i option for ssh which should let me select a different key pair but no luck. I still have to enter a password to log in as root.

          I realize I could just disable root login, but it bothers me that I can’t get this working.

          Great success! Quite a combo of user error and knowledge-gap on my end here. Looks like I didn’t save the public key in /root/.ssh/authorized_keys correctly. Fixed it and I was able to use my key pair to log into root. (BTW I did disable root login after fixing this)

          The final head scratcher was that I could still log in using my standard credentials even with public key authentication correctly working. I didn’t realize that that must be disabled explicitly in /etc/ssh/sshd_config by changing the flag on the line PasswordAuthentication from yes to no.

          Justin Ellingwood
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 12, 2015

          @pe8ter: Awesome! I’m glad that you got it figured out and sorry I wasn’t able to help over the weekend. Thanks for posting back with your solutions. I’m sure some other people will be thankful for that!

          After I have created my new user mynewuser and try to ssh in with my new user, I run the following command: ssh -p 4444 mynewuser@my_server_ip_address

          It then attempts to log in for a few minutes, but eventually times out… ssh_exchange_identification: read: Operation timed out

          Thoughts?

          Kamal Nasser
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 18, 2015

          Do you have a firewall set up? What’s the output of the following command?

          sudo iptables-save
          

          Upon setting root privileges for my user, I tried to add my public key to the new remote user. In nano, I got the following error:

          Error writing .ssh/authorized_keys: Permission denied 
          

          Anybody know how I can fix?

          I did exactly written on Step Four and I still can access to my user from the terminal with password from other computers.I don’t have the authentication key(id_rsa)saved in my other computer. Is this how it works?

          Justin Ellingwood
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 19, 2015

          @gio1044686: You’re exactly right. After you test that the SSH key does work, you can disable password authentication for your account by following the steps here.

          This was originally not included in this guide because we were concerned about users locking themselves out of their servers, but we are considering changing this.

          Thank you for the link.Working great now!

          Thanks for the helpful tutorial… now, to get my Django admin working!

          Nice tutorial, but I’d suggest replacing the Add Public Key to New Remote User section with: ssh-copy-id -i ~/.ssh/your_key -o PubkeyAuthentication=no your_user@your_host Note that .pub is automatically appended to key file name (see: man ssh-copy-id) This creates the ~/.ssh with 700 access rights and copies a single key, voila!

          This comment has been deleted

            Thanks for this tutorial, I have done this a few times now but still like to have an “instruction manual” at hand and this fits the ticket nicely.

            Out of curiosity, by enabling SSH access for demo , do you also prevent the possibility of logging in with a password?

            I have a very secure password (which I use for sudo commands etc) but now that I connect with SSH, I’d like to know that there is no way of brute-forcing the password.

            You can never be too secure =0p

            Justin Ellingwood
            DigitalOcean Employee
            DigitalOcean Employee badge
            March 9, 2015

            @qbdsolutionsltd: When you enable SSH keys for a new user, password authentication is still configured. After you’ve thoroughly tested your SSH keys to make sure they are working properly, it is a good idea to disable password authentication for the reasons you state. You can find the steps to do that in this guide.

            I hope that helps!

            This comment has been deleted

              I’ved followed all the tutorial step by step. I’m using Windows ( so Putty as client and Putty_gen as key generator ). I’d copy the public key in authorized_key 's file, but when i try to connect via Putty, it requires password and not the SSL. i’d try to use the public key ( with another session of Putty ), and it answer me with the following error :

              type 2 ( protocol error ) : “bad service request ssh-connection”

              on the active connection i gived the command ssh -vvv myuser@myipaddress

              and the extract of the debug is :

              debug2: key: /home/myuser/.ssh/id_rsa ((nil)), debug2: key: /home/myuser/.ssh/id_dsa ((nil)), debug2: key: /home/myuser/.ssh/id_ecdsa ((nil)), debug2: key: /home/myuser/.ssh/id_ed25519 ((nil)), debug1: Authentications that can continue: publickey,password debug3: start over, passed a different list publickey,password debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password debug3: authmethod_lookup publickey debug3: remaining preferred: keyboard-interactive,password debug3: authmethod_is_enabled publickey debug1: Next authentication method: publickey debug1: Trying private key: /home/myuser/.ssh/id_rsa debug3: no such identity: /home/myuser/.ssh/id_rsa: No such file or directory debug1: Trying private key: /home/myuser/.ssh/id_dsa debug3: no such identity: /home/myuser/.ssh/id_dsa: No such file or directory debug1: Trying private key: /home/myuser/.ssh/id_ecdsa debug3: no such identity: /home/myuser/.ssh/id_ecdsa: No such file or directory debug1: Trying private key: /home/myuser/.ssh/id_ed25519 debug3: no such identity: /home/myuser/.ssh/id_ed25519: No such file or directory debug2: we did not send a packet, disable method debug3: authmethod_lookup password debug3: remaining preferred: ,password debug3: authmethod_is_enabled password debug1: Next authentication method: password

              Any help, pls?

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              March 25, 2015

              @zerobyte: I’m not entirely familiar with PuTTY, but from the logs from the second PuTTY session, it looks like it is unable to find your private key. Just to be clear, you are supposed to add the public key to the authorized keys file on the server. You use the private key on your local computer to connect. Can you see if the ssh command works correctly if you explicitly point to your private key using the -i option?

              It would look something like this:

              ssh -vvv -i /path/to/ssh_private_key myusername@myipaddress
              

              Usually, the private key that you generate will be called id_rsa and the public key that you should copy to the authorized_keys file should be called id_rsa.pub. Hopefully that helps a bit.

              … maybe I’m nitpicking, but the link at the end for what’s next… it doesn’t cover fail2ban there as the description following the link implies it would. It is covered here though, https://www.digitalocean.com/community/tutorials/how-to-install-and-use-fail2ban-on-ubuntu-14-04

              Great tutorial! I have few issues:

              1. in my ssh_config file:
              • Do I need to remove the # before the Port… I guess I do so I removed it.
              • I don’t have any PermitRootLogin yes so I add at the end PermitRootLogin no. Is it ok?
              1. When try to log in using my new user I get: ssh: connect to host IP-NUMBER port 4444: Connection refused

              I have tried sshd -T as @tamara said but can’t follow and understand what to do. At the beginning I get: Could not load host key: /etc/ssh/ssh_host_ed25519_key

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 7, 2015

              @amir1117926: Hello! First, make sure that you are editing the sshd_config file and not the ssh_config file. This should be done after using SSH to connect to your server (not on your local machine).

              Otherwise, yes you would remove the # character before any line that you edit so that your changes are seen by the server (the # character indicates that the line is a comment which SSH should ignore. Removing it “activates” the line). If your specific file does not have a certain directive (like PermitRootLogin), you can safely add it.

              Remember to restart the SSH service on the server after you’ve made your changes:

              sudo service ssh restart
              

              Afterwards, the command you’ll need to reconnect as your new users is ssh (not sshd) from your local computer. From your local computer, this will look something like this:

              ssh -p 4444 your_user@IP-NUMBER
              

              I hope that helps!

              @jellingwood thank you! And what a newbie mistake!!! Now it work great and I update the ssh_config as well removing my changes.

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 8, 2015

              @amir1117926: Awesome! Glad it was an easy fix :)

              How can I upload files from my mac to my server? I tried this

              scp /Users/MacBookPro/Desktop/wptest.zip -p 4444 serveruser@xxx.xxx.xxx.xxx:/var/www/html/webs/wptest
              

              But the console always respond like this

              ssh: connect to host 192.241.199.233 port 22: Connection refused
              
              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 7, 2015

              @babyjungle: Hey, I think I can help you here.

              Confusingly, while ssh uses the -p flag, scp uses the -P flag (notice the capitalization). Also, put your port specification before the file you are trying to copy. It’ll look something like this:

              scp -P 4444 /Users/MacBookPro/Desktop/wptest.zip serveruser@xxx.xxx.xxx.xxx:/var/www/html/webs/wptest
              

              Let me know if that helps.

              Hi thanks, I tried and so far I dont get that notice, but I got this instead:

              usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
                     cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory
              

              I looked in my server if the file was already uploaded and no…nothing there…

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 7, 2015

              @babyjungle: It looks like you tried to use cp instead of scp. What happens when you try again with scp?

              Using SCP refuses the connections on port 22. This is what I’m doing now

              scp /Users/MacBookPro/Desktop/wptest.zip -P 4444 serveruser@xxx.xxx.xxx.xxx:/var/www/html/webs/wptest
              

              And this is the message that I’m getting:

              ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection refused
              lost connection
              

              Ok its working now, I just had to put the -P at the beginning, and not between the local path and the server :)

              But now I’m getting a message saying that the directory doesnt exist, and I already create it…

              scp: 4444:/var/www/html/webs/wptest: No such file or directory

              I was missing 2 important settings in this tutorial:

              1. set locale (sudo nano /etc/default/locale) // before I got errors and packages were downloaded incomplete
              2. set server time (sudo dpkg-reconfigure tzdata) // otherwise log files will confuse you

              Optional: 3. add swap file // important when running small droplets for intensive tasks (e.g. mail servers)

              not

              gpasswd -ademo sudo
              

              use

              gpasswd -a demo sudo
              
              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 22, 2015

              @badalloffsh: Thanks for the heads up. We’re actually having an issue with our markdown parser at the moment (it’s removing spaces before our highlighted text). It should hopefully be fixed soon.

              Hi. I completed all steps successfully. But when I try to ssh to my new user like ssh -p [NEW_PORT] newuser@SERVER_IP_ADDRESS, it doesn’t ask a password, just logging in. Did I do something wrong, or is it the way it does?

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 28, 2015

              @sodbileg: Setting up your public SSH key on your server will allow you to authenticate without having to enter a password as long as you are connecting from a computer that holds the corresponding private key. When you connect, your computer will prove to the server that it holds the private key and the server will allow you to log in. Anyone connecting from a computer without the private key will be denied (or asked for a password depending on your configuration). So if you are able to log in without a password, that means that everything is set up correctly.

              ‘where to go from here’ links to further steps and says that it will cover things like fail2ban - however the linked page does not cover fail2ban

              https://www.digitalocean.com/community/tutorials/additional-recommended-steps-for-new-ubuntu-14-04-servers

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 29, 2015

              @rob107421: Oops! Apologies for the mistake. I’ve updated the paragraphs at the end of this guide to include a link to our fail2ban article.

              @jellingwood possible problem with the additional steps and the fail2ban article. as far as I can see, the fail2ban article assumes iptables - but the additional steps article uses ufw

              Justin Ellingwood
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 29, 2015

              @rob107421: The ufw firewall is simply a wrapper used to manage iptables rules more easily, so I don’t think that it would cause any issues. Let me know if you find out otherwise.

              For those who have trouble logging in with ssh key and falls back to password, the problem for me was the permissions, more specifically the group that .ssh folder and .ssh/autherized_keys belonged to. For me this did the trick: chown $USER:$USER ~/.ssh -R For more information this post on askubuntu really helped

              After following tutorial above and try to login with newly created user, i have this problem when running a command with root privileges (via putty @Win 7 ultimate), e.g

              sudo service apache2 restart
              sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
              

              How to solve this problem … do i have to reboot ?

              However ssh access with root still working well.

              adduser demo sudo
              

              This is a better and more intuitive way of adding a user to the sudo group, I think.

              Thanks for the very clear article.

              I would suggest that once the user SSH key has been added, password based logins need to be turned off by setting PasswordAuthentication to no in /etc/ssh/sshd_config. Having password based logins still available allows brute-forcing as an attack vector and kind-of defeats the point of configuring an ssh key

              have’nt add Demo as user just using my root account. Is it necessary to use other user account to be safe or it dose’nt matter?

              I need to one more thing. How to make search engine for my website? any tutorial for beginners on that? or any pre tools like “sphider php search engine” does fine? or any others light weight you want to suggest.

              thanks man in advance.

              hi , local machine is my computer ok but where exatly in windows 7 i am confused … i tried it in cmd but nothing …

              Kamal Nasser
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 21, 2015

              Hi! You need to SSH in to your droplet using PuTTy or any other SSH client and then run the commands in this tutorial in your droplet.

              This was completely useless. There is no indication how to install an existing project. I installed git and pulled, but error upon error occurred with dependences, postgres and gunicorn which just could not find the project. What is the point of this tutorial? It’s unusable for anyone who has an existing project they want to deploy…

              Kamal Nasser
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 22, 2015

              Hi! This tutorial walks you through the “initial” server setup which prepares the server for whatever you want to install on it, be it a webserver, a database server, a backup program, etc…

              Once you’ve followed this tutorial, take a look at How to Deploy Python WSGI Apps Using Gunicorn HTTP Server Behind Nginx. If you’re deploying a Django app, this might be a better resource: How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 14.04.

              This comment has been deleted

                I was being required for a password even if I have my public key setup so I set in /etc/ssh/sshd_config:

                PubkeyAuthentication yes
                AuthorizedKeysFile      %h/.ssh/authorized_keys
                

                This should allow password less ssh like ssh demo@IP_ADDRESS.

                Hi, I just enabled public key authentication on my Ubuntu 15.10 x64 droplet - and indeed, next time I logged in from my machine, I was prompted to enter the pass-phrase. I then proceeded to log in from another machine (my laptop) - same user, same Ubuntu server - and I could still log in from my laptop with simple user-password authentication - no private key available on that machine.

                It defeats the purpose of having that extra layer of authentication if it can be bypassed like that.

                It appears that you also need to disable the regular authentication by:

                sudo nano /etc/ssh/sshd_config
                # Change yes to no:
                PasswordAuthentication no
                # Save and exit file
                sudo service ssh restart
                

                after Step Six I got this error: service ssh restart

                stop: Rejected send message, 1 matched rules; type="method_call", sender=":1.10" (uid=1000 pid=1222 comm="stop ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Stop" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init ")
                start: Rejected send message, 1 matched rules; type="method_call", sender=":1.11" (uid=1000 pid=1216 comm="start ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init ")
                

                Can someone help, please? :-)

                Justin Ellingwood
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 18, 2015

                @heyalbert: You can try to use sudo before the command like this: sudo service ssh restart.

                In a previous section of the guide (the end of step 4), we exit out of the new user account by typing exit. The error you’re getting indicates that you’re trying to execute the restart command as a non-root user (the user ID is 1000). You can try sudo before the command or you can type exit to get back to your root session and execute the command.

                Oh no, I forgot. Thank you!

                Hey, I couldn’t see PermitRootLogin in my VPS server file /etc/ssh/sshd_config

                What ports, IPs and protocols we listen for

                Port 22

                Use these options to restrict which interfaces/protocols sshd will bind to

                #ListenAddress :: #ListenAddress 0.0.0.0 Protocol 2

                HostKeys for protocol version 2

                HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key HostKey /etc/ssh/ssh_host_ecdsa_key HostKey /etc/ssh/ssh_host_ed25519_key #Privilege Separation is turned on for security UsePrivilegeSeparation yes

                Lifetime and size of ephemeral version 1 server key

                KeyRegenerationInterval 3600 ServerKeyBits 1024

                Above is what in the file ?

                When I do “nano .ssh/authorized_keys” I get: Error opening terminal: msys. (on windows in git shell)

                Now droplets can be created with adding SSH keys in the first place. I wonder whether should I continue on step four to six. I’m confused. If necessary, please explain the reason to me. Thanks.

                I’m lost.

                What do you mean by “local machine” in step 4? My Windows computer?

                I can’t do this in the console of my Droplet?

                FYI as a helpful comment, for Step #4 in reference to manually setting up SSH keys for the newly created user. I wasn’t able to login because what I did was do a copy root’s authorized_keys file to the new users .ssh/ folder. I guess perhaps because it was referencing the same indexed file as root, therefore I simply copied the contents of the file THEN created a new file and pasted the comments.

                All that to say, dont copy the file from root or it will fail. A new file with the same contents is whats needed.

                In step 1
                I don’t know how can I get SERVER_IP_ADDRESS ?

                Thanks, everything worked just fine on Ubuntu 14.04.

                Which command will undo the root permission to “yes”? I’m trying to use serverpilot and it wants access to root… Is it possible to use serverpilot after doing these tutorial steps?

                In Step Five — Configure SSH Daemon, I do not have the following lines in the file;

                /etc/ssh/sshd_config (before) PermitRootLogin yes

                What am I missing here? Is there some step I should have complete for them to be in the file?

                I remember there was a step which asked us to change the SSH port. May I know why was it removed from the tutorial?

                May I suggest that after changing /etc/ssh/sshd_config with:

                #PermitRootLogin yes
                PermitRootLogin no
                

                also suggest users to change:

                #PasswordAuthentication yes
                PasswordAuthentication no
                

                Otherwise people can still log in from other machines bypassing the extra securit added by public/private key authentication. See topic: https://www.digitalocean.com/community/questions/after-enabling-public-key-authentication-i-can-still-log-in-without-from-other-machine

                How can I:

                1. Disable password logins completely for all users?

                2. Allow my new user with superuser access to su/sudo without a password?

                I want to force the use of SSH keys and only keys for everything and not allow any outside root logins. Passwords are pointless, unnecessary and difficult to remember if secure.

                Justin Ellingwood
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 9, 2016

                @bn520995: You can disable password authentication by adjusting the /etc/ssh/sshd_config file:

                1. sudo nano /etc/ssh/sshd_config

                Find the PasswordAuthentication directive, uncomment it and set it to “no”:

                /etc/ssh/sshd_config
                . . .
                # Change to no to disable tunnelled clear text passwords
                PasswordAuthentication no
                . . .
                

                Do a search through the file for “Authentication” and make sure that, out of the found directives, only RSAAuthentication and PubkeyAuthentication are set to “yes”. Save and close the file when you are done.

                Restart your SSH server to implement the changes:

                1. sudo service ssh restart

                That should make it so that only SSH keys are accepted.

                You can test this by using the -v option when connecting to your server:

                1. ssh -v user@server_domain_or_IP

                Among the output, you should see:

                Output
                . . . debug1: Authentications that can continue: publickey . . .

                Since the server is reporting that public key authentication is the only available authentication method, it means your changes were implemented successfully.

                So I went through the first half of this tutorial just fine, but stopped before restricting root access because I need to know how to access the key first. I log into my server via PuTTY and need a private key file saved to my computer in order to login.

                How can I access the private ssh key so that I can save it and login with PuTTY?

                After login as demo don’t forget to do:

                sudo chown -R demo:demo .ssh
                

                or ssh return “Server refused our key”, because sshd don’t have access to key at directory.

                N.B. this need to do in home directory of demo user. p.s. I’m so sorry for my bad english, hope u can understood what i mean.

                Excellent tutorial. One question though: I’ve added a separate rsa key for my user, and disabled root access. I can log in as user and run sudo commands just fine. However, the owner of the .ssh folder for that user is still root. So, if I lock it down with 600 and 700, I’m locked out of my server. Should I change user directory and authorized_keys file ownership from root to user, and then secure them? Sorry, I’m very new to this. Thanks in advance to anyone who can help.

                why does it only let me store one key in .ssh? i can only overwrite, can’t make more than one I logged into my droplet root using ssh via command line. I entered the password for the public key and logged in. then this digital ocean guide has me creating another key for a superuser but I don’t know how to store both in that folder

                I want to disable password authentication for all users. In my /etc/ssh/sshd_config password authentication and root login has been set to “no”:

                PermitRootLogin no
                …
                PasswordAuthentication no
                

                But after executing sudo service ssh restart, exiting and trying to log back in with ssh -v user@IP, I still see “password” listed as a means for authentication:

                …
                debug1: Authentications that can continue: publickey,password

                Does this debug message mean than password authentication is still possible? If so, how can I disable it?

                Am I confused in that this tutorial actually doesn’t disable logging in without the key? In other words you can still login with a username\password?

                If in Step Four I have added Public Key Authentication to the new user created (SSH key), why do I still have to type the password when logging in with this user?

                I tried this tutorial to set up my Ubuntu server connecting from Windows by PuTTY and I got quite confused in following the steps. The ‘local machine’ part especially left me clueless. After several hours of struggling to get it through my thick head, I realized that the same result could be gotten with a few mouse clicks in the PuTTY window. I think it would be better if this article were tagged as for Unix/Mac users.

                TL;DR: I recommend PuTTY users read the following tutorial instead:

                https://www.digitalocean.com/community/tutorials/how-to-use-ssh-keys-with-putty-on-digitalocean-droplets-windows-users

                Thank you…!!! this very help for me

                This comment has been deleted

                  I tried this documentation, its really helpful and works great. I haven’t faced any issues with it.

                  In step 4 of this tutorial under Generate a key pair , it states:

                  ‘If you do not already have an SSH key pair, which consists of a public and private key, you need to generate one.’

                  Is this suggesting that if I’ve already generated keys as part of setting up the Droplet that I can use them again for this new user I’m creating? If it is not suggesting this is it acceptable to over write the files stored in local $ /home/USER/.ssh/id_rsa where my current key pairs generated for root are stored?

                  I have made a bash script to automate the setup process, hopefully this will be useful to someone else.

                  This comment has been deleted

                    at step 6 when I enter the command ‘sudo command_to_run’ is distinguished out: rosamint@ubuntu-512mb-nyc3-02:~$ sudo command_to_run sudo: command_to_run: command not found

                    is this okay?

                    I am using Putty on Local now. I followed this tutorial several times, always has the same problem, i can ssh login as root, but not non-root, error says: server refused the keys. I am guessing it is some setting that is not permitting non-root user to login SSH

                    when you give ssh to non-root, is there any change you need to do in /etc/ssh/sshd_config? in my /etc/ssh/sshd_config of my ubuntu 14.04, there is one line that was commented #authrizedkeyfile: @h:/.ssh/authorized.key, and that is the directory i used to store public key. Do i need to uncomment that?

                    Hi, i did not find Users directory on my ubuntu server.

                    I have just found an usr directory.

                    Is the same above both direcrory?

                    How do i access the server as local $ in Putty? Or, who shall command ssh keygen: root or user or who?

                    Ok, i am root, i am user, but how i become localuser so i can generate the keys?

                    I made it all the way to step 4, but when I exit to my local machine and try to login as the new user, it says:

                    ➜ ~ ssh trev@[SERVER_IP] Permission denied (publickey).

                    I ran into that issue as well. When I moved the SSH key into the droplet I copied it in the wrong format somehow. I put the key into the droplet config when I first made it, so I ended up going back to that screen, copying it from there, and pasting it in again. It’s very picky about every aspect of the format - a line break where it doesn’t belong will cause a failure.

                    In the last step “Reload SSH”, it might be a good idea to recommend attempting to SSH as root, as well; we disabled SSH as root earlier, so attempting to do so should return negative feedback. Seems like a nice little extra step of security to me.

                    I’m not really following what to do at this point

                    Now, before we log out of the server, we should test our new configuration. We do not want to disconnect until we can confirm that new connections can be established successfully.

                    Open a new terminal window on your local machine. In the new window, we need to begin a new connection to our server. This time, instead of using the root account, we want to use the new account that we created.

                    For the server that we showed you how to configure above, you would connect using this command. Substitute your own user name and server IP address where appropriate:

                    could anyone help with a little more detail explanation for me?

                    Justin Ellingwood
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 22, 2017

                    @juanleon7 Since that part of the tutorial is modifying the SSH settings, which impact how users are able to connect to the server, the instructions there are meant to help you test that the settings are correct before disconnecting from the server.

                    The process involves:

                    1. Changing the SSH settings
                    2. Restarting the SSH service on the server
                    3. Without disconnecting, open a new connection to the server. If you are able to connect successfully with a new connection, then your settings are correct. If you are unable to connect, you still have an active session open so that you can revert the settings and troubleshoot.

                    The instructions are meant to help you avoid locking yourself out of the server in case a mistake was made. I hope that helps.

                    Hi thank you for the helpful post, as I am completely new to this. I followed steps 1-6 and it all seemed to have worked. But now when I try to login as root@server_ip and I am asked for the password, I get a message saying “Permission denied (publickey,password”). I can still login with the user I created in step 2 of your tutorial. What am I doing wrong?

                    Unable to copy SSH key from computer to GNU nano. In GNU nano on my MacBook Pro, there is no way to do this. Tried right clicking to paste and a bunch of other things. No luck.

                    When you create a new key and you give it a specific name (not the default id_rsa), in order to connect to the server you must tell SSH that you want to use that specific key:

                    ssh -i ~/.ssh/specific_identity_file user_name_on_server@droplet_ip 
                    

                    If you don’t want to add your specific identity file every time you connect (and I guess nobody wants that), create a new “config” file in the ~/.ssh folder (the file will be ~/.ssh/config), if there isn’t one and add the following:

                    Host some_host_name
                    	HostName droplet_ip
                    	IdentityFile ~/.ssh/specific_identity_file
                    	User user_name_on_server
                    

                    Of course, replace some_host_name with whatever you like to call your host, the droplet_ip with your server ip, the specific_identity_file with the ssh file name (without the .pub extension) and the user_name_on_server with the username you added your specific ssh key to.

                    Afterwards you can connect using:

                    ssh some_host_name
                    

                    (or whatever you named your host to - on the first line)

                    Hope it helps.

                    This comment has been deleted

                      This comment has been deleted

                        This comment has been deleted

                          This comment has been deleted

                            what shell or command prompt thingy are you using ? I am so confused and can’t find any shell thing that will accept local$ ssh root@SERVER_IP_ADDRESs

                            nothing recognizes local$

                            Justin Ellingwood
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            July 19, 2017

                            @funianrun Hey there. Sorry to see you’re having trouble and I can see why this is a bit confusing.

                            The local$ portion of that line is actually just supposed to represent your command line prompt. It’s labeled local to indicate that you should type that command into your terminal on your local computer, not when SSH’ed into a server. So the actual command you need to run comes after that part.

                            In contrast, the commands that should be run on your remote server just start with $ for a regular user prompt or # for a root (administrative user) prompt.

                            If it helps you keep this all straight, the portion of the prompt that you can highlight and select with your mouse is the actual command. The remaining portion on the left will indicate where to run that command:

                            • local$: Run in your terminal while not SSH’ed into a server
                            • $: Run in your terminal while SSH’ed into a server as a regular user
                            • #: Run in your terminal while SSH’d into a server as the root user.

                            I hope that helps a bit. And when you’re ready, make sure you remember to switch out SERVER_IP_ADDRESS with your actual server’s IP address when running the ssh command! Good luck!

                            great this makes sense now! thansk alot:)

                            This was awesome. Thanks :)

                            alt text
                            Thumbs Up

                            All went well with this process; I set up a new super user with password, but when I try to test on terminal from my local, it gives me an incorrect password message. I tried to change the password in case I typed wrong, but still get “sorry, try again” no matter what I enter

                            For anyone who adds an SSH key to ~/.ssh/authorized_keys and still gets the password prompt when trying to ssh into the server. A simple oversight is if you have multiple keys on your local machine, you need to specify which key ssh should use with ssh -i .ssh/key_file user@server .

                            I looked up a handful of over-thought solutions to this, none of them mentioned making sure the correct key is being used.

                            Try DigitalOcean for free

                            Click below to sign up and get $200 of credit to try our products over 60 days!

                            Sign up

                            Join the Tech Talk
                            Success! Thank you! Please check your email for further details.

                            Please complete your information!

                            Become a contributor for community

                            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                            DigitalOcean Documentation

                            Full documentation for every DigitalOcean product.

                            Resources for startups and SMBs

                            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                            Get our newsletter

                            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                            New accounts only. By submitting your email you agree to our Privacy Policy

                            The developer cloud

                            Scale up as you grow — whether you're running one virtual machine or ten thousand.

                            Get started for free

                            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                            *This promotional offer applies to new accounts only.