Skip to content
ImagineWorld

Connecting to Networks

node_idnode-book_mastering-ubuntu-server_chapter-10-connecting-to-networks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleConnecting to Networks
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Linux networks took the IT industry by storm. Many organizations use Linux in their data centers, on both physical servers and in the cloud. Ubuntu Server is among the most popular choices for running mission-critical applications, but without a stable network to connect the individual components of your infrastructure together, even the most powerful server hardware will be ineffective.

So far in this book, we’ve worked with a single Ubuntu Server instance. Here, we begin a two-part look at networking in Linux. In this chapter, we’ll discuss topics related to initial network connectivity and remote management. We’ll continue learning additional networking topics in Chapter 11, Setting Up Network Services, where we’ll work on building and configuring additional components that will enable your servers to communicate more effectively, which will result in a strong foundational network that will serve your needs for years to come.

In this episode of our Ubuntu adventure, we will cover:

  • Setting the hostname
  • Managing network interfaces
  • Assigning static IP addresses
  • Understanding Linux name resolution
  • Getting started with OpenSSH
  • Getting started with SSH key management
  • Simplifying SSH connections with a config file

To get started in our exploration of networking, we should first give each of our Ubuntu servers its own identity; basically, we should give them a name to help distinguish each from the others.

During installation, you were asked to create a hostname for your server. Specifically, the field was labeled Your server's name during the initial setup process. At that time, our goal was to simply get an Ubuntu Server installation set up for working through the examples in this book. At this point, you may consider changing the hostname of your server.

When we utilize OpenSSH to remotely manage our servers (as we’ll do later on in this chapter), the hostname is shown on the command line. That can be very confusing if all servers have the same name. More importantly, the hostname of a server gives it an identity. When it comes to real production deployments of Ubuntu Server, each individual server should have its own designated purpose, and be named accordingly. Often, organizations will have their own naming scheme. Perhaps web servers in a company are named similar to webserver-01, or with a fully qualified domain name, such as webserver-01.example.com.

In this book, I won’t assume any particular naming scheme, so when we do work through changing the hostname, feel free to adjust the name as you see fit. If you don’t have a naming scheme (but would like to create one) feel free to get creative. I’ve seen quite a few variations, from naming servers after cartoon characters (who wouldn’t want a server named daffy-duck?), to Greek gods or goddesses. Some companies choose to be a bit boring and come up with naming schemes consisting of a series of characters separated by hyphens, with codes representing which rack the server is in, as well as its purpose. You can create your own naming convention if you haven’t already, and no matter what you come up with, I won’t judge you.

As I mentioned, the hostname of your server is its identity. It identifies your server to the rest of the network. While a simple hostname, such as ubuntu, is fine if you have just one host, it would get confusing really quickly if you kept the default on every Ubuntu Server within your network. Giving each server a descriptive name helps you tell them apart from each other. But there’s more to a server’s name than its hostname, which we’ll get into in Chapter 11, Setting Up Network Services, when we discuss DNS. But for now, we’ll work through viewing and configuring the hostname, so you’ll be ready to make your hostname official with a DNS assignment, when we come to it.

So, how do you view your hostname? One way is to simply look at your shell prompt; you’ve probably already noticed that your hostname is included there. While you can customize your shell prompt in many different ways, the default shows your current hostname. However, depending on what you’ve named your server, it may or may not show the entire name. Basically, the default prompt (known as a PS1 prompt, in case you were wondering) shows the hostname only until it reaches the first period. For example, if your hostname is dev.mycompany.org, your prompt will only show dev. To view the entire hostname, simply enter the hostname command:

Graphical user interface, application Description automatically generated

Figure 10.1: Output from the hostname command

Changing the hostname is fairly simple. To do this, we can use the hostnamectl command as root or with sudo. If, for example, I’d like to change my hostname from dev.mynetwork.org to dev2.mynetwork.org, I would execute the following command:

sudo hostnamectl set-hostname dev2.mynetwork.org

Simple enough, but what does that command actually do? Well, I’d love to give you a fancy outline, but all it really does is change the contents of a text file (specifically, /etc/hostname). To see this for yourself, feel free to use the cat command to view the contents of this file before and after making the change with hostnamectl:

cat /etc/hostname

You’ll see that this file contains only your hostname.

Once you change your hostname, you may start seeing an error message similar to the following after executing some commands:

unable to resolve host dev.mynetwork.org

This error means that the computer is no longer able to resolve your local hostname. This is due to the fact that the /etc/hostname file is not the only file where your hostname is located; it’s also referenced in /etc/hosts. Unfortunately, the hostnamectl command doesn’t update /etc/hosts for you, so you’ll need to edit that file yourself to make the error go away. Here’s what an /etc/hosts file looks like on an example server:

Text Description automatically generated

Figure 10.2: Sample contents from an /etc/hosts file

The first two entries, in this example, refer to the local machine itself. Localhost addresses, also known as loopback addresses, allow the machine to essentially reach itself. If you were to use the ping command against the 127.0.0.1 address, the reply would come from the machine that executed the command, not from another host on the network. On the first line, we have the following:

127.0.0.1 localhost

If you were to use any networking command to attempt to communicate with the local server, such as pinging 127.0.0.1 or localhost, the /etc/hosts file on this line declares that this communication is directed toward the underlying server itself.

With the second line in the example screenshot, we have the following:

127.0.1.1 dev.mynetwork.org dev

Depending on your configuration, such as whether you are using a physical server, a virtualization platform, or a cloud server provider, that line may or may not be present. You can add that line if it’s missing, but we’ll talk about that more in a moment.

Essentially, that particular line identifies that the local server can also be reached at the IP address 127.0.1.1, the fully qualified domain name of dev.mynetwork.org, as well as the simplified form of dev. A fully qualified domain name consists of the name of the server (dev in this case) as well as the domain name for the organization (mynetwork.org in this example). This enables you to ping your local server directly from that server by using the name dev.mynetwork.org or the simplified form of dev.

If you don’t have a domain name to use with your servers, you can leave the fully qualified domain name out of the /etc/hosts file. So in our example, that line would look like the following if there was no domain:

127.0.1.1 dev

Going back to our example of changing a hostname on a server, I mentioned that you can use the hostnamectl command to do that, but that command doesn’t update the /etc/hosts file for you, it only updates the /etc/hostname file. It’s a best practice to also update the /etc/hosts file to match. You can avoid using the hostnamectl command altogether and manually edit the /etc/hosts and /etc/hostname files, which is actually my preferred method. If I have to manually edit a text file, regardless of whether or not I use the hostnamectl command, I figure that I may as well use a text editor for both.

The main takeaway, though, is to give your servers an identity that makes sense and matches the role that the server will fill within your network. At a typical organization, you’ll have web servers, file servers, database servers, and more. A consistent and logical naming scheme will just make everything that much easier.

Now that we have learned how to give our servers an identity, we can learn how to manage network interfaces.

Networking is critical for server infrastructure. Without a network, servers cannot communicate with one another, and users will be unable to access them. In order for a server to connect to a network, it needs to have a network interface installed. Most servers will have a standard wired Ethernet adapter installed, allowing you to plug in a network cable to connect it to a switch. Assuming our server’s hardware has been properly detected by Ubuntu, this is handled pretty much automatically. However, the automatic configuration is not always ideal. Perhaps we want to customize the IP address or settings related to the connection.

First, we need to understand how to view the current connection parameters that the network card of our server currently has in effect. That’s the main goal of this section. We can do so using two basic commands: ip (which is recommended) and ifconfig (which was the previous method in older versions of Ubuntu, and its usage is no longer recommended).

We can review information regarding our network interfaces and manage them with the ip command. For example, we can use ip addr show to view our currently assigned IP address:

ip addr show

This will produce an output similar to that shown in the following screenshot:

Text Description automatically generated

Figure 10.3: Viewing IP information with the ip addr show command

Once you enter that command, you should see output that pertains to the network interfaces that you have available and their current status. Also, you can abbreviate the command all the way down to simply ip a (the output will be the same in either case). From the output, we can see several useful tidbits, such as the IP address for each device (if it has one), as well as its MAC address.

Using the ip command, we can also manage the state of an interface. We can bring a device down (prevent it from connecting to networks), and then back up again:

sudo ip link set enp0s3 down
sudo ip link set enp0s3 up

In that example, I’m simply toggling the state for interface enp0s3. First, I’m bringing it down, and then I’m bringing it back up again.

Bringing interfaces up and down is all well and good, but what’s up with that naming convention? The convention used in Ubuntu 22.04 may seem a bit strange for those of you that have grown accustomed to the scheme used in earlier versions, which utilized network interface names such as eth0, wlan0, and so on. Since Ubuntu is based on Debian, it has adopted the new naming convention that was introduced starting with Debian 9.0.

The new naming convention has been put in place in order to make interface naming more predictable. While you may argue that names such as eth0 may be easier to memorize than something like enp0s3, the change helps the name stay persistent between boots. When you add new network interfaces to a Linux system, there’s always the possibility that other interface names may change as well.

For example, if you have an older Linux installation on a server with a single network card (eth0) and you add a second (which is given the name eth1), your configuration may break if the names were to get switched during the next boot. Imagine for a moment that one interface is connected to the internet and another connected to a switch (basically, you have an internet gateway). If the interfaces came up in the wrong order, internet access would be disrupted for your entire office, due to the fact that the firewall rules you’ve written are being applied to the wrong interfaces. Definitely not a pleasant experience!

In the past, previous versions of Ubuntu (as well as Debian, and even CentOS) have opted to use udev to make the names stick in order to work around this issue. This is no longer necessary nowadays, but I figured I’d mention it here just in case you end up working on a server with an older installation. These older servers would achieve stickiness with interface names from configuration stored in the following file:

/etc/udev/rules.d/70-persistent-net-rules

This file existed on older versions of some popular Linux distributions (including Ubuntu), as a workaround to this problem. This file contains some information that identifies specific qualities of the network interface, so that with each boot, it will always come up with the same name. Therefore, the card you recognize as eth0 will always be eth0. If you have an older version of Ubuntu Server in use, you should be able to see this file for yourself. Here’s some sample output of this file on an older installation:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*",
TTR{address}=="01:22:4e:a5:f2:ec", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

As you can see, it’s using the MAC address of the card to identify it with eth0. But this becomes a small problem if I want to take an image of this machine and re-deploy it onto another server. This is a common practice—we administrators rarely start over from scratch if we don’t have to, and if another server is similar enough to a new server’s desired purpose, cloning it will be an option. However, when we restore the image onto another server, the /etc/udev/rules.d/70-persistent-net-rules file will come along for the ride. We’ll more than likely find that the new server’s first network interface will have a designation of eth1, even if we only have one interface.

This is because the file already designated a device as eth0 (it’s referencing a device that’s not present in the system), so we would need to correct this file ourselves in order to reclaim eth0. We would do that by editing the rules file, deleting the line that contains the card that’s not on the system, and then changing the device designation on the remaining line back to eth0.

The new naming scheme is effective as of systemd v197 and later (in case you didn’t already know from earlier topics in this book, systemd is the underlying framework utilized in Ubuntu for managing processes and various resources). For the most part, the new naming convention references the physical location of the network card on your system’s bus.

Therefore, the name it receives cannot change unless you were to actually remove the network card and place it in a different slot on the system’s board, or change the position of the virtual network device in your hypervisor.

As a quick overview of how the network names break down, en is for Ethernet, and wl is for wireless. Therefore, we know that the example interface I mentioned earlier (enp0s3) references a wired card. The p references which bus is being used, so p0 refers to the system’s first PCI bus (the numbering starts at 0). Next, we have s3, which references PCI slot 3. Putting it together, enp0s3 references a wired network interface card on the system’s first bus, placed in PCI slot 3. The exact details of the new naming specification could even be a chapter of its own, but hopefully this gives you a general idea of how the new naming convention breaks down. There’s much more documentation online if you’re interested in the nitty-gritty details (see the Further reading section). The important point here is that since the new naming scheme is based on where the card is physically located, it’s much less likely to change abruptly. In fact, it can’t change, as long as you don’t physically switch the positions of your network cards inside the case.

Getting back to managing our interfaces, another command worth discussion is ifconfig.

The ifconfig command is part of the net-tools suite of utilities, which has been deprecated (for the most part). Its replacement is the iproute2 suite of utilities, which includes the ip command we’ve already discussed. In summary, this basically means you should be using commands from the iproute2 suite, instead of commands such as ifconfig. The problem, though, is that most administrators nowadays still use ifconfig, with no sign of it slowing down. In fact, the net-tools suite has been recommended for deprecation for years now, and many Linux distributions shipping today still have this suite installed by default. Those that don’t have it installed offer it as an additional package that you can install. In the case of Ubuntu Server 22.04, the net-tools package is no longer installed by default, but it’s still available if you want to manually install it. I don’t recommend installing it though, since it’s deprecated and shouldn’t be used anymore.

The reason commands such as ifconfig have a tendency to stick around so long after they’ve been deprecated usually comes down to the change is hard mentality, but quite a few scripts and programs out there are still using ifconfig, and therefore it’s worth discussing here. Even if you immediately stop using ifconfig, and move to ip from now on, you’ll still encounter this command on your travels, so you may as well know a few examples. Knowing the older commands will also help you if you find yourself on an older server.

First, when executed by itself with no options, ifconfig will print information regarding your interfaces like we did with ip addr show earlier. That seems pretty simple.

If you are unable to use ifconfig to view interface information using a normal user, try using the fully qualified command (include the full path):

/usr/sbin/ifconfig

The /usr/sbin directory may or may not be in your $PATH (a set of directories your shell looks within for commands), so if your system doesn’t recognize ifconfig, using the fully qualified command should produce the desired output, as follows:

Text Description automatically generated

Figure 10.4: Viewing interface information with the ifconfig command

Secondly, just like with the ip commands we practiced earlier, we can also bring an interface down or up with ifconfig as well:

sudo ifconfig enp0s3 down
sudo ifconfig enp0s3 up

There are, of course, other options and variations of ip and ifconfig, so feel free to look up the man pages for either if you want more information. For the purposes of this section, the main thing is to remember how to view your current IP assignments, as well as how to bring an interface up or down.

As useful as our network interfaces can be, they’re useless without an IP address assigned to them. While a network will often use DHCP to take care of this, in the next section we’ll take a look at how to assign a static IP address.

With servers, it’s very important that your IP addresses remain fixed and do not change for any reason. If an IP address does change (such as a dynamic lease with no reservation), your users will experience an outage, services will fail, or entire sites may become unavailable. When you install Ubuntu Server, it will grab a dynamically assigned lease from your DHCP server, but after you configure the server the way you want it, it’s important to set a permanent IP address right away before it’s considered production-ready. One exception to this rule is an Ubuntu-based VPS. Cloud providers that bill you for these servers will have an automatic system in place to declare an IP address for your new VPS, and will already have it configured to remain in place. But in the case of virtual or physical servers you manage yourself, you’ll start off with a dynamic address, unless you’ve already configured a static IP address during installation.

In most cases, you’ll have an IP address scheme in place at your office or organization, which will outline a range of IP addresses that are available for use with static assignments. If you don’t have such a scheme, it’s important to create one, so you will have less work to do later when you bring more servers online. We’ll talk about setting up a DHCP server and IP address scheme in Chapter 11, Setting Up Network Services, but for now, I’ll give you a few quick tips. Your DHCP server will typically have a range of IP addresses that will be automatically assigned to any host that requests an assignment. When setting up a static IP on a server, you’ll want to make sure that the IP address that you choose is outside of the range that your DHCP server assigns so you don’t end up with a duplicate IP on your network. For example, if your DHCP server assigns IPs ranging from 10.10.10.100 through 10.10.10.150, you’ll want to use an IP address not included within that range for your servers.

There are two ways of assigning a fixed address to a network host, including your servers. The first is by using a static IP assignment, as I’ve already mentioned. With that method, you’ll arbitrarily grab an IP address that’s not being used by anything, and then configure your Ubuntu Server to use that address. In that case, your server is never requesting an IP address from your network’s DHCP server. It simply uses whatever you assign it. This is the method I’ll be going over in this section.

The other way of assigning a fixed address to a server is by using a static lease. This is also known as a DHCP reservation, but I prefer to use the former term. With this method, you configure your DHCP server to assign a specific IP address to specific hosts. In other words, your server will request an IP address from your local DHCP server, and your DHCP server is instructed to give a specific address to your server each time it asks for one. This is the method I prefer, because it makes your DHCP server the single source of truth for the IP addresses that are assigned on your network. I’ll go over it in more detail in Chapter 11, Setting Up Network Services.

However, you don’t always have a choice. As a Linux administrator, you may or may not be in charge of the DHCP server. It’s often the case at many organizations that administrators that manage servers are not the same individuals that also manage the network.

If you don’t have authority over the design of the network, you’d use an IP address that would be provided to you by your network administrator, and then you’ll proceed to configure your Ubuntu Server to use it by applying the parameters they give you.

Within the last several years, the method that we utilize to customize the IP address of our servers has changed from the way it was handled in the past. Since Ubuntu 17.10, which was released back in 2017, configuring your IP address settings is now done via Netplan. In the past, we would configure networking via NetworkManager, but that’s installed only by default in Ubuntu Desktop. With Netplan, configuration files for your network interfaces now reside in the /etc/netplan directory, in YAML format. Explaining the YAML format itself is beyond the scope of this book, but the syntax is very easy to follow so you don’t really need to thoroughly understand this format in order to configure your network interfaces. If you list the contents of the /etc/netplan directory, you should see at least one file there, often named 00-installer-config.yaml or 50-cloud-init.yaml. It’s possible the file could be saved with a different name, so check the contents of the /etc/netplan directory to see what the file is named on your end. On one of my servers, I see the following contents in the /etc/netplan/00-installer-config.yaml file:

# This is the network config written by 'subiquity'
network:
ethernets:
enp0s3:
dhcp4: true
version: 2

We can already glean some obvious information from this default file. First, the comment at the beginning mentions subiquity, which is the official name of the Ubuntu Server installer, used when you install the distribution from boot media created from the ISO file.

More importantly, we can see that this particular server is configured to utilize DHCP in order to grab an IP address, which we can tell from the following line:

dhcp4: true

We can also tell that this configuration file pertains to interface enp0s3. Putting it all together, this file is telling us that interface enp0s3 is configured to automatically obtain an IP address via DHCP. If we’d like to convert this configuration to a static IP address instead, we should first back up the file:

sudo cp /etc/netplan/00-installer-config.yaml /etc/netplan/00-installer-config.yaml.bak

This way, if we make a mistake, we can easily restore the original file by renaming the backup file to the original name. This is a good practice to get into, regardless of the file we’re editing. Being able to restore a previous configuration is a best practice for just about any change we might be making. The first change we need to make is to remove the following line (or just change it to false):

dhcp4: true

Essentially, to set up a static IP we will replace that line with the details specific to our configuration. Here’s an example of the file, configured for a static IP address:

# This is the network config written by 'subiquity'
network:
ethernets:
enp0s3:
addresses: [192.168.100.50/24]
gateway4: 192.168.100.1
nameservers:
addresses: [192.168.100.1, 192.168.100.2]
version: 2

In the example, I’ve bolded four lines, which were added in place of the dhcp4: true line. First, we set the actual IP address:

addresses: [192.168.100.50/24]

There, I’ve used an example IP address of 192.168.100.50/24. On your end, you would make sure that the IP address you choose is within the scope of the network you’d like your server to be a part of. As I mentioned earlier, the IP address you choose should not be within the DHCP scope that automatically assigned IP addresses are chosen from. The preceding IP address would be fine if the example scope of the DHCP server on your network ranged from 192.168.100.100 to 192.168.100.150. The IP chosen here of 192.168.100.50 is outside of that, so we don’t have to worry about another device being assigned that address.

We also include /24 to declare that the IP address is part of a 24-bit subnet, which is fairly standard unless your network administrator has set up a larger scope. An /24 network is the same as a Class C network, in case that’s more familiar to you. This also takes care of the subnet mask, which we don’t need here since /24 implies the same subnet mask as 255.255.255.0 (if you’re more familiar with the classful style, which shows the subnet mask in the same format as an IP address). We will discuss subnets in Chapter 11, Setting Up Network Services; however, a full walk-through of subnetting and the TCP/IP protocol would be more fitting for a book dedicated to networking concepts, so we won’t go anymore into detail than necessary.

Moving on, we also set up the gateway:

gateway4: 192.168.100.1

When it comes to networking, the gateway refers to the device your outbound connections are routed through, which will often be a router or firewall, depending on how your network is set up. This value will need to match the actual default gateway address on your network, which is quite often the same as the IP address with the last portion being .1. If in doubt, you can check the IP address assignment of another device on the same network you’re joining the Ubuntu server to, which would be the same.

The last section allows us to configure the DNS server that our server will use to look up external domain names:

nameservers:
addresses: [192.168.100.1, 192.168.100.2]

The example configuration is just that, an example—all the values must match whatever is appropriate for your network. Often, the DNS server IP address will be the same as the gateway address, but that’s not always true. Sometimes a network administrator will have a custom IP scheme for DNS servers. I also added a secondary DNS server in the example, 192.168.100.2, but you can remove the second IP address if that’s not necessary.

Once you’ve ensured that the values in the file are appropriate, we’ll need to apply and test these changes:

  • If you are using a virtual machine, you may want to make the changes from the virtual machine console
  • If you’re updating a physical machine, you may want to have a display and keyboard attached
  • Although we discuss OpenSSH later in this chapter, if you’re already aware of how to connect to a server via OpenSSH, you probably won’t want to change network configuration over OpenSSH, since as soon as you activate these changes your connection will drop

Just take your time and double-check everything to ensure you didn’t mistype anything, so you won’t find yourself with a server that cannot connect.

To actually make these changes take effect, you can run the following command:

sudo netplan apply

When you run the previous command, it will let you know if there are any errors in the file or apply the changes if not. The new IP address will take effect immediately.

In the case of utilizing remote connections such as OpenSSH while configuring networking, you can work around the issue of being disconnected and having networking not restart properly by using tmux, a popular terminal multiplexer. A full run-through of tmux is beyond the scope of this book, but it is helpful to us in this scenario because it keeps commands running in the background, even if our connection to the server gets dropped. To use it, first install the package:

sudo apt install tmux

Then, activate tmux by simply typing tmux in your shell prompt.

From this point on, tmux is now responsible for your session. If you run a command within tmux, it will continue to run, regardless of whether or not you’re attached to it. To see this in action, first enter tmux and then execute the top command. While top is running, disconnect from tmux. To do that, press Ctrl + b on your keyboard, release, and then press d. You’ll exit tmux, but if you enter the tmux a command to reattach your session, you’ll see that top was still running even though you disconnected. Following this same logic, you can activate tmux prior to executing the sudo netplan apply command.

Most likely, you’ll still get dropped from your shell, since the process of activating network changes brings the network interface down and then back up again, but with tmux the command will complete in the background. You can then reconnect to the server and run tmux a to rejoin your tmux session.

The tmux utility is extremely powerful, and when harnessed can really enhance your workflow when using the Linux shell. Although a complete tutorial is outside the scope of this book, I highly recommend looking into using it, which you can do here: If you need some guidance with it, check out the video guide on LearnLinuxTV that will be linked at the end of this chapter.

With networking restarted, you should be able to immediately reconnect to the server and see that the new IP assignment has taken place by executing ip a. If, for some reason, you cannot reconnect to the server, you may have made a mistake while editing the configuration file for Netplan. Double-check that file for any errors. But as long as you’ve followed along and typed in the proper values for your interface and network, you should be up and running with a static IP assignment.

Now, we have an actual network—we’ve named our server(s) and configured our network interfaces. We should also understand how name resolution works in Ubuntu, which is the process in which servers are able to find other servers by their name.

In Chapter 11, Setting Up Network Services, we’ll have a discussion on setting up a DNS server for local name resolution for your network. But before we get to that, it’s also important to understand how Linux resolves names in the first place. Most of you are probably aware of the concept of a Domain Name System (DNS), which matches human-understandable domain names to IP addresses. This makes browsing your network (as well as the internet) much easier. However, a DNS isn’t always the first thing that your Linux server will use when resolving names.

For more information on the order in which Ubuntu Server checks resources to resolve names, feel free to take a look at the /etc/nsswitch.conf file. There’s a line in this file that begins with the word hosts. Here is the output of the relevant line from the file on my server:

hosts: files mdns4_minimal [NOTFOUND=return] dns mymachines

In this case, the server is configured to first check local files, and then the DNS if the request isn’t found. This is the default order, and I see little reason to make any changes here (but you certainly can). Specifically, the file the server will check is /etc/hosts. If it doesn’t find what it needs there, it will move on to the DNS (basically, it will check the DNS server we configured earlier with Netplan, or the default server provided by DHCP).

There are many other lines in the nsswitch.conf file, but I won’t discuss them here as they are out of scope of the topic of this section.

The /etc/hosts file, which we briefly discussed while working with our hostname, tells our server how to resolve itself (it has a hostname mapping to the localhost IP of 127.0.0.1), but you are also able to create additional names to IP mappings here as well.

For example, if I had a server (myserver.mydomain.org) at IP 10.10.96.124, I could add the following line to /etc/hosts to make my machine resolve the server to that IP each time, without it needing to consult a DNS server at all:

10.10.96.124 myserver.mydomain.org

In practice though, this is usually not a very convenient method by which to configure name resolution. Don’t get me wrong, you can certainly list your servers in this file along with their IP addresses, and your server would be able to resolve those names just fine. The problem stems from the fact that this method is difficult to maintain. The name mappings apply only to the server you’ve made the /etc/hosts changes on; other servers wouldn’t benefit since they would only check their own /etc/hosts file. You could add a list of servers to the hosts file on each of your servers, but that would be a pain to manage. This is the main reason why having a central DNS server is a benefit to any network, especially for resolving the names of local resources.

However, the /etc/hosts file is used every now and again in the enterprise as a quick one-off workaround, and you’ll probably eventually end up needing to use this method for one reason or another. One very common reason to use such a manual method of resolving names is in the case where you’re testing a replacement server. In that case, you can configure the /etc/hosts file to have the same name as the original server, but with the IP address of the new server. Once you finish testing and confirm that the new server is operating properly, you can then replace the network-wide DNS name to point to the new IP address.

On legacy Ubuntu servers, the /etc/resolv.conf file included the IP addresses for DNS servers the system would use to resolve names. If you wanted to override the DNS servers for your server, you would alter that file. Although this file still exists in Ubuntu 22.04, it only exists to redirect lookups to systemd-resolved, which is a systemd unit that runs in the background and applies DNS settings based on what the system receives via DHCP or what you may have configured in Netplan. For the sake of completeness though, here is a brief overview of the syntax of this file in older releases, in case you end up working on such a server. An example of this file is as follows:

nameserver 10.10.96.1
nameserver 10.10.96.2

In this example, the /etc/resolv.conf output is utilizing servers 10.10.96.1 and 10.10.96.2. Therefore, the server will first check /etc/hosts for a match of the resource you’re looking up, and if it doesn’t find it, it will then check /etc/resolv.conf in order to find out which server to check next. In this case, the server will check 10.10.96.1.

The /etc/resolv.conf file on legacy servers is typically not one that you’d make actual changes to, since it’s automatically generated by NetworkManager. NetworkManager is a service that helps you manage your network interfaces; however, it’s not used anymore with Ubuntu Server for a handful of releases now. Even though you don’t typically manually edit the /etc/resolv.conf file, it may be worth looking at on legacy servers to see which DNS servers were assigned, in case you’re troubleshooting some sort of networking issue.

Nowadays, modern Ubuntu servers utilize systemd-resolved to handle name resolution. If you’d like to see which DNS servers were assigned on a newer Ubuntu Server installation, you can simply look at the configuration file for Netplan that we worked through earlier in the case of a static IP assignment, but if DHCP is being used, the resolvectl command will let you know what DNS nameservers your server is currently pointing to. This will provide an output similar to that shown in the following screenshot:

Figure 10.5: Viewing a server’s current DNS assignment

In a typical enterprise Linux network, you’ll set up a local DNS server to resolve your internal resources, which will then forward requests to a public DNS server in case you’re attempting to reach something that’s not internal. We’ll get to that in Chapter 11, Setting Up Network Services, but you should now understand how the name resolution process works on your Ubuntu Server.

As Linux administrators, we will likely manage a large number of servers, and often the server we’re managing may not even be in the same physical location as us. OpenSSH is a powerful tool for remote management, and it’s what we’ll explore next.

OpenSSH is quite possibly the most useful tool in existence for managing Linux servers. Of all the countless utilities available, this is the one I recommend that everyone starts practicing as soon as they can. Technically, I could probably better fit a section for setting up OpenSSH in Chapter 11, Setting Up Network Services, but this utility is very handy, and we should start using it as soon as possible.

OpenSSH allows you to open a command shell on other Linux servers, enabling you to run commands as if you were there in front of the server. For Linux administrators like us, this is extremely convenient. We could be tasked with managing dozens, hundreds, or even thousands of servers.

With OpenSSH, we can manage our entire server architecture without even getting out of our chairs. In this section, I’ll give you some information on OpenSSH and how to install it, and then I’ll finish up the section with a few examples of actually using it.

OpenSSH consists of two components, the server daemon that runs in the background that accepts SSH connections, and the client that runs on a laptop, workstation, or another server that gives you the ability to connect to an SSH server and run commands. All operating systems nowadays give you access to an OpenSSH client that you can use to make the connection to the server, so that requirement is probably already met. When it comes to Linux, most distributions give you the OpenSSH client already. You can verify that by running which ssh at your shell prompt. If you have the client installed, your output should read /usr/bin/ssh.

If, for some reason, you don’t have this package installed and you’ve received no output from the previous command (which would be rare), you can install the OpenSSH client with the following command:

sudo apt install openssh-client

Depending on the choices you’ve made during installation, your Ubuntu Server likely has the OpenSSH server installed already. If you don’t remember whether or not you opted to have this included during our initial installation, you can run the which sshd command at your shell prompt and you should see the output of /usr/sbin/sshd. You can also execute systemctl status ssh as well, and if the server component is present and running, then your server is ready to accept SSH connections:

Text Description automatically generated

Figure 10.6: Verifying that the OpenSSH service is running on a server

In the case that you don’t have the OpenSSH server component installed on your server, you can install it with the following command:

sudo apt install openssh-server

With great power comes great responsibility, though. As great as OpenSSH is, any service that listens for connections has the potential of being abused. An outside intruder finding a weakness or exploit that allows them to take control over your server is a really bad situation. Therefore, like any service that runs on your server, you should only have it running if you need to use it. Since OpenSSH is incredibly helpful (and it’s the standard method of remote management) it’s very hard to not use it.

There are many methods you can utilize to secure such a service and help protect it. One method is covered in the next section, and we’ll talk about security pertaining to OpenSSH again before the book comes to a close. Specifically, in Chapter 21, Securing Your Server, I will walk you through various configuration changes you can make to help minimize the threat of miscreants breaking into your server from the outside and wreaking havoc.

Securing OpenSSH is actually not hard at all, and would probably only take a few minutes of your time. Therefore, feel free to make a detour to that chapter to read the section there that talks about securing OpenSSH, and then come back here when you’re done. For now, make sure that you have secure, randomly generated passwords on the server at the very least. If OpenSSH is reachable via the public internet, and any of your users have weak passwords, it definitely won’t be a fun situation.

With all of that out of the way, we can get started with actually using OpenSSH.

After you’ve installed the openssh-server package on your target machine (the one you want to control remotely), you’ll need to start it if it hasn’t been already. By default, Ubuntu’s openssh-server package is automatically configured to start and become enabled once installed. Just as we’ve done earlier, you can verify that the required service is running with the following command:

systemctl status ssh

If OpenSSH is running as a daemon on your server, you should see output that tells you that it’s active (running). If not, you can start it with the following command:

sudo systemctl start ssh

If the output of the systemctl status ssh command shows that the daemon is disabled (meaning it doesn’t start up automatically when the server boots), you can enable it with the following command:

sudo systemctl enable ssh

With the OpenSSH server started and running, your server should now be listening for connections. To verify this, use the following command to list listening ports, restricting the output to SSH:

sudo ss -tunlp |grep ssh

The ss command allows us to view a list of processes running on our server that are listening for connections. It will also display which port a process is listening on.

We’ll explore this command in more detail in Chapter 21, Securing Your Server. But for now, this command should produce an output similar to the following:

Graphical user interface, text Description automatically generated

Figure 10.7: Checking if the required port for SSH is listening

If, for some reason, your server doesn’t show that it has an SSH server listening, double-check that you’ve started the daemon. By default, the SSH server listens for connections on port 22. This can be changed by modifying the port declaration in the /etc/ssh/sshd_config file, but that’s a story for a later chapter. While I won’t be going over the editing of this file just yet, just take note that it’s the default configuration file for the daemon. OpenSSH reads this file for configuration values each time it’s started or restarted.

To connect to a server using SSH, simply execute the ssh command followed by the name or IP address of the server you’d like to connect to:

ssh 192.168.1.120

By default, the ssh command will use the username you’re currently logged in with for the connection. If you’d like to use a different username, specify it with the ssh command by including your username followed by the @ symbol just before the IP address or hostname:

Unless you tell it otherwise, the ssh command assumes that your target is listening on port 22. If it isn’t, you can give the command a different port with the -p option followed by a port number:

ssh -p 2242 [email protected]

Once you’re connected to the target machine, you’ll be able to run shell commands and administer the system as if you were right in front of it. You’ll have all the same permissions as the user you’ve logged in with, and you’ll also be able to use sudo to run administrative commands if you normally have access to do so on that server.

Basically, anything you’re able to do if you were standing right in front of the server, you’ll be able to do via SSH. When you’re finished with your session, simply type exit at the shell prompt, or press Ctrl + d on your keyboard.

When you exit an OpenSSH connection, any processes you may have had running in the background will be killed. Be sure you resume any background processes you may have running and finish working with them before you exit your connection. We took a look at how to run processes in the background back in Chapter 7, Controlling and Monitoring Processes.

As you can see, OpenSSH is a miraculous tool that will benefit you by allowing you to remotely manage your servers from anywhere you allow SSH access from. Make sure to read the relevant section in Chapter 11, Setting Up Network Services, with regard to securing it, though. In the next section, we’ll discuss SSH key management, which brings the benefit of convenience, but also allows you to increase security as well.

When you connect to a host via SSH, you’ll be asked for your password, and after you authenticate you’ll be connected. Instead of using your password, though, you can authenticate via public key authentication instead. The core benefit to this method is added security, as your system password is never transmitted during the process of connecting to the server. When you create an SSH key pair, you are generating two files, a public key and a private key. These two files are mathematically linked, so if you connect to a server that has your public key, it will know it’s you because you (and only you) have the private key that matches it. This method is far more secure than password authentication, and I highly recommend that you use it. To get the most out of the security benefit of authentication via keys, you can actually disable password-based authentication on your server so that your SSH key is your only way in. By disabling password-based authentication and using only keys, you’re increasing your server’s security by a sizeable margin. We’ll go over that in Chapter 21, Securing Your Server.

To get started, you’ll first need to generate your key. To do so, on your workstation or laptop (the device you’re using to connect to the server), use the ssh-keygen command as your normal user account. The following screenshot shows what this process generally looks like:

Text Description automatically generated

Figure 10.8: Generating an SSH key pair

First, you’ll be asked for the directory in which to save your key files, defaulting to /home/<user>/.ssh. You’ll next be asked for a passphrase, which is optional. Although it does add an additional step to authenticating via keys, I recommend that you give it a passphrase (which should be different than your system password) since it greatly enhances security (the key would be unusable without the passphrase, if you gave it one). You can press Enter for the passphrase without entering one if you do not want this.

What this command does is create a directory named .ssh in your home directory, if it doesn’t already exist. Inside that directory, it will create two files, id_rsa and id_rsa.pub. The id_rsa file is your private key. It should never leave your machine, be given to another user, or be stored on any external media. If your private key leaks out, your keys can no longer be trusted. By default, the private key is owned by the user that created it, with rw permissions given only to its owner.

The public key, on the other hand, can leave your computer and doesn’t need to be secured as much. Its permissions are more lenient, being readable by everyone and writeable by the owner. You can see this yourself by executing ls -l /home/<user>/.ssh:

A screenshot of a computer Description automatically generated with medium confidence

Figure 10.9: Listing the contents of the.ssh directory, showing the permissions of the newly created keys

The public key is the key that actually gets copied to other servers to facilitate your being able to log in via such a key pair. When you log in to a server that has your key, it checks that it’s a mathematical match to your private key, and if it is, it will let you log in. You’ll also be asked for your passphrase, if you chose to set one when you first created it. But before we can actually use our key, we need to copy it over to the server we intend to connect to.

Copying your public key to a remote server

Section titled “Copying your public key to a remote server”

To actually transmit your public key to a target server, we can use the ssh-copy-id command, as I’m doing in the following example command:

ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.1.150

With that command, replace the IP address with the actual IP address, or with the hostname of the target server. You’ll be asked to log in via your password first, and then your key will be copied over. From that point on, you’ll log in via your key, falling back to being asked for your password if, for some reason, your key relationship is broken. Here’s an example of what this process looks like, if I were to work through the process of copying my key to a server named myserver.mycompany.org:

Text Description automatically generated

Figure 10.10: Using the ssh-copy-id command to copy a public key to a server

So, what exactly did the ssh-copy-id command do? Where is your public key copied to, exactly? What happens with this command is that on the target server, a .ssh directory is created in your home directory on the target server if it didn’t already exist. Inside that directory, a file named authorized_keys is created if it wasn’t already present. The contents of ~/.ssh/id_rsa.pub on your machine are copied into the ~/.ssh/authorized_keys file on the target server. With each additional key you add (for example, you connect to that server from multiple machines), the key is added to the end of the authorized_keys file, one per line.

Using the ssh-copy-id command is merely a matter of convenience; there’s nothing stopping you from copying the contents of your id_rsa.pub file and manually pasting it into the authorized_keys file of the target server. That method will actually work just fine as well.

When you connect to a server that you have set up a key relationship with by adding your public key, SSH checks the contents of the ~/.ssh/authorized_keys file on that server, looking for a key that mathematically matches the private key (~/.ssh/id_rsa) on your machine. If the two keys are an appropriate match, you are allowed access. If you set up a passphrase, you’ll be asked to enter it in order to open your public key.

If you decided not to create a passphrase with your key, you’re essentially setting up authentication without a password, meaning you won’t be asked to enter anything when authenticating.

When we created our SSH key earlier, it was mentioned that having a passphrase is optional but is a good idea. Using passphrases with OpenSSH key pairs boosts their security. If an OpenSSH key falls into the wrong hands, it will be useless if the person attempting to utilize it doesn’t know the passphrase. However, we lose a bit of convenience because we need to enter the passphrase for a key each time we want to use it. An OpenSSH key without a passphrase will allow us to connect to a server and be logged in without entering anything at all. With an SSH agent, you can actually cache your passphrase the first time you use it, so you won’t be asked for it with every connection. This essentially allows you to benefit from the added security of a passphrase, and still maintain at least some convenience. Best of all, if your laptop or desktop is able to utilize the OpenSSH client for connecting to remote systems, you should have an SSH agent on your system already. If we’re using a flavor of Linux or macOS on our workstation or laptop, for example, we will have the ssh-agent command available to us.

The ssh-agent is used by starting it in the background in our terminal. We can then “unlock” our keys with our passphrase, and then the unlocked key will be stored in memory and will be automatically used when we attempt to connect to a server we’ve copied our public key to. To start it, enter the following command as your normal user account on the machine you’re starting your connections from (that is, your workstation):

eval $(ssh-agent)

This command will start an SSH agent, which will continue to run in the background of your shell. But it’s not adding any value to us yet—so we will need to add an SSH key to the now-running agent. The ssh-add command allows us to add an SSH key to our running ssh-agent. To do so, we can give the ssh-add command the path to our public key as an argument:

ssh-add ~/.ssh/id_rsa

At this point, you’ll be asked for your passphrase. As long as you enter it properly, your key will remain open and you won’t need to enter it again for future connections, until you close that shell or log out. Now that you have the ssh-agent running in the background with your unlocked key, utilizing a key with a passphrase becomes much easier and you’ll end up typing a lot less.

At some point, you may want to change the passphrase associated with a key. If you’d like to do that, you can use the -p argument with the ssh-keygen command. That same argument can also be used if you didn’t choose to add a passphrase when you initially created the key. That’s all there is to it. The command you’d enter to add or change a passphrase is as simple as the following:

ssh-keygen -p

Once you enter that command, press Enter to accept the default file (id_rsa) unless the key you want to alter is under a different name, in which case you can type the path to, and the name of, that key. Then, you’ll be asked for your current passphrase (leave it blank if you don’t have one yet) followed by your new passphrase twice. The process looks like this:

A screenshot of a computer Description automatically generated with medium confidence

Figure 10.11: Changing an SSH passphrase

These concepts may take a bit of practice if you’ve never used SSH before. The best way to practice is to set up multiple Ubuntu Server installations (perhaps several virtual machines), and practice using SSH to connect to them, as well as deploying your key to each machine via the ssh-copy-id command. It’s actually quite easy once you get the hang of it.

Simplifying SSH connections with a config file

Section titled “Simplifying SSH connections with a config file”

Before we leave the topic of OpenSSH, there’s another trick that has the benefit of convenience, and that is the creation of a local configuration file for SSH. This file must be stored in the .ssh directory of your home directory, and be named config. The full path for this file in my case looks like this:

/home/jay/.ssh/config

This file doesn’t exist by default, but if it’s found, SSH will parse it whenever you use the client and you’ll be able to benefit from it. Go ahead and open this file in your text editor, such as nano:

nano /home/your_username/.ssh/config

This config file allows you to type configuration for servers that you connect to often, which can simplify the ssh command automatically. The following are example contents from such a file that will help me illustrate what it does:

host myserver
Hostname 192.168.1.23
Port 22
User jdoe
Host nagios
Hostname nagios.mynetwork.org
Port 2222
User nagiosuser

In the example contents, I have two hosts outlined, myserver and nagios. For each, I’ve identified a way to reach it by name or IP address (the Hostname line), as well as the Port and User account to use for the connection. If I use ssh to connect to either Host by the name I outlined in this file, it will use the values I have stored there, for example:

ssh nagios

That command is a lot shorter than if I set all the options manually. Considering I have a config file for SSH, that command is essentially the same as if I identified the connection details manually, which would’ve been the following:

ssh -p 2222 [email protected]

I’m sure you can see how much simpler it is to type the first command than the second. With the config file for SSH, I can have some of those details automatically applied. Since I’ve outlined that my nagios server is located at nagios.mynetwork.org, its SSH user is nagiosuser, and it’s listening on port 2222, it will automatically use those values even though I only typed ssh nagios. Furthermore, you can also override this entry as well. If you provide a different username when you use the ssh command, it will use that instead of what you have written in the config file.

In the first example (for the myserver server), I’m providing an IP address for the connection, rather than a hostname. This is useful in a situation where you may not have a DNS entry for your target server. With this example, I don’t have to remember that the IP address for myserver is 192.168.1.23. I simply execute ssh myserver and it’s taken care of for me.

The names of each server within the config file are arbitrary and don’t have to match the target server’s hostname. I could’ve named the first server potato and it would still have routed me to 192.168.1.23, so I can create any sort of named shortcut I want, whatever I find is most convenient for me and easiest to remember. As you can see, maintaining a config file in your home directory containing your most commonly used SSH connections will certainly help keep you organized and allow you to connect more easily.

In this chapter, we worked through several examples of connecting to other networks. We started off by configuring our hostname, managing network interfaces, assigning static IP addresses, as well as looking at how name resolution works in Linux. A decent portion of this chapter was dedicated to topics regarding OpenSSH, which is an extremely useful utility that allows you to remotely manage your servers. We’ll revisit OpenSSH in Chapter 21, Securing Your Server, with a look at boosting its security. Overall, we’ve only begun to scratch the surface of this tool. Entire books have been written about SSH, but the examples in this chapter should be enough to make you productive with it. The name of the game is to practice, practice, practice!

In the next chapter, we’ll talk about managing software packages. We’ll work through adding and removing them, adding additional repositories, and more!