How To Zip Multiple Files on Linux

ZIP is by far one of the most popular archive file format among system administrators.

Used in order to save space on Linux filesystems, it can be used in order to zip multiple files on Linux easily.

In this tutorial, we are going to see how can easily zip multiple files on Linux using the zip command.

Prerequisites

In order to zip multiple files on Linux, you need to have zip installed.

If the zip command is not found on your system, make sure to install it using APT or YUM

$ sudo apt-get install zip

$ sudo yum install zip

Zip Multiple Files on Linux

In order to zip multiple files using the zip command, you can simply append all your filenames.

$ zip archive.zip file1 file2 file3

adding: file1 (stored 0%)
adding: file2 (stored 0%)
adding: file3 (stored 0%)

Alternatively, you can use a wildcard if you are able to group your files by extension.

$ zip archive.zip *.txt

adding: file.txt (stored 0%)
adding: license.txt (stored 0%)

$ zip archive.zip *.iso

adding: debian-10.iso (stored 0%)
adding: centos-8.iso (stored 0%)

Zip Multiple Directories on Linux

Similarly, you can zip multiple directories by simply appending the directory names to your command.

$ zip archive.zip directory1 directory2

adding: directory1/ (stored 0%)
adding: directory2/ (stored 0%)

Conclusion

In this tutorial, you learnt how you can easily zip multiple files on Linux using the zip command.

You also learnt that wildcards can be used and that you can zip multiple directories similarly.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to have a look.

How To Add Route on Linux

As a network engineer, you probably spend a lot of time thinking and planning your network infrastructure.

You plan how computers will be linked, physically using specific cables but also logically using routing tables.

When your network plan is built, you will have to implement every single link that you theorized on paper.

In some cases, if you are using Linux computers, you may have to add some routes in order to link it to other networks in your company.

Adding routes on Linux is extremely simple and costless : you can use the Network Manager daemon (if you are running a recent distribution) or the ifconfig one.

In this tutorial, you will learn how you can easily add new routes on a Linux machine in order to link it to your physical network.

Prerequisites

In order to add routes on your Linux machine, you need to have administrator rights.

In order to verify it, you can run the “sudo” command followed by the “-v” option (in order to update your cached credentials).

$ sudo -v

If you don’t have sudo rights, you can have a look at our dedicated articles on getting administrator rights on Ubuntu or CentOS.

Add route on Linux using ip

The easiest way to add a route on Linux is to use the “ip route add” command followed by the network address to be reached and the gateway to be used for this route.

$ ip route add <network_ip>/<cidr> via <gateway_ip>

# Example
$ ip route add 10.0.3.0/24 via 10.0.3.1

By default, if you don’t specify any network device, your first network card, your local loopback excluded, will be selected.

However, if you want to have a specific device, you can add it to the end of the command.

$ ip route add <network_ip>/<cidr> via <gateway_ip> dev <network_card_name>

As an example, let’s say that you want two LAN networks to be able to communicate with each other.

The network topology has three different Linux machines :

  • One Ubuntu computer that has the 10.0.2.2/24 IP address;
  • Another Ubuntu computer that has the 10.0.3.2/24 IP address;
  • One RHEL 8 computer that will act as a simple router for our two networks.

simple-lan-network

The first computer cannot ping the other computer, they are not in the same subnet : 10.0.2.0 for the first computer network and 10.0.3.0 for the second one network.
ping-unreachable

As the two hosts are not part of the same subnet, the ping command goes to the default gateway.

In order to see the routes already defined on your machine, use the “ip route” command with no arguments. You can also use the “ip r” command as an abbreviation.

$ ip r

ip-routes

This is the routing table of your Linux computer : every computer has one. A router happens to manage many more routes than that but it is essentially using the same routing syntax.

So how does one read that?

In order to understand this output, you have to read from top to bottom :

  • By default, network calls will be forwarded to the local default gateway which is 10.0.2.1
  • UNLESS your call is for the 10.0.2.0/24 network. In this case, it will simply be sent on your local network via your default physical link (physically a CAT network cable)
  • UNLESS your call is for the 169.254.0.0/16 network. In this case, it will also be sent on your local network using your default physical link.
Note : did you know? The 169.254.0.0/16 address is called APIPA (for Automatic IP Address Addressing). It is the default IP used by a system that failed to reach a DHCP server on the network.

In our case, in order to call the 10.0.3.2/24 IP address, the call will be forwarded to our 10.0.2.1 router.

However, is our router able to forward calls addressed to the 10.0.3.0/24 network?

A simple “ip r” command on the router can give us a hint.

ip-route-router

As you can see, the router is only linked to the 10.0.2.0/24 network which is obviously an issue.

In order to add a route on our Linux router, we use the “ip route add” command.

$ sudo ip route add 10.0.3.0/24 via 10.0.3.1

ip-route-add

Now, if you were to ping your second computer on the first computer, you would be able to reach it.

ping-first-computer

Awesome, you have successfully added a route from one Linux computer to another!

Adding permanent route configuration on Ubuntu

On Ubuntu, there are three ways of adding a permanent route to your Linux machine :

  • You can add it to your Network Manager configuration file;
  • You can edit your Netplan YAML configuration file;
  • You can add your route to the “/etc/network/interfaces” file if you are using an old Ubuntu distribution.

Using Network Manager

To add a permanent route to the Network Manager, you have to navigate to the connection file located at “/etc/NetworkManager/system-connections”.

listing-network-manager-connections

Edit your “Wired connection” file and add a “route1” property in the IPv4 part of the network configuration.

route1-property-network

The route has to be defined as : the network IP address followed by the CIDR, next the default gateway and finally the next-hop.

In order for the changes to be applied, you can restart your network connection, and execute the “route -n” command in order to see your route.

$ sudo nmcli connection reload

adding-route-network-manager

Awesome, you have added a permanent route to your Linux server!

Using Netplan

Netplan is an Ubuntu exclusive but it can be quite useful if you want to configure your network using a simple YAML file.

To add a permanent route using Netplan, add the following section to your “/etc/netplan” configuration file.

$ sudo vi /etc/netplan/<configuration_file>.yaml

netplan-configuration

For the changes to be applied, you will have to execute the “netplan” command with the “apply” argument.

$ sudo netplan apply

netplan-permanent-route

Congratulations, you have configured your network using Netplan. If you want to read more about Netplan and its objectives, you can have a look at the dedicated documentation.

Using /etc/network/interfaces

To add a permanent route to a distribution using ifup and ifdown, edit the “/etc/network/interfaces” file and add the following section.

$ sudo vi /etc/network/interfaces

auto eth0
iface eth0 inet static
      address 10.0.2.2
      netmask 255.255.255.0
      up route add -net 10.0.3.0 netmask 255.255.0.0 gw 10.0.2.1

Adding permanent route configuration on RHEL

By adding the route in the previous section, there is a chance that your distribution created a file for the route to be persisted.

However, if it is not the case, you need to add it in order to keep your route when restarting your server.

On RHEL and CentOS distributions, you need to create a file named “route-<device>” in the “/etc/sysconfig/network-scripts” folder.

$ sudo vi /etc/sysconfig/network-scripts/route-enp0s3

persistent-routes-linux

Add route on Linux using nmcli

Another way of adding a route on Linux is to use the “nmcli” utility and add an IPV4 route using the “modify” command.

$ sudo nmcli connection modify <interface_name> +ipv4.routes "<network_ip> <gateway_ip>"
Note : need a complete article about the Network Manager? We have a complete article about configuring your network using Network Manager.

For example, using the infrastructure of the previous section, in order to add a route, we would execute the following command.

$ sudo nmcli connection modify enp0s3 +ipv4.routes "10.0.3.0/24 10.0.3.1"

As changes are not made live, you will need to reload your network connections from disk using the “nmcli reload” command.

$ sudo nmcli connection reload

add-route-linux-nmcli-1

Awesome! Now there is a route between your first and second network.

As a consequence, you will be able to ping your second computer from the first computer.

ping-first-network

Adding a route using the network graphical interface

If you are not into executing commands in the terminal, luckily for you, there is a way to add a route on Linux using a graphical interface.

Whether you are on Ubuntu, Debian or RHEL makes no difference as they all share the same network panel on GNOME.

At the top right corner of your screen, look for a small network icon and click on it.

wired-connection-panel

Click on “Wired Connected” and look for the “Wired Settings” panel under it.

wired-settings-rhel

When the panel opens, look for the “Wired” section and click on the small gear wheel right next to it.

network-gear-wheel

In the “Wired” panel, you will be presented with many different parameters : your current IPv4 address, your current MAC address, an optional IPv6 address and your link speed.

local-network-parameters

In the “IPv4” tab, you will be presented with your current IP configured (most likely two for your computer to act as a Linux router).

Right under it, you will see the “Routes” section. In there, you can specify the input of the previous sections.

add-route-graphical-interface

When you are done, click on the “Apply” blue button at the top right corner of the window.

In order for the changes to be applied, you will need to restart your network. You can achieve that by clicking on the “on/off” toggle in the “Wired” window of the network parameters.

restart-network-linux

Done!

You have successfully added a route on Linux using the graphical interface, your computers should now be able to talk to each other.

Troubleshooting Internet issues on Linux

In some cases, you may want to add a route on your Linux because you want to be able to reach websites outside of your local network, say 8.8.8.8 for example.

As an example, let’s say that you have a local router linked to “Internet” that resides at 192.168.178.1/24.

Inspecting your current routes is an easy way for you to guess why you are not able to reach Internet websites.

The thought process is quite simple :

  • Is the IP that I am trying to reach a part of my subnet or not?
  • If yes, I should be able to reach it without any routes, everything will be handled by the ARP protocol and Ethernet.
  • If not, I need to have a route from my computer to a router that is able to forward requests to Internet.

However, remember that routes are two-lane highways : you need to be able to reach an external IP, but the external IP needs to be able to reach back to you.

As a consequence, routes need to be correctly defined on your local network architecture. As a diagram is more useful that a thousand words, here is a way to understand it.

troubleshoot-internet-issues

Whenever you are troubleshooting Internet issues, you have to think with routes : do I have a route from my computer to the computer that I am trying to reach?

Are the computers or routers between me and the target configured to handle my calls?

Reaching a part of the network is great, but is this part of the network able to answer me back?

In our diagram detailed above, our router may receive an answer from Google, but it has to know what to do with the request. In your local home network, you don’t have to worry about it as most of the requests are forwarded using the NAT protocol (short for Network Address Translation Protocol).

Conclusion

In this tutorial, you learnt how you can easily add a new route on many different Linux distributions.

Right now, as for other topics, some tools co-exist on Linux making the network configuration a bit convoluted sometimes.

However, we listed most of the options that you may encounter. If we forgot about an option, make sure to leave a comment for us to know.

If you are interested in Linux System Administration, make sure to have a look at our dedicated section on the website.

How To List Disks on Linux

For the system administrator, checking that disks are working properly is a big concern.

In many cases, you will have to list all the disks available on your computer, with their sizes, in order to make sure that they don’t run out of space.

If they were to run out of space, you could essentially have your server down, preventing all your users from accessing it.

In this tutorial, we are going to see how you can easily list disks available on your Linux machine.

Prerequisites

For some of the commands used in this tutorial, you will need administrator rights in order to have the full output of the command.

In order to check that you have sudo rights, you can execute the “sudo” command with the “-l” option.

$ sudo -l

check-sudo-rights

If you see matching entries, it means that you are a privileged account on this machine.

However, if you are notified that you “can’t run sudo on this computer“, have a read at our dedicated tutorials for Ubuntu or CentOS (RHEL equivalent).

List Disks on Linux using lsblk

The easiest way to list disks on Linux is to use the “lsblk” command with no options. The “type” column will mention the “disk” as well as optional partitions and LVM available on it.

$ lsblk

List Disks on Linux using lsblk-command

Optionally, you can use the “-f” option for “filesystems“. This way, your disks will be listed as well as partitions and filesystems formatted on them.

$ lsblk -f

list-disks-lsblk-command

By executing the “lsblk” command, you are presented with multiple different columns :

  • Name : the name of the device. It is quite important for you to know that Linux devices have a specific prefix depending on the nature of the device. “sd” in this case refers to SCSI devices but it is also short for SATA connections as most drives use SATA nowadays;
  • Filesystem type : if your partition contains a filesystem, it should be listed in this column (xfs, swap or encrypted devices);
  • Label : in some cases, in order to avoid using a UUID, you can choose to have a label for your device;
  • UUID : a universal unique identifier. This identifier should be unique worldwide and uniquely identify your device;
  • Mountpoint : if your filesystem is mounted, you should be able to see the actual mountpoint.

Awesome, you successfully listed your disks on Linux using “lsblk”.

However, in some cases, you are interested in listing your disks with the actual hardware information linked to it.

If I want to remove a disk from my Linux machine, knowing the actual physical port or the vendor can be quite useful.

List Disks Information using lshw

In order to list disk information on Linux, you have to use the “lshw” with the “class” option specifying “disk”. Combining “lshw” with the “grep” command, you can retrieve specific information about a disk on your system.

$ sudo lshw -class disk

$ sudo lshw -class disk | grep <disk_name> -A 5 -B

lshw-command-linux-1

As you can see, by running the “lshw” with no grep filters, you are presented with all the disks available on your computer.

If you want to target a specific disk on your computer, you can “pipe” the command with “grep” in order to only list the disks that you want.

list-disks-using-lshw-1

As you can see, using this command, you have way more information about your disks : the description, the product and its vendor as well as the actual bus info (where it might be plugged on your mother board).

Using this information, you can unplug it and replace it with another one very easily.

Awesome, you know how to list your disk information using “lshw” now.

Alternatives to lsblk : fdisk or hwinfo

The “lsblk” command is not the only command that you can use in order to have a listing of your disks on Linux. There are two other commands : fdisk (that is often used for partitioning) and hwinfo.

First, if you use the “fdisk” command with the “-l” option, you will be presented with all the partitions available on your machine as well as disks.

$ sudo fdisk -l

fdisk-command

As you can see there, you have a very detailed description of your main disk. You can even verify the partitions available on it as well as the bootable flag for example.

However, “fdisk” is not the only way for you to list disks, you can also use the “hwinfo” command with the “–disk” option.

$ sudo hwinfo --disk

hwinfo-command-linux

Using the “hwinfo” command without any options is quite hard to read. Luckily for you, there is an option that you can use in order to restrict the output to the disk list.

In order to achieve that, you have to use the “–short” option.

$ sudo hwinfo --disk --short

hwinfo-disk

As you can see, the output is quite concise but it gives you a clear idea on disks available.

Finally, for advanced system administrators, you can have a look at the “/dev/disk” folder.

$ ls -l /dev/disk/

dev-disk-folder

In this folder, you can check the “by-id” folder if you are looking for disks or the “by-uuid” one if you are looking for partitions.

$ ls -l /dev/disk/by-id

dev-disk-by-id

List Disk Using Graphical Interface

To list disks on Linux using the graphical interface, you have to go to the “Activities” and look for a program called “Disks”.

activities-menu-linux

When in the “Activities” menu, you can type “Disks” and look for an output similar to the one depicted below.

disks-activity-linux

When clicking on “Disks”, you will be presented with the list of disks available on your Linux machine.

disks-window

As you can see, in the “Disks” window, you have the “hard disk” as well as “block devices” which are the LVM devices that you may have created during the distribution installation.

When clicking on a specific disk, you can see its disk size, the serial number as well as the partitions and the contents that may be stored on it.

Great! You now have the list of disks that are plugged on your computer.

Conclusion

In this tutorial, you learnt how you can easily list your disks on Linux using the “lsblk” command.

You have learnt that the same result can be achieved using many different commands : hwinfo, fdisk or lshw.

If you read this tutorial in order to learn how you can see your disk usage on Linux, you should read our tutorial on the subject.

If you are interested in Linux System Administration, we have a complete section dedicated to it, make sure to have a look.

How To Add a User to Sudoers On Debian 10 Buster

In today’s tutorial, we are going to see how you can add a user to sudoers on Debian distributions.

The sudo command allows authorized users to perform commands as another user, which is by default the root user.

There are two ways to add a user to sudoers : you can add this user to the sudo group or you can add this user to the sudoers file located at etc.

Here are the details of the two methods.

I – Adding an existing user to the sudo group

As a prerequisites, make sure that the sudo command is available by default. If it’s not the case, you can install it by running (with an account with admin rights)

$ apt-get update
$ apt-get install sudo

The first method is to add the user to the sudo group.

To do that, you are going to use the “usermod” command with the capital G flag (for groups)

$ sudo usermod -a -G sudo user

You can also use the gpasswd command to grand sudo rights.

$ sudo gpasswd -a bob sudo
Adding user to the group sudo

Make sure that the user belongs to the sudo group with the groups command.

$ su - user
(password for user)

$ groups
user sudo

You should now be able to perform a sudo request on Debian 10.

Depending on the configuration you chose during your Debian 10 installation process, you may or may not have access to a root account. If you chose a password for your root account, you will be able to connect to it. Otherwise, the default admin account is the one you created during the installation process.

The sudoers file is located at /etc/sudoers.

This file contains a set of rules that are applied to determine who has sudo rights on a system, which commands they can execute with sudo privileges, and if they should be prompted a password or not.

However, you should never modify the sudoers file with a text editor.

Saving a bad sudoers may leave you with the impossibility of getting sudo rights ever again.

Instead, you are going to use visudo, a tool designed to make sure you don’t do any mistakes.

$ sudo visudo

This is what you should see.

II – Adding an existing user to the sudoers file visudo

At the end of the file, add a new line for the user.

john       ALL=(ALL:ALL) ALL

II – Adding an existing user to the sudoers file sudoers-syntax

By default, the account password will be asked every five minutes to perform sudo operations.

However, if you want to remove this password verification, you can set the NOPASSWD option.

john       ALL=(ALL:ALL) NOPASSWD:ALL

If you want the password verification to be skipped for longer periods of time, you can overwrite the timestamp_timeout (in minutes) parameter in your sudoers file.

# /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path = /sbin:/bin:/usr/sbin:/usr/bin
Defaults        timestamp_timeout=30

III – Adding a group to the sudoers file

Via the visudo, you can add an entire group to the sudoers.

This might be handy if you have a group for system administrators for example. In this case, you simply have to add a user to the system administrators group for him/her to be granted sudo privileges.

To add a group to the sudoers file, simply add a percent symbol at the beginning of the file.

%sysadmins       ALL=(ALL:ALL) NOPASSWD:ALL

Make sure that your user is part of the designed group with the groups command.

$ su - user
$ groups
user sysadmins

You can test your new sudo rights by changing your password for example

$ sudo passwd

IV – Most Common Errors

  • user is not in the sudoers file. This incident will be reported.

IV – Most Common Errors not-in-sudoers

This is the standard error message you get when a user does not belong to the sudo group on Debian 10.

By adding this user to the sudoers file on Debian, this error message should not be raised anymore.

How To Add User To Sudoers On Ubuntu 20.04

This tutorial focuses on adding sudoers rights to a user on Ubuntu 20.04 Focal Fossa.

When managing an Ubuntu 20.04 server, it is actually quite important to know how to add sudoers to it.

The sudo command is a very popular command on Linux.

It allows unauthorized users to perform commands as another user, by default being the root user.

On Ubuntu 20.04, we will focus on three different ways to add a user as sudo : add it to the sudo group, to the sudoers file or using the graphical interface.

Here are the details of the three different methods.

Adding an existing user to the sudo group

On most distributions, it is very likely that the sudo command is available by default.

$ which sudo
Note : the “which” command can be used in order to verify the existence of the sudo command on your host.

Adding an existing user to the sudo group which-sudo

If you notice that this is not the case, you can install sudo by running the following commands.

$ apt-get update
$ apt-get install sudo

In order to add a user to sudoers, you have to use the “usermod” command and the capital G (for secondary groups).

$ sudo usermod -a -G sudo <user>

Adding an existing user to the sudo group usermod-sudo

In order to verify that your user was correctly added to the sudo group, you have to use the “groups” command.

If you see “sudo” as a secondary group for your user, congratulations, you successfully added your user to sudoers!

Adding a user to sudoers using gpasswd

A less popular, yet very powerful way to add a user to sudoers is to use the gpasswd command.

$ sudo gpasswd -a <user> sudo

Adding a user to sudoers using gpasswd

As a quick reminder, gpasswd is used in order to administer the “/etc/group” file on your filesystem.

Adding an existing user to the sudoers file

By default, on Ubuntu 20.04, the sudoers file is located at /etc/sudoers.

Adding an existing user to the sudoers file sudoers

This file contains a set of rules that are applied in order to determine who has sudo rights on your system.

Also, the sudoers file can define privileges such as the commands that can be executed with or without sudo, or if you should be prompted with a password.

By default, you should not modify the sudoers file by yourself (the same logic applies to cron jobs for example).

If you were to corrupt this file, you might would not be able to get sudo rights again.

Instead, you are going to use “visudo” : a tool designed to make sure that you don’t make any mistakes.

$ sudo visudo

sudo-visudo

At the end of the file, add a new line for the user.

john       ALL=(ALL:ALL) ALL

Adding an existing user to the sudoers file sudoers-syntax

By saving and exiting the file, the user “john” will be automatically added to the sudo group.

By default, the account password will be asked every five minutes in order to perform sudo operations.

If you want to remove the password verification, you can simply add the “NOPASSWD” option.

john       ALL=(ALL:ALL) NOPASSWD:ALL
Note : if you add a user to the sudoers file, it does not mean that the user will belong to the sudo group on the system. It will be authorized to perform sudo operations, but it won’t be listed if you use the “groups” command.

Tweaking password verification

If you want to tweak the password verification period, or if you want to increase the verification, you have to modify the “timestamp_timeout” parameter.

# /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path = /sbin:/bin:/usr/sbin:/usr/bin
Defaults        timestamp_timeout=30

In this case, the password will be asked every thirty minutes.

Adding a user to sudoers using the graphical interface

On recent Ubuntu distributions, it is possible to add a user to the sudo group very easily.

First, head over to the “Activities” tab located at the top left corner of your screen and type “Users“.

You should see a screen similar to this one.

Adding a user to sudoers using the graphical interface users

Next, you will have to unlock the panel by clicking on “Unlock”.

Adding a user to sudoers using the graphical interface unlock (1)

You will be asked for your password, note that the account has to be a privileged account in order to perform this operation.

Adding a user to sudoers using the graphical interface authentication-required

Now that the panel is unlocked, you can tick the “Administrator” radio button in order for your user to be part of the administrators!
Adding a user to sudoers using the graphical interface john-sudo
You can even verify that your user is part of the sudo group using the “groups” command.

$ groups john

groups-john

Congratulations, your user is now part of the sudo group!

Adding a group to the sudoers file

In the previous section, we added a user to the sudoers file, but what if you wanted to give those rights to an entire group?

To add a group to the sudoers file, add a “percent” symbol at the beginning of the line, just before the name of the group.

%sysadmins       ALL=(ALL:ALL) NOPASSWD:ALL

Next, make sure that you are part of the designed group and execute your command using “sudo”.

$ groups
user sysadmins

$ sudo passwd

Congratulations, you set “sudo” privileges to an entire group!

Conclusion

In this tutorial, you learnt how you can easily add a user to sudoers using three different methods : using the command-line, the visudo command or using the graphical interface.

If you are interested in Ubuntu 20.04, we wrote a guide on installing and enabling a SSH server.

Also, if you are interested in Linux System Administration, we have an entire section dedicated to it on the website, so make sure to check it out!

How To List Services on Linux

As a system administrator, you are probably dealing with a lot of services every day.

On Linux, services are used for many different purposes.

They may be used in order to start a SSH server on your machine or they can perform some operations on a specific hour or day.

Whether you are using a Debian based distribution or a RedHat one, querying services is very similar.

However, given the distribution you are using, and more specifically the initialization system (init or systemd), you may have to use different commands.

In this tutorial, you will learn how you can, given your system manager, list all services on your Linux machine.

Determine the system manager used

As you probably know, recent distributions use the Systemd system manager.

However, it has not always been the case : in the past, most distributions used the SysVinit system manager.

As a consequence, there are really two ways of managing your services on a Linux system.

Before learning the commands to list services, you have to know the system manager that you are currently using.

To determine your current system manager, the easiest way is to use the “pstree” command and to check the first process ever run on your system.

$ pstree | head -n 5

Determine the system manager used pstree

If you see “systemd“, it obviously means that you are currently using systemd. However, if you see “init“, it means that you are using SysVinit.

On Ubuntu 14.04, that is still using the old init system, your “pstree” may look like this.

Determine the system manager used pstree-init

List Services using systemctl

The easiest way to list services on Linux, when you are on a systemd system, is to use the “systemctl” command followed by “list-units”. You can specify the “–type=service” option in order to restrict the results to services only.

$ systemctl list-units --type=service

List Services using systemctl list-services-linux-systemd

By default, this command will show you only the services that are active or the services that have failed on your system. In the screenshot above, most of the services are active but the logrotate one (highlighted in red) is marked as failed.

Awesome, you learnt how you can easily list your services on a Linux server.

However, as you may have noticed, you did not have access to all services : what about inactive services? What about services that were not loaded by systemd on boot?

List All Services on Linux using list-units

In order to list all services, meaning active and inactive, you have to use the “systemctl list-units” command followed by the “–all” option.

Similarly, you can limit the results to services only by using the type filter.

$ systemctl list-units --type=service --all

List All Services on Linux using list-units list-inactive-services

As you can see, inactives services also listed which might be convenient if you just wrote your service and looking after it in the list.

In this case, only loaded services are listed. On boot, systemd loads unit files and it may choose not to load a specific service if it finds that it won’t be used by the system.

As a consequence, there is a real difference between “loaded” and “installed” services. “Installed” services mean that unit files can be found in the corresponding paths.

Disabling Root Login over SSH ssh-root-login

List Services By State

In some cases, you may only be interested in services that have failed. For that, you can specify the state that you are looking for as an option of the systemctl command.

$ systemctl list-units --state=<state>

$ systemctl list-units --state=<state1>,<state2>

Where “state” can be one of the following values : active, inactive, activating, deactivating, failed, not-found or dead.

For example, if we are only interested in “failed” services, we are going to run the following command

$ systemctl list-units --state=failed

List Services By State failed-service

List All Service Files using list-unit-files

Finally, if you are interested in “loaded“, “installed“, “disabled” as well as “enabled” service files, there is a another command that might be pretty handy.

In order to list all service files available, you have to use the “systemctl” command followed by “list-unit-files”. Optionally, you can specify the type by using the “–type=service” option.

$ systemctl list-unit-files --type=service

List All Service Files using list-unit-files list-installed-services

Alternatively, you can use the “grep” command in order to search for specific paths on your system that may contain service files.

$ ls -l /etc/systemd/system /usr/lib/systemd/service | egrep .service$

List All Service Files using list-unit-files list-files-using-grep

Congratulations, you learnt how you can list services if your system is using systemd!

List Services using service

The easiest way to list services on Linux, when you are on a SystemV init system, is to use the “service” command followed by “–status-all” option. This way, you will be presented with a complete list of services on your system.

$ service --status-all

List Services using service list-services-init-system

As you can see, each service is listed preceded by symbols under brackets. Those symbols mean :

  • + : means that the service is running;
  •  : means that the service is not running at all;
  • ? : means that Ubuntu was not able to tell if the service is running or not.

So why are some services to tell if they are running or not, and some are not able to?

It all comes down to the implementation of the init script. In some scripts, such as the udev script for example, you are able to see that the “status” command is implemented.

udev-status

This is not the case for the “dns-clean” script for example which is the reason why you have a question mark when you query this service.

List SysVinit Services in Folders

Another way of listing the current list of services is to use the “ls” command on the folders containing all scripts on a Linux system, namely “/etc/init.d”.

$ ls -l /etc/init.d/*

List SysVinit Services in Folders initd-folder

Conclusion

In this tutorial, you learnt how you can easily list services on a Linux system whether you are using systemd or SysVinit ones.

If you are interested in creating your own services, we recommend that you have a look at the following resources. They might be really useful in order to correctly achieve that.

  • Writing a startup script for init systems;
  • Starting services at boot using systemd;

If you are interested in Linux System Administration, we have a complete section on this subject on the website, so make sure to check it out.

How To Find Last Login on Linux

If you are working in a medium to big-sized company, it is quite likely that you are working with many other system administrators.

As you are performing your sysadmin tasks, some users may try to connect to your server in order to perform their daily tasks.

However, in some cases, you may find that something has changed on your server. As a consequence, you are wondering who performed the change.

Luckily for you, there are many ways to find who last logged in on your server.

In this tutorial, you will learn about the different useful commands that you can use in order to check the last logins on your computer.

Find Last Login using last

The easiest way to find the last login on your Linux computer is to execute the “last” command with no options. Using this command, you will be presented with all the last logins performed on the computer.

$ last

# To check the last ten login attempts, you can pipe it with "head"

$ last | head -n 10

Find Last Login using last-command

As you can see, by default, the output is truncated : the “devconnected” user is only displayed as “devconne” with simply using the last command.

If you find last logins using complete usernames and hostnames, you have to append the “-w” option or “–fullnames“.

$ last -w

$ last --fullnames

Find Last Login using last-complete-output

Last Command Columns

When taking a look at the last command, the output can be a bit confusing. There are many columns but we don’t exactly know what they stand for.

First of all, there is a difference between user login and reboots.

As you can see, user logins start with the name of the user that connected to the computer. On the other hand, “reboot” logs obviously start with the “reboot” keyword.

User Log In Columns

For user logs, the meaning of the different columns is the following :

  • Username : the username who connected to the computer;
  • TTY : the index of the TTY used by the user in order to connect to the computer. “:0” denotes that the connection is local and you may use the “tty” command in order to find the device used by the user;
$ tty

Last Command Columnstty-command
The user is using /dev/pts/0 to interact with the system

  • The name of the display : as X is used as the display server on every machine, it may use a local display (:0, :1 and so on) or a remote display. If you are interested in running graphical applications remotely, you may read our guide about the X protocol;
  • Hour of the login : starting the server is quite different from logging into it. This hour represents the time where the password was actually provided in the interface;
  • Login status : either you are “still logged in” or “down” with the duration of the session.

Last Command Columns last-session-duration

For example, in the following example, the session duration was twelve minutes.

Pseudo reboot columns

On every reboot, your system adds a new line to the current list of reboots performed on your computer.

Those special lines, starting with “reboot“, have the following columns :

  • Reboot : specifying that this is not a log in but rather a system reboot;
  • Details about the reboot : in this case it was actually a “system boot” meaning that the system just started;
  • Kernel version : the kernel version loaded when booting up the system. It might be different if you host different version of the kernel on your boot partition.
  • Hour of the boot : the hour represents the time of the system boot. It is either followed by a “still running” indication or the end hour followed by the session duration in paranthesis.

Now that you have seen how you can list all last logins on your server, let’s see if you are interested in bad login attempts.

Find Last Login By Date

In some cases, you may be interested in login that were made since or until a specific date in the past, or in the last five minutes.

To find the last login by date, execute the “last” command with the “–since” command and specify the date to find the last logins for.

Similarly, you can use the “–until” command in order to find login attempts made until a given date in the past.

$ last --since <date>

$ last --until <date>

So what are the dates that you can use in order to search?

Date formats are specified in the last documentation page.

Find Last Login By Date last-date-formats

As an example, let’s say that you want to find all login attempts were in the past two days, you would execute the following command

$ last --since -2days

Find Last Login By Date last-since-two-days

Similarly, if you want to find all login attempts made five days in the past, you would run the following command

$ last --until -5days

As a diagram often helps more than words, here is a way to understand the “–since” and “–until” options.

Find Last Login By Date linux-last-login-command

Find Last Bad Login Attempts using lastb

In order to find the last bad login attempts on your Linux server, you have to use the “lastb” with administrator rights.

$ sudo lastb

If you are not sure about how to check such rights, make sure to read our dedicated guides.

Find Last Bad Login Attempts using lastb-command-linux

As you can see, the output is quite similar to the one from the “last” command : the username attempted, the device used as well as the time of the attempt.

In this case, the duration “(00:00)” will be fixed as a connection attempt has no duration at all.

Note that the device line can display “ssh:notty” in case that the log in attempt was made from a SSH terminal.

Inspecting the auth.log file

Alternatively, you can inspect the content of the “/var/log/auth.log” file in order to see all failed attempts on your server.

$ tail -f -n 100 /var/log/auth.log | grep -i failed

Inspecting the auth.log file auth-log-failed-attempts

Find Last SSH Logins on Linux

In order to find the last SSH logins performed on your Linux machine, you can simply inspect the content of the “/var/log/auth.log” and pipe it with “grep” to find SSH logs.

$ tail -f -n 100 /var/log/auth.log | grep -i sshd

Find Last SSH Logins on Linux sshd-logs-last

Alternatively, you can inspect the logs of the SSH service by running the “journalctl” command followed by the “-u” option for “unit” and the name of the service.

$ sudo journalctl -r -u ssh | grep -i failed

Find Last SSH Logins on Linux journactl-command

Note : interested in listing services and their statuses on your server? Here is a guide about listing your services on Linux.

If you don’t see any logs related to the SSH service, it might be related to your SSH configuration file, namely to the “PrintLastLog” option.

$ cat /etc/ssh/sshd_config | grep PrintLastLog

Find Last SSH Logins on Linux print-last-log-ssh

If this option is set to “No” on your server and you wish to print last logs, make sure to uncomment the line with the “yes” value. Do not forget to restart your SSH server after that.

$ sudo nano /etc/ssh/sshd_config

PrintLastLog yes

$ sudo systemctl restart ssh

$ sudo systemctl status ssh

Great! You learnt how you can find the last SSH logs on your computer.

List User Last Login on Linux

In order to find last login times for all users on your Linux machine, you can use the “lastlog” command with no options. By default, you will be presented with the list of all users with their last login attempts.

Alternatively, you can use the “-u” option for “user” and specify the user you are looking for.

$ lastlog

$ lastlog -u <user>

List User Last Login on Linux lastlog-command

As you can see, with no options, the command will return the list of all accounts on your machine, even the root one and system ones.

Conclusion

In this tutorial, you learnt how you can easily find the last login attempts made on a Linux computer.

Whether those attempts were made through a login shell or a SSH session, you now know which files to inspect and which tools to use in order to retrieve them.

Remember that you can inspect those files but you can also plot them on a dashboarding solution such as Kibana, here’s a guide on how to achieve that.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to have a look!

How To Encrypt File on Linux

If you are a conscientious system administrator, you have probably already wondered how you can make your files secure.

Nowadays, as system attacks get more and more frequent, it isn’t probably a bad idea to think about encrypting your files.

On Linux, there are multiple of encrypting files, directories or filesystems : namely using the LUKS disk encryption specification or simple tools such as GnuPG.

In this tutorial, you will learn how you can easily encrypt files and directories on Linux using the GnuPG tool as well as the zip utility.

Encrypt Files using passphase protection

One of the easiest ways of encrypting a file on Linux is to use the “gpg” utility.

“gpg” is a simple utility that is part of the OpenPGP initiative that aims at providing easy methods to securely sign documents.

Files can be decrypted using two different methods : a password or a key file. In this section, we are going to focus on setting up a password protection for your encrypted files.

To encrypt files using a password, use the “gpg” command with the “-c” option specifying that you want to use a symmetric encryption for your file. After that, specify the name of the file that you want to encrypt.

$ gpg -c <file>

The “gpg” command will create a file with a “.gpg” extension which is the encrypted file that you want to store.

Encrypt Files using passphase protection encrypt-file-using-gpg

If you are running a Linux distribution with a graphical environment, you will be prompted with a window in order to specify the passphrase.

passphrase-encrypt-file

Note : make sure not to forget your passphrase. You won’t be able to recover the passphrase in any means.
Special tip : writing down your passphrase and storing it in a physical lock can be a solution.

If you were to inspect the content of the file using a simple “cat “command, you would not be able to see the content.

Encrypt Files using passphase protection encrypted-file

Awesome, you successfully encrypted a file on Linux using “gpg”!

Decrypt Encrypted File on Linux

In order to decrypt an encrypted file on Linux, you have to use the “gpg” command with the “-d” option for “decrypt” and specify the “.gpg” file that you want to decrypt.

$ gpg -d <file>.gpg

Decrypt Encrypted File on Linux decrypt-file-root

Again, you will be probably be prompted with a window (or directly in the terminal) for the passphrase. If you provide the correct one, you will be able to see the content of your file.

Decrypt Encrypted File on Linux decrypt-file-linux

Note : if you were not prompted for the passphrase for the file, it is because the GPG utility will create a set of keys for you in your home directory when you unlock a file (or create it)

Awesome, your file is now decrypted, you can inspect its content easily.

Encrypt Directory using gpg

In some cases, you may be interested in encrypting a whole directory, containing a lot of files.

In order to achieve that, you are going to create an archive first and encrypt it later on.

To create an archive, use the “tar” command along with the “-cvf” options that stand for “create a file in verbose mode”. Now that your archive is created, you can encrypt it using the “gpg” command with the “-c” option.

$ tar -cvf archive.tar <directory>

$ gpg -c archive.tar

Encrypt Directory using gpg encrypt-tar-archive

Again, you might be prompted for a specific passphrase that you will have to remember.

Congratulations, you successfully encrypted a directory using the tar and gpg commands!

Encrypt Directory using zip

In order to encrypt a file using zip, use the “zip” command with the “–encrypt” option and provide the zip name as well as the files to be encrypted.

$ zip -r --encrypt secure.zip <directory>

$ zip --encrypt secure.zip <file>...<file10>

Encrypt Directory using zip secure-zip

Awesome, you have successfully created an encrypted zip archive!

To open your encrypted archive, you can simply use the “unzip” command and provide the password you just used.

Encrypt Directory using zip unzip-encrypted-zip

Encrypt Files using private key

As explained in other tutorials, generating key pairs (a public key and a private key) remain a very efficient way of preventing people from accessing your files.

To encrypt files on Linux using a private key, you have to execute the “gpg” command with the “–full-gen-key” option. You have multiple options for key generation (such as “–quick-generate-key”) but the full one gives you more options.

$ gpg --full-gen-key

Encrypt Files using private key gpg-generate-key

By default, the GPG utility will ask you a couple of questions. First, it wants you to choose an encryption method for your key.

We are going to choose “RSA” as it can be trusted as one of the best encryption methods available.

Encrypt Files using private key rsa-encryption-method

On the next step, you are asked for the size of the key that you want, we are going to remain with the defaults one and press Enter.

Encrypt Files using private key expiration-key

Finally, you are asked if you want to configure an expiration for the key that you are going to create. In this case, we want to use the same key forever, so you can choose the “0” option.

Encrypt Files using private key information-gpg-key

Now that you specified the key parameters, you are going to provide your name, your email address as well as a comment that is describing your key.

If everything is okay, you can press “O” and proceed to choose a passphrase.

passphrase-key-encryption

So why would you need a passphrase? A passphrase is used in order to protect your key from being stolen. Having a key alone is not enough, not that it could be brute-forced, but somebody could steal your key and use it to decrypt your files. A passphrase prevents this operation.

Encrypt Files using private key generated-key-linux

Congratulations, you successfully created your set of keys for encryption, you can now use them in order to encrypt your files.

To encrypt your file using your created key, you have to use the “gpg” command with the “-e” option for “encrypt” and specify the key to be used with the “–recipient” option.

$ gpg -e --recipient <email or name> <file>

In this case, we used the “devconnected” name along with the “devconnected@example.com” email address. To encrypt the file, we are going to execute the following command :

$ gpg -e --recipient devconnected@example.com

encrypt-using-key

Awesome, you have successfully encrypted your file using your key!

Decrypt File using key

In order to decrypt the file you just encrypted using your key, you have to use the “gpg” command with the “-d” option for decrypt.

$ gpg -d <file>.gpg

In this case, you will be prompted with a window that contains many more information, more specifically the key used.

passphrase-2

When providing the correct passphrase, you will be able to decrypt your file, great!

Decrypt File using key decrypt-file-gpg

Encrypt Files using Nautilus GUI

If you are not into using the terminal, you might want to have a beautiful GUI in order to encrypt your files.

To encrypt using a graphical interface, you are going to use the “Nautilus” file manager along with the “seahorse-nautilus” extension. This extension brings GPG features right into your graphical file explorer.

$ sudo apt-get install nautilus

$ sudo apt-get install seahorse-nautilus

Encrypt Files using Nautilus GUI seahorse-nautilus

When you are done, restart Nautilus by using the “nautilus” command with the “-q” option for “quit”.

$ nautilus -q

Open Nautilus again, using the command line or your left vertical bar, and right click on a file to see the “Encrypt” option.
Encrypt Files using Nautilus GUI nautilus-encryption
When clicking on “Encrypt“, you are asked if you want to choose a passphrase or if you want to encrypt the file using a key.
Encrypt Files using Nautilus GUI nautilus-encryption-2-1

In this case, select the key that you created in the steps before, and click on “Ok” when you are done.

That’s it! You now have an encrypted version of your file.

gpg-file

But did you know that you could decrypt your file using a GUI interface also?

Decrypt using GUI Interface

In order to decrypt your file, you can simply double-click or right-click and select the “Open with Decrypt File”.

Decrypt using GUI Interface open-with-decrypt-file

By using this option, you will be asked the name of the file to be created when decrypting the file. In this case we are going to choose file named “custom.txt

custom-file

When clicking on “Save“, you will be asked for the passphrase that you specified when creating your public key. Provide the specified passphrase and your file should be decrypted!

file-decrypted

Conclusion

In this tutorial, you learnt how you can simply encrypt and decrypt a file on Linux using console line commands or GUI tools.

Encryption is a big part of security : if you are storing sensitive information on your computer or server, you should seriously think about encryption for your disks.

If you are interested in disk encryption, maybe you should take a look at the LUKS project that aims at providing a simple API for it.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Encrypt Root Filesystem on Linux

As a system administrator, you probably already know how important it is to encrypt your disks.

If your laptop were to be stolen, even a novice hacker would be able to extract the information contained on the disks.

All it takes is a simple USB stick with a LiveCD on it and everything would be stolen.

Luckily for you, there are ways for you to prevent this from happening : by encrypting data stored on your disks.

In this tutorial, we are going to see the steps needed in order to perform a full system encryption. You may find other tutorials online focused on encrypting just a file or home partitions for example.

In this case, we are encrypting the entire system meaning the entire root partition and the boot folder. We are going to encrypt a part of the bootloader.

Ready?

Prerequisites

In order to perform all the operations detailed in this guide, you obviously need to have system administrator rights.

In order to check that this is the case, make sure that you belong to the “sudo“ group (for Debian based distributions) or “wheel“ (on RedHat based ones).
How To Encrypt Root Filesystem on Linux checking-sudo

If you see the following output, you should be good to go.

Before continuing, it is important for you to know that encrypting disks doesn’t come without any risks.

The process involves formatting your entire disk meaning that you will lose data if you don’t back it up. As a consequence, it might be a good idea for you to backup your files, whether you choose to do it on an external drive or in an online cloud.

If you are not sure about the steps needed to backup your entire system, I recommend that you read the following tutorial that explains it in clear terms.

Now that everything is set, we can begin encrypting our entire system.

Identify your current situation

This tutorial is divided into three parts : one for each scenario that you may be facing.

After identifying your current situation, you can directly navigate to the chapter that you are interested about.

If you want to encrypt a system that already contains unencrypted data, you have two choices :

  • You can add an additional disk to your computer or server and configure it to become the bootable disk : you can go to the part one.
  • You cannot add an additional disk to your computer (a laptop under warranty for example) : you will find the information needed on part two.

If you are installing a brand new system, meaning that you install the distribution from scratch, you may encrypt your entire disk directly from the graphical installer. As a consequence, you can go to part three.

Design Hard Disk Layout

Whenever you are creating new partitions, encrypted or not, it is quite important to choose the hard disk design ahead of time.

In this case, we are going to design our disk using a MBR layout : the first 512 bytes of the bootable disk will be reserved for the first stage of the GRUB (as well as metadata for our partitions).

The first partition will be an empty partition reserved for systems using EFI (or UEFI) as the booting firmware. If you choose to install Windows 10 in the future, you will have a partition already available for that.

The second partition of our disk will be formatted as a LUKS-LVM partition containing one physical volume (the disk partition itself) as well as one volume group containing two logical volumes : one for the root filesystem and another one for a small swap partition.

As you can see, the second stage of the GRUB will be encrypted too : this is because we chose to have the boot folder stored on the same partition.

Design Hard Disk Layout mbr-disk-design

Of course, you are not limited to the design provided here, you can add additional logical volumes for your logs for example.

This design will be our roadmap for this tutorial : we are going to start from a brand new disk and implement all the parts together.

Data-at-rest encryption

This tutorial focuses on data-at-rest encryption. As its name states, data-at-rest encryption means that your system is encrypted, i.e nobody can read from it, when it is resting or powered off.

Data-at-rest encryption data-at-rest-encryption

This encryption is quite useful if your computer were to be stolen, hackers would not be able to read data on the disk unless they know about the passphrase that you are going to choose in the next sections.

However, there would still be a risk that your data is erased forever : having no read access to a disk does not mean that they cannot simply remove partitions on it.

As a consequence, make sure that you keep a backup of your important files somewhere safe.

Encrypting Root Filesystem on New Disk

As detailed during the introduction, we are going to encrypt the root filesystem from a new disk that does not contain any data at all. This is quite important because the encrypted disk will be formatted in the process.

Head over to the system that you want to encrypt and plug the new disk. First of all, identify your current disk, which is probably named “/dev/sda” and the disk that you just plugged in (probably named “/dev/sdb”).

If you have any doubts about the correspondence between names and disk serials, you can append vendors and serials with the “-o” option of lsblk.

$ lsblk -do +VENDOR,SERIAL

Encrypting Root Filesystem on New Disk listing-drives-linux

In this case, the disk with data is named “/dev/sda” and the new one is named “/dev/sdb”.

First of all, we need to create the layout we specified in the introduction, meaning one partition that is going to be a EFI one and one LUKS-LVM partition.

Creating Basic Disk Layout

The first step on our journey towards full disk encryption starts with two simple partitions : one EFI (even if we use MBR, in case you want to change in the future) and one for our LVM.

To create new partitions on your disk, use the “fdisk” command and specify the disk to be formatted.

$ sudo fdisk /dev/sdb

As explained in the introduction, the first partition will be a 512 Mb one and the other one will take the remaining space on the disk.

Creating Basic Disk Layout create-w95-partition

In the “fdisk” utility, you can create a new partition with the “n” option and specify a size of 512 megabytes with “+512M“.

Make sure to change the partition type to W95 FAT32 using the “t” option and specifying “b” as the type.

Awesome, now that you have your first partition, we are going to create the one we are interested in.

Creating Basic Disk Layout create-second-partition

Creating the second partition is even simpler.

In the fdisk utility, use “n” in order to create a new partition and stick with the defaults, meaning that you can press “Enter” on every steps.

When you are done, you can simply press “w” in order to write the changes to disk.

Now, executing the “fdisk” command again will give you a good idea of the changes that you performed on the disk.

$ sudo fdisk -l /dev/sdb

Creating Basic Disk Layout fdisk-command-disk

Great!

Your second partition is ready to be formatted so let’s head to it.

Creating LUKS & LVM partitions on disk

In order to encrypt disks, we are going to use LUKS, short for the Linux Unified Key Setup project.

LUKS is a specification for several backends implemented in some versions of the Linux kernel.

In this case, we are going to use the “dm-crypt” submodule of the Linux storage stack.

As its names states, “dm-crypt” is part of the device mapper module that aims at creating a layer of abstraction between your physical disks and the way you choose to design your storage stack.

Creating LUKS & LVM partitions on disk dm-crypt

This information is quite important because it means that you can encrypt pretty much every device using the “dm-crypt” backend.

In this case, we are going to encrypt a disk, containing a set of LVM partitions, but you may choose to encrypt a USB memory stick or a floppy disk.

In order to interact with the “dm-crypt” module, we are going to use the “cryptsetup” command.

Obviously, you may need to install it on your server if you don’t have it already.

$ sudo apt-get instal cryptsetup

$ which cryptsetup

Creating LUKS & LVM partitions on disk which-cryptsetup

Now that the cryptsetup is available on your computer, you will create your first LUKS-formatted partition.

To create a LUKS partition, you are going to use the “cryptsetup” command followed by the “luksFormat” command that formats the specified partition (or disk).

 $ sudo cryptsetup luksFormat --type luks1 /dev/sdb2
Note : so why are we specifying the LUKS1 formatting type? As of January 2021, GRUB (our bootloader) does not support LUKS2 encryption. Make sure to leave a comment if you notice that LUKS2 is now released for the GRUB bootlader.

Creating LUKS & LVM partitions on disk cryptsetup-luksformat

As you can see, you are notified that this operation will erase all data stored on the disk. Check the disk that you are formatting one last time, and type “YES” when you are ready.

Right after, you are prompted with a passphrase. LUKS uses two authentication methods : a passphrase based one which is essentially a password that you enter on decryption.

LUKS can also use keys. Using keys, you can for example store it on a part of your disk and your system will be able to look after it automatically.

Choose a strong passphrase, enter it again and wait to the disk encryption to complete.

Creating LUKS & LVM partitions on disk cryptsetup-luksformat-2

When you are done, you can check with the “lsblk” command that your partition is now encrypted as a LUKS one.

Awesome! You now have an encrypted partition.

$ lsblk -f

list-encrypted-drives

To check that your partition is correctly formatted, you can use the “cryptsetup” command followed by the “luksDump” option and specify the name of the encrypted device.

$ sudo cryptsetup luksDump /dev/sdb2

cryptsetup-luksdump

Your version should be set to “1” for the “LUKS1” format and you should see below the encrypted passphrase in one of the keyslots.

Creating Encrypted LVM on disk

Now that your LUKS encrypted partition is ready, you can “open” it. “Opening” an encrypted partition simply means that you are going to access data on the disk.

To open your encrypted device, use the “cryptsetup” command followed by “luksOpen”, the name of the encrypted device and a name.

$ sudo cryptsetup luksOpen <encrypted_device> <name>

cryptsetup-luksOpen

In this case, we chose to name the device “cryptlvm“.

As a consequence, using the “lsblk” command again, you can see that a new device was added to the existing device list. The second partition now contains a device named “cryptlvm” which is your decrypted partition.

Now that everything is ready, we can start creating our two LVM : one for our root partition and one for swap.

First of all, we are going to create a physical volume for our new disk using the “pvcreate” command.

# Optional, if you don't have LVM commands : sudo apt-get install lvm2

$ sudo pvcreate /dev/mapper/cryptlvm

create-physical-volume

Now that your physical volume is ready, you can use it to create a volume group named “cryptvg“.

$ sudo vgcreate cryptvg /dev/mapper/cryptlvm

vgcreate-command

Now that your volume group is ready, you can create your two logical volumes.

In this case, the first partition is a 13Gb one and the swap partition will take the remaining space. Make sure to modify those numbers for your specific case.

In order to host our root filesystem, we are going to create an EXT4 filesystem on the logical volume.

$ sudo lvcreate -n lvroot -L 13G cryptvg

$ sudo mkfs.ext4 /dev/mapper/cryptvg-lvroot

create-root-logical-volume

Creating the swap partition can be achieved using the same steps, using the “lvcreate” and the “mkswap” one.

$ sudo lvcreate -n lvswap -l 100%FREE cryptvg

$ sudo mkswap /dev/mapper/cryptvg-lvswap

create-swap-logical-volume

Awesome! Now that your partitions are created, it is time for you to transfer your existing rootfilesystem on the newly created one.

Transfer Entire Filesystem to Encrypted Disk

Before transferring your entire filesystem, it might be a good idea to check that you have enough space on the destination drive.

$ df -h

In order to transfer your entire filesystem to your newly created partition, you are going to use the “rsync” command.

Mount your newly created logical volume and start copying your files and folders recursively to the destination drive.

$ sudo mount /dev/mapper/cryptvg-lvroot /mnt

$ sudo rsync -aAXv / --exclude="mnt" /mnt --progress

This process can take quite some time depending on the amount of data that you have to transfer.

After a while, your entire filesystem should be copied to your encrypted drive. Now that the “/boot” is encrypted, you will need to re-install the stage 1 of the GRUB accordingly.

Install and Configure GRUB Bootloader

So, why would you need to re-install and re-configure your GRUB accordingly?

To answer this question, you need to have a basic idea of the way your system boots up when using a BIOS/MBR conventional booting process.

Install and Configure GRUB Bootloader linux-bios-boot-process

As explained in the introduction, GRUB is split into two (sometimes three) parts : GRUB stage 1 and GRUB stage 2. The stage 1 will only look for the location of the stage 2, often located in the “/boot” folder of your filesystem.

The stage 2 is responsible for many tasks : loading the necessary modules, loading the kernel into memory and starting the the initramfs process.

As you understood, the stage 2 is encrypted here, so we need to tell the stage 1 (located in the first 512 bytes of your disk) that it needs to be decrypted first.

Re-install GRUB Stage 1 & 2

In order to reinstall the first stage of the GRUB, you first need to enable the “cryptomount” that enables access to encrypted devices in the GRUB environment.

To achieve that, you need to edit the “/etc/default/grub” file and add the “GRUB_ENABLE_CRYPTODISK=y” option.

However, you are currently sitting on the system that you are trying to encrypt. As a consequence, you will need to chroot into your new drive in order to execute the commands properly.

Chroot in Encrypted Drive

To chroot into your encrypted drive, you will have to execute the following commands.

$ sudo mount --bind /dev /mnt/dev
$ sudo mount --bind /run /mnt/run

$ sudo chroot /mnt/

$ sudo mount --types=proc proc /proc
$ sudo mount --types=sysfs sys /sys

Chroot in Encrypted Drive lsblk-chroot

Now that you executed those commands, you should now be in the context of your encrypted drive.

$ vi /etc/default/grub

grub-enable-cryptodisk-1

GRUB_ENABLE_CRYPTODISK=y

As stated in the GRUB documentation, this option will configure the GRUB to look for encrypted devices and add additional commands in order to decrypt them.

Now that the stage 1 is configured, you can install it on your MBR using the grub-install command.

$ grub-install --boot-directory=/boot /dev/sdb
Note : be careful, you need to specify “/dev/sdb” and not “/dev/sdb1”.

grub-install-stage-1

As you probably noticed, when providing no options for the GRUB installation, you have by default an “i386-pc” installation (which is designed for a BIOS-based firmware).

Re-install GRUB Stage 2

Using the steps detailed above, the stage 1 has been updated but we also need to tell the stage 2 that it is dealing with an encrypted disk.

To achieve that, head over to the “/etc/default/grub” and add another line for your GRUB stage 2.

GRUB_CMDLINE_LINUX="cryptdevice=UUID=<encrypted_device_uuid> root=UUID=<root_fs_uuid>"

This is an important line because it tells the second stage of the GRUB where the encrypted drive is and where the root partition is located.

To identify the UUIDs needed, you can use the “lsblk” command with the “-f” option.

$ lsblk -f

lsblk-uuids

Using those UUIDs, we would add the following line to the GRUB configuration file.

GRUB_CMDLINE_LINUX="cryptdevice=UUID=1b9a0045-93d5-4560-a6f7-78c07e1e15c4 root=UUID=dd2bfc7f-3da2-4dc8-b4f0-405a758f548e"

To update your current GRUB installation, you can use the “update-grub2” command in your chrooted environment.

$ sudo update-grub2

update-grub2-command

Now that you updated your GRUB installation, your GRUB menu (i.e the stage 2) should be modified and you should see the following content when inspecting the “/boot/grub/grub.cfg” file.

grub-configuration-file

As you can see, the GRUB configuration file was modified and your system is now using “cryptomount” in order to locate the encrypted drive.

For your system to boot properly, you need to check that :

  • You are loading the correct modules such as cryptodisk, luks, lvm and others;
  • The “cryptomount” instruction is correctly set;
  • The kernel is loaded using the “cryptdevice” instruction we just set in the previous section.
  • The UUID specified are correct : the “cryptdevice” one is pointing to the LUKS2 encrypted partition and the “root” one to the ext4 root filesystem.

Modify crypttab and fstab files

One of the first steps of initramfs will be to mount your volumes using the “/etc/crypttab” and “/etc/fstab” files on the filesystem.

As a consequence, and because you creating new volumes, you may have to modify those files in order to put the correct UUID in them.

First of all, head over to the “/etc/crypttab” file (you can create it if it does not exist already) and add the following content

$ nano /etc/crypttab

# <target name>   <source device>        <key file> <options>
  cryptlvm        UUID=<luks_uuid>       none       luks

Modify crypttab and fstab files crypttab-file

If you are not sure about the UUID of your encrypted device, you can use the “blkid” to get the information.

$ blkid | grep -i LUKS

Now that the crypttab file is modified, you only need to modify the fstab accordingly.

$ nano /etc/fstab

# <file system>       <mount point>   <type>  <options>             <dump>    <pass>
UUID=<ext4 uuid>      /               ext4    errors=remount-ro     0         1

Again, if you are not sure about the UUID of your ext4 filesystem, you can use the “blkid” command again.

$ blkid | grep -i ext4

Almost done!

Now that your GRUB and configuration files are correctly configured, we only need to configure the initramfs image.

Re-configure initramfs image

Among all the boot scripts, initramfs will look for the root filesystem you specified in the previous chapter.

However, in order to decrypt the root filesystem, it will need to invoke the correct initramfs modules, namely the “cryptsetup-initramfs” one. In your chrooted environment, you can execute the following command :

$ apt-get install cryptsetup-initramfs

In order to include the cryptsetup modules in your initramfs image, make sure to execute the “update-initramfs” command.

$ update-initramfs -u -k all

That’s it!

You have successfully assembled all the needed pieces in order to create a fully encrypted disk on your system. You can now reboot your computer and have a look at your new boot process.

Boot on Encrypted Device

When booting, the first screen that you will see is the first stage of the GRUB trying to decrypt the second stage of the GRUB.

Boot on Encrypted Device grub-stage-1-encrypted

If you see this password prompt, it means that you don’t have any errors in your stage 1 configuration.

Note : be aware that this screen may not follow your usual keyboard layout. As a consequence, if you have an incorrect password prompt, you should try pretending that you have a US keyboard or an AZERTY one for example.

When providing the correct password, you will be presented with the GRUB menu.

grub-stage-2

If you see this screen, it means that your stage 1 was able to open the stage 2. You can select the “Ubuntu” option and boot on your system.

boot-lock-screen

On the next screen, you are asked to provide the passphrase again.

This is quite normal because your boot partition is encrypted. As a consequence, you need one passphrase in order to unlock the stage 2 and one to unlock the entire root filesystem.

Luckily, there is a way to avoid that : by having a key file embedded in the initramfs image. For that, ArchLinux contributors wrote an excellent tutorial on the subject.

In this case, we are just going to provide the passphrase and press Enter.

After a while, when the init process is done, you should be presented with the lock screen of your user interface!

Congratulations, you successfully encrypted an entire system on Linux!

lock-screen

Encrypting Root Filesystem on Existing Disk

In some cases, you may have to encrypt an existing disk without the capability of removing one of the disks on your computer. This case may happen if you have a disk under warranty for example.

In this case, the process is quite simple :

  • Make a bootable USB (or removable device) containing an ISO of the distribution of your choice;
  • Use the device in order to boot and log into a LiveCD of your distribution;
  • From the LiveCD, identify the hard disk containing your root distribution and make a backup of it;
  • Mount the primary partition on the folder of your choice and follow the instructions of the previous chapter;

So why do you need to use a LiveCD if you want to encrypt a non-removable disk?

If you were to encrypt your main primary disk, you would have to unmount it. However, as it is the root partition of your system, you would not be able to unmount it, as a consequence you have to use a LiveCD.

Encrypting Root Filesystem From Installation Wizard

In some cases, some distributors embed the encryption process right into the installation wizard.

If you are not looking to transfer an existing filesystem from one system to another, you might be tempted to use this option.

Taking Ubuntu 20.04 as an example, the installation process suggests disk encryption in the disk configuration wizard.

Encrypting Root Filesystem From Installation Wizard
If you select this option, you will have a similar setup to the one done in the previous sections. However, most distributions choose not to encrypt the “/boot” folder.

encrypted-system-from-wizard

If you want to encrypt the “/boot” folder, we recommend that you read the first section of this tutorial.

Troubleshooting

As open-source changes constantly, there is a chance that you are not able to boot your system, even if you followed the steps of this tutorial carefully.

However, as error sources are probably infinite and specific to every user, there would be no point enumerating every single issue that you can encouter.

However, most of the time, it is quite important to know on which step of the boot process you are failing.

If you see a screen with a “grub rescue” prompt, it probably means that you are stuck on the stage 1, thus that the bootloader was not able to locate the disk containing the second stage.

If you are in an initramfs prompt, it probably means that something wrong happened during the init process :

  • Are you sure that you specified the filesystems to mount in the crypttab and fstab files?
  • Are you sure that all modules were currently loaded in your initramfs image? Aren’t you missing the cryptsetup or lvm modules for example?

initramfs-screen

Below are some resources that we found interesting during the writing of this tutorial, they may have some answers to your problems :

  • Encrypting an entire system : a similar tutorial for ArchLinux;
  • Manual System Encryption on Ubuntu : steps used in order to chroot in a root filesystem.

Conclusion

In this tutorial, you learnt how you can encrypt an entire root filesystem, with the “/boot” folder, using the LUKS specification.

You also learnt about the Linux boot process and the different steps that your system goes through in order to launch your operating system.

Achieving a full-system encryption is quite lengthy but it is very interesting for users that are willing to dig deeper into the Linux and open source world.

If you are interested in Linux System Administration, make sure to read our other tutorials and to navigate to our dedicated section.

How To List Users and Groups on Linux

On Linux, as a system administrator, you often want to have a complete list of all the users and all the groups on your host.

It is quite crucial for security purposes to make sure that you have the correct amount of users and that you didn’t forget to delete some.

There are several ways to list users and groups on Linux.

First, you can read the passwd and the group file on your system, with cut commands to extract useful information.

A more effective way is to use the getent command that relies on the Name Service Switch, a Unix-based facility to define custom databases on your host.

Here is how you can list users and groups on Linux.

List Users on Linux

In order to list users on Linux, you have to execute the “cat” command on the “/etc/passwd” file. When executing this command, you will be presented with the list of users currently available on your system.

Alternatively, you can use the “less” or the “more” command in order to navigate within the username list.

$ cat /etc/passwd

$ less /etc/passwd

$ more /etc/passwd

You will be presented with a list of users currently available on your system.

Note : it does not mean that users are connected right now!

List Users on Linux etc-passwd

But what do the columns of the passwd file even mean?

list-users-linux

As a quick side note, an “x” in the password column means that the password is encrypted and it is to be found in the /etc/shadow file.

Now that you know how to list users on your Linux host, let’s see how you can effectively isolate a list of usernames.

List Usernames using the /etc/passwd file

As you probably noticed, the /etc/passwd file is made of lines separated by colons.

a – List Usernames using cut

In order to list usernames on Linux, use the “cat” command and pipe it to the “cut” command in order to isolate usernames available in the first column of your file.

To achieve that, run the following command

$ cat /etc/passwd | cut -d: -f1

First, you are printing a list of all records in the passwd file. Next, those results are piped (using Linux pipes and redirection) to the cut command.

The cut command defines a custom separator (with the d option) that is equal to the colon character.

Finally, we are isolating the first field of the results we are getting. In this case, this is equal to the usernames as defined by our schema on the passwd columns.

a – List Usernames using cut cut-options

b – List Usernames using awk

In order to list usernames on Linux, you can also use the “cat” command piped with the “awk” command that is similar to the “cut” command that we have seen before.

As a reminder, the awk command (or mawk) is an interpreter for the AWK programming language.

AWK is a programming language designed to ease data extract and manipulation for data streams.

It is widely used on Unix-based systems when text structures are quite complicated and cannot be separated with a single command.

To list usernames on Linux using the awk interpreter, run the following command

$ cat /etc/passwd | awk -F: '{print $1}'

b – List Usernames using awk -list

List Users on Linux using getent

The easiest way to list users on Linux is to use the “getent” command with the “passwd” argument and specify an optional user that you want to list on your system.

getent passwd <optional_user>

As a reminder, the getent command retrieves entries from Name Service Switch databases.

The Name Service Switch is a Unix utility that retrieves entries from a set of different datasources such as files, LDAP, a DNS server or a Network Information Service.

The list of all the datasources available can be read from the nsswitch.conf file located at /etc.

List Users on Linux using getent nsswitch

In our case, it can be used in order to list users and groups easily on our Linux host.

To list users using the getent function, run the following command

$ getent passwd

getent-passwd

a – List Usernames with getent

Similarly to the previous section, it is possible to list only usernames when interacting with the getent command.

To achieve that, you can alternatively execute the cut command or the awk command in the following way.

$ getent passwd | cut -d: -f1

Or with AWK

$ getent passwd | awk -F: '{print $1}'

a – List Usernames with getent-passwd

List Connected Users on your Linux host

As mentionned previously, inspecting the passwd file, either with less or with getent, does not provide you with a list of all the connected users on your host.

To achieve that, you are going to use the who command.

$ who

List Connected Users on your Linux host who

As you can see, you are provided with a list of users currently connected on your host along with the shell they are using and when they connected.

Alternatively, you can use the users command to achieve the same result with less details.

$ users
devconnected john

Pretty handy!

Now that we have seen how we can list users on a Linux host, let’s see how we can apply the same knowledge to list groups on your system.

List Groups on Linux using the /etc/group file

In order to list groups on Linux, you have to execute the “cat” command on the “/etc/group” file. When executing this command, you will be presented with the list of groups available on your system.

Use one of the following commands to list groups on your system.

$ cat /etc/group

$ less /etc/group

$ more /etc/group
List Groups on Linux using the etc group file
But what do the columns of the group file even represent?

Let’s take a complete line on the group file to inspect it.

List Groups on Linux using the etc group file group-users

As you can see, similarly to the passwd file, the entries are separated by colons. They are fairly easy to understand.

List Groups on Linux using the etc group file etc-group-file

Note : the password field is not used most of the time, it is reserved to create privileged groups on your system.

List Groupnames using the /etc/group

As you can see, inspecting the /etc/group gives you a complete and sometimes too detailed listing of all the groups on your system.

However, you sometimes want to isolate the groupnames on your group file.

To achieve that, you can either use the cut command or the AWK command.

$ cat /etc/group | cut -d: -f1

List Groupnames using the etc group cut-etc-group

$ cat /etc/group | awk -F: '{print $1}'

List Groupnames using the etc group cut-etc-group-awk

You can of course choose to isolate one group if you want to see which users belong to the group you are targeting.

$ cat /etc/group | grep <group>

List Groupnames using the etc group isolate-one-group

List Groups using getent

Again, you can choose to list groups on Linux by using the getent command.

$ getent <database> <key>

Here, we are interested in the “group” database.

If you choose not to provide a key, you will be provided with the entire group file.

$ getent group

List Groups using getent getent-group

Similarly to the passwd database, you can choose to “target” one specific group by providing a key to the getent function.

$ getent group sudo

List Groups using getent getent-group-sudo

List Groups for the current user

The groups commands is used to get a list of groups a specific user is in.

$ groups <username>

If provided with no arguments, it will return the groups for the user that launched the command.

List Groups for the current user groups

To prove that it provides the groups for the user that launched the command, try to launch the command with sudo privileges.

$ sudo groups

List Groups for the current user sudo-groups

The result is.. root! Because the command is executed as root and root only belongs to one group which is the root group.

Conclusion

In this tutorial, you learnt how you can list users and groups on any Linux based system.

You learnt more about specific configuration file like passwd and group, as well as the getent command for Name Service Switch facilities.

Again, if you are interested in Linux system administration, we have tons of tutorials on the subject in our Linux System Administration category.

Click the image below to check them.