50+ Useful Linux Commands for Server Admins

Linux commands play a crucial role in server administration, as they provide a high level of control and flexibility when managing Linux servers. Here are 50+ useful Linux commands any Linux server admin must know.

In this article:

What is Linux commands

Linux commands are text-based instructions that allow server administrators to interact with and manage a Linux-based operating system. These commands are executed in a command-line interface, also known as a terminal or shell, which enables direct communication with the operating system's core components. Server administrators rely on Linux commands to perform various tasks, such as file management, system monitoring, user administration, package management, and network configuration.

Linux commands play a crucial role in server administration, as they provide a high level of control and flexibility when managing Linux servers. By mastering these commands, administrators can automate tasks, diagnose and resolve issues, and optimize server performance.

Linux commands are typically short and concise, with various options and arguments that can be combined to perform specific tasks or achieve desired outcomes. These options and arguments allow administrators to customize the command's behavior, providing a powerful and efficient way to manage servers.

Understanding and utilizing Linux commands is essential for server administrators, as it enables them to effectively manage and maintain Linux-based servers. With a vast array of commands available, administrators can perform a wide range of tasks, from basic file management to advanced system diagnostics and optimization. As a result, Linux commands are a fundamental skill for server administrators working with Linux-based systems.

Remotely log into a Linux server with SSH

SSH (Secure Shell) is a cryptographic network protocol that enables secure communication between a client and a server over an unsecured network. It is widely used for remotely logging into Linux servers and managing them. SSH allows administrators to securely execute commands, transfer files, and perform other tasks on a remote server.

To remotely log into a Linux server with SSH, you'll need an SSH client. Most Linux distributions and macOS have a built-in SSH client accessible through the Terminal application. For Windows users, a popular SSH client is PuTTY, which can be downloaded and installed separately.

To log into a remote Linux server using SSH, follow these steps:

  1. Open the Terminal application (on Linux or macOS) or PuTTY (on Windows).
  2. Type the following command and replace username with your actual username and remote_host with the IP address or hostname of the remote server:
    $ ssh username@remote_host​
  3. When prompted, enter your password to authenticate.

Password-less SSH login

For added security and convenience, you can set up password-less logins using public and private keys. This method involves creating a key pair (public and private keys) and adding the public key to the remote server's authorized_keys file. Here's how to do it:

  1. On your local machine, generate an SSH key pair by running the following command:
    $ ssh-keygen
  2. By default, the key pair will be saved in the ~/.ssh/ directory. You can choose a different directory or accept the default location by pressing Enter.
  3. You'll be prompted to enter a passphrase for the key pair. This is optional, but recommended for added security. Press Enter to skip or type a passphrase and press Enter.
  4. The key pair has now been generated. The public key has the .pub extension (e.g., id_rsa.pub), and the private key has no extension (e.g., id_rsa).
  5. Copy the public key to the remote server using the ssh-copy-id command, replacing username and remote_host with your actual username and the remote server's IP address or hostname:
    $ ssh-copy-id username@remote_host
  6. You'll be prompted to enter your password to authenticate the remote server. Once authenticated, the public key will be appended to the ~/.ssh/authorized_keys file on the remote server.
  7. Now you can log into the remote server without a password. The SSH client will use the private key to authenticate:
    $ ssh username@remote_host

By setting up password-less logins, you can enhance security and streamline the process of connecting to remote Linux servers using SSH.

Execute commands with administrative (root) privileges

$ sudo command

Sudo (superuser do) is a command-line utility that allows users to execute commands with the privileges of another user, usually the superuser or root. It is commonly used to perform administrative tasks that require elevated permissions, such as installing software, managing services, or editing system configuration files.

To use sudo, simply prefix the command you want to run with sudo:

$ sudo apt-get update

When you execute a command with sudo, you will be prompted to enter your password. If the password is correct and you have the necessary permissions, the command will be executed with the elevated privileges.

The sudo -i command provides a convenient way to start a new shell with root privileges:

$ sudo -i

This command opens a new shell session as the root user, allowing you to perform administrative tasks without having to prefix each command with sudo. To exit the root shell and return to your normal user session, simply type exit or press Ctrl-D.

It's important to note that using sudo or a root shell should be done with caution, as it allows you to make changes that can affect the entire system. Always double-check your commands and avoid running commands with sudo or as root unless absolutely necessary.

To manage sudo permissions, the /etc/sudoers file or the /etc/sudoers.d/ directory can be edited using the visudo command, which ensures correct syntax and file locking to prevent simultaneous edits. This file defines which users or groups have sudo privileges and the extent of those privileges.

List directory contents

$ ls
Documents Downloads Pictures Videos

The ls command lists the content of the current directory. For more detailed output or to list the content of another directory, you can use additional options.

$ ls -lah /var/log
total 4768
drwxr-xr-x+ 52 root admin 1.6K Apr 8 22:04 apache2
drwxr-xr-x 6 root admin 192B Dec 29 15:42 mail

Display the current directory

$ pwd
/home/username

The pwd command displays the current directory you are in. This command is helpful for server administrators to keep track of the directory they are working in.

Change directory

$ cd /var/www
$ pwd
/var/www

The cd command is used to change the current directory. It is essential to navigate through the filesystem. To go up one level, use the command:

$ cd ..
$ pwd
/var

List processes running on the system

$ ps
PID TTY TIME CMD
7197 pts/0 00:00:00 bash
7238 pts/0 00:00:00 ps

The ps command lists the processes currently running on the system. To get a detailed list of all processes, use the following command:

$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.1 225848 9444 ? Ss Apr07 0:07 /sbin/init

Display file content

$ cat /etc/hosts
127.0.0.1 localhost

The cat command is used to display the content of a file. To display line numbers along with the content, use the following command:

$ cat -n /etc/hosts
1 127.0.0.1 localhost

Create a new empty file or update the file's timestamp

$ touch example.txt

The touch command is used to create a new empty file or update the timestamp of an existing file. This command is useful for creating files before editing them with a text editor.

Copy files and directories

$ cp source.txt destination.txt

The cp command is used to copy files and directories. To copy a directory and its content, use the following command:

$ cp -r sourcedir/ destinationdir/

Move or rename files and directories

$ mv oldfile.txt newfile.txt

The mv command is used to move or rename files and directories. This command can also be used to move a file to a different directory:

$ mv file.txt /path/to/new/directory/

Remove files and directories

$ rm file.txt

The rm command is used to remove files. To remove a directory and its content, use the following command:

$ rm -r directory/

Create a new directory

$ mkdir new_directory

The mkdir command is used to create a new directory.

Search for files

$ find / -name "filename.txt"
/home/username/filename.txt

The find command is used to search for files in the filesystem. You can search for files based on various criteria, such as name, size, and modification time.

Search for text in files

$ grep "searchterm" file.txt
This line contains the searchterm.

The grep command is used to search for a specific text in files. To search for text in all files in a directory, use the following command:

$ grep -r "searchterm" /path/to/directory/

Display disk usage

$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 50G 30G 20G 60% /

The df command displays disk usage statistics. The -h option makes the output human-readable.

If you want to see what disk partition (filesystem) a certain directory is mounted on, just add the path:

$ df -h /var/www

Display directory space usage

$ du -sh /var/www
1.5G /var/www

The du command displays the space used by directories. The -s option summarizes the output, and the -h option makes it human-readable.

Create a symbolic link

$ ln -s target.txt symlink.txt

The ln command with the -s option creates a symbolic link (symlink) to a target file or directory. Symbolic links are useful for creating shortcuts or for maintaining multiple versions of files.

Change file permissions

$ chmod 755 script.sh

The chmod command is used to change file permissions. In this example, the file permissions are set to 755, which means the owner has read, write, and execute permissions, while the group and others have read and execute permissions.

Change file ownership

$ chown user:group file.txt

The chown command is used to change the ownership of a file or directory. This command changes the owner to "user" and the group to "group" for the specified file.

Show system information

$ uname -a
Linux server 5.11.0-38-generic #42-Ubuntu SMP Tue Sep 28 20:38:01 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

The uname command displays system information, such as kernel name, version, and release date. The -a option shows all available information.

Display system uptime

$ uptime
22:04:10 up 15 days, 6:45, 1 user, load average: 0.00, 0.01, 0.05

The uptime command shows the current time, how long the system has been running, the number of logged-in users, and the system load averages.

Monitor system activity

$ top

The top command displays an overview of the system's processes, memory usage, and CPU utilization. This command is useful for monitoring the overall system performance and identifying resource-hungry processes.

Sort and filter processes

$ ps aux | sort -nk +4 | tail
root 1228 0.0 2.0 169168 10440 ? Ss Apr07 0:00 /usr/sbin/sshd

The ps command can be piped to sort and filter processes based on various criteria, such as memory or CPU usage. In this example, processes are sorted by memory usage, and the last 10 processes are displayed.

Kill a process

$ kill 12345

The kill command is used to terminate a process by sending a signal to it. In this example, the process with the process ID (PID) of 12345 will be terminated.

Schedule a command to run at a later time

$ at 22:30
at> echo "Hello, world!" > hello.txt
at> <EOT>
job 1 at Fri Apr 8 22:30:00 2023

The at command schedules a command to run at a specific time. In this example, the command "echo 'Hello, world!' > hello.txt" will be executed at 22:30.

Schedule periodic tasks

$ crontab -e

The crontab command is used to create, edit, and manage cron jobs for a user. Cron jobs are scheduled tasks that run periodically at specified intervals.

Monitor log files

$ tail -f /var/log/syslog
Apr 8 22:08:01 server CRON[7319]: (root) CMD ( /usr/sbin/ntpdate ntp.ubuntu.com)

The tail command with the -f option is used to monitor log files in real-time. This command displays the last 10 lines of a file and updates the output as the file grows. To show more lines than just the last 10, use the -n <number> option:

$ tail -f -n 100 /var/log/syslog

The last example will begin with outputting the last 100 lines from the syslog.

Archive files and directories

$ tar -czvf archive.tar.gz /path/to/directory

The tar command is used to create and manipulate archive files. In this example, a gzip-compressed archive named "archive.tar.gz" is created from the specified directory.

Extract files from an archive

$ tar -xzvf archive.tar.gz
/path/to/directory/

The tar command can also be used to extract files from an archive. In this example, the files are extracted from the "archive.tar.gz" archive to the current directory.

Compress files and directories

$ gzip file.txt

The gzip command is used to compress files, reducing their size. In this example, "file.txt" is compressed into "file.txt.gz".

Decompress gzip files

$ gunzip file.txt.gz

The gunzip command is used to decompress gzip-compressed files. In this example, "file.txt.gz" is decompressed back into "file.txt".

Display network interfaces

$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.100 netmask 255.255.255.0 broadcast 192.168.1.255

The ifconfig command displays network interface configuration, including IP addresses, netmasks, and broadcast addresses.

Display routing table

$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth0

The route command displays the system's routing table, which shows the available network routes and their associated gateways.

Test network connectivity

$ ping google.com
PING google.com (216.58.207.46) 56(84) bytes of data.
64 bytes from lhr25s12-in-f14.1e100.net (216.58.207.46): icmp_seq=1 ttl=53 time=23.0 ms

The ping command is used to test network connectivity by sending ICMP packets to a specified host. This command is useful for troubleshooting network issues.

Download files from the internet

$ wget https://example.com/file.txt
--2023-04-08 22:32:05-- https://example.com/file.txt
Connecting to example.com (example.com)|93.184.216.34|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1024 (1.0K) [text/plain]
Saving to: ‘file.txt’

The wget command is used to download files from the internet. This command supports downloading files over HTTP, HTTPS, and FTP protocols.

Download files or interact with web services using HTTP, HTTPS, or FTP

$ curl http://example.com/file.txt -o file.txt

Curl is a command-line utility used to transfer data from or to a server using various protocols such as HTTP, HTTPS, and FTP. It is widely used for downloading files, interacting with web services, and testing RESTful APIs. By default, curl sends an HTTP GET request to the specified URL and displays the response in the terminal.

$ curl https://api.example.com/data.json
{
"name": "John Doe",
"age": 30
}

To save the output to a file instead of displaying it in the terminal, use the -o option followed by the output file name:

$ curl http://example.com/file.txt -o file.txt

Curl also supports sending HTTP POST requests, which is useful when interacting with web forms or APIs. To send a POST request, use the -X option followed by the POST keyword, and include the data to send using the -d option:

$ curl -X POST -d "key=value&key2=value2" https://api.example.com/data

To send data as JSON, set the Content-Type header using the -H option:

$ curl -X POST -H "Content-Type: application/json" -d '{"key": "value", "key2": "value2"}' https://api.example.com/data

For more advanced usage, such as authentication, handling redirects, or limiting download speed, consult the curl man page (man curl) or the official documentation (https://curl.se/docs/). Curl offers a wide range of options and capabilities, making it a powerful tool for working with web resources and APIs from the command line.

Transfer files over SSH

$ scp file.txt user@remote_host:/path/to/destination
file.txt 100% 1024 1.0KB/s 00:00

The scp command is used to securely transfer files between the local and remote hosts over an SSH connection. This command is useful for transferring files to and from a remote server.

View installed packages

$ dpkg -l
ii acl 2.2.53-8 amd64 Access control list utilities

The dpkg command with the -l option lists installed packages on a Debian-based system. This command is useful for checking the installed software and their versions.

Install packages

$ sudo apt-get install package_name
Reading package lists... Done
Building dependency tree
Reading state information... Done

The apt-get command is used to manage packages on Debian-based systems. The install option is used to install the specified package along with its dependencies.

Update package list and upgrade packages

$ sudo apt-get update && sudo apt-get upgrade
Hit:1 http://archive.ubuntu.com/ubuntu focal InRelease
Get:2 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]

The apt-get command with the update option is used to update the package list, while the upgrade option is used to upgrade the installed packages to their latest versions. Running both commands together ensures your system is up-to-date.

Search for packages

$ apt-cache search package_name
package_name - brief package description

The apt-cache command with the search option is used to search for packages in the package list. This command is helpful when you are unsure of the exact package name or want to find packages related to a specific task.

Remove packages

$ sudo apt-get remove package_name
Reading package lists... Done
Building dependency tree
Reading state information... Done

The apt-get command with the remove option is used to uninstall packages from the system. This command will remove the specified package but will not remove its configuration files.

Remove packages and configuration files

$ sudo apt-get purge package_name
Reading package lists... Done
Building dependency tree
Reading state information... Done

The apt-get command with the purge option is used to uninstall packages and their configuration files. This command completely removes the specified package and its associated data.

Add a user

$ sudo adduser new_user
Adding user new_user' ... Adding new group new_user' (1001) ...
Adding new user new_user' (1001) with group new_user' ...
Creating home directory `/home/new_user' ...

The adduser command is used to create a new user on the system. This command creates a new user, a new group with the same name as the user, and a home directory for the user.

Delete a user

$ sudo deluser --remove-home user_to_delete
Removing user user_to_delete' ... Warning: group user_to_delete' has no more members.
Done.

The deluser command is used to delete a user from the system. The --remove-home option is used to remove the user's home directory along with the user.

Add a user to a group

$ sudo usermod -aG group_name user_name

The usermod command is used to modify user accounts. In this example, the -aG option is used to add a user to a group.

Check system logs

$ journalctl
-- Logs begin at Fri 2023-04-07 22:12:29 UTC, end at Sat 2023-04-08 22:45:01 UTC. --
Apr 07 22:12:29 server systemd[1]: Started Daily apt upgrade and clean activities.
Apr 07 22:12:29 server systemd[1]: Started Daily apt download activities.

The journalctl command is used to view system logs managed by the systemd journal. This command provides an overview of system events, errors, and other important information.

Clean up system logs

$ journalctl --vacuum-time=2d

The journalctl command with the --vacuum-time option is used to clean up system logs older than a specified time period. In this example, logs older than 2 days will be removed.

$ journalctl --vacuum-size=500M

The journalctl command with the --vacuum-size option is used to clean up system logs to limit their total size. In this example, logs will be cleaned up until their total size is 500MB or less.

Reboot the system

$ sudo reboot

The reboot command is used to restart the system. This command is useful when you need to apply updates, change hardware settings, or troubleshoot issues that require a system restart.

View command history

$ history
1 ls
2 pwd
3 cd /var/log
4 ls -lah

The history command displays the list of previously executed commands. This command is useful for reviewing past commands or repeating a command by using its history number.

Mount all filesystems in fstab

$ sudo mount -a

The mount command with the -a option is used to mount all filesystems listed in /etc/fstab. This command is useful when adding new filesystems or remounting filesystems after making changes to /etc/fstab.

Unmount a filesystem

$ sudo umount /path/to/mountpoint

The umount command is used to unmount a mounted filesystem. This command is useful when you need to disconnect external storage devices or troubleshoot filesystem issues.

Set environment variables

$ export VARIABLE_NAME=value

The export command is used to set environment variables. In this example, a new environment variable named "VARIABLE_NAME" is set with the value "value".

Display environment variables

$ env
USER=nowintech
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

The env command displays a list of all environment variables and their values.

Display file type

$ file filename.txt
filename.txt: ASCII text

The file command determines the file type by examining its content. This command is helpful for identifying the format of a file when the extension is missing or unknown.

Learn more about Linux administration

There are numerous resources available for learning more about Linux commands, server administration, and SSH. Here are some recommendations:

  • Linux documentation and man pages: Most Linux commands come with built-in documentation called "man pages" (short for manual pages). To access the man page for a specific command, type man command_name in the terminal. This will provide detailed information on how to use the command, its options, and arguments.
  • Online tutorials and courses:
    • Linux Journey (https://linuxjourney.com/) is an excellent resource for beginners looking to learn Linux concepts and commands through interactive lessons.
    • edX (https://www.edx.org/) and Coursera (https://www.coursera.org/) offer various Linux-related courses, including introductory and advanced courses on Linux server administration, security, and shell scripting.
  • Books:
    • "The Linux Command Line" by William Shotts is a comprehensive guide to the Linux command line, covering essential commands, shell scripting, and more.
    • "Linux Pocket Guide" by Daniel J. Barrett is a concise reference book that covers essential Linux commands, perfect for quick reference or on-the-job use.
  • Forums and online communities:
    • Stack Overflow (https://stackoverflow.com/) and Server Fault (https://serverfault.com/) are excellent Q&A platforms where you can ask questions, find answers, and share knowledge on Linux commands and server administration.
    • LinuxQuestions.org (https://www.linuxquestions.org/) is another popular forum for Linux users and administrators, offering discussions and support for various Linux distributions and topics.
  • Linux distribution documentation: Many Linux distributions have their own documentation, which can be a valuable resource for learning more about distribution-specific commands and configuration. Some popular examples include the Ubuntu documentation (https://help.ubuntu.com/) and the CentOS documentation (https://www.centos.org/docs/).

By exploring these resources and practicing your Linux command skills, you'll gain a solid foundation in Linux server administration and become more proficient in managing Linux-based systems.

Conclusion

Linux commands are an essential tool for server administrators, enabling them to effectively manage and maintain Linux-based servers. By understanding and utilizing these commands, administrators can perform a wide range of tasks, automate processes, and optimize server performance. Furthermore, using SSH for secure remote access to servers allows administrators to manage their systems remotely, while password-less logins enhance security and simplify the authentication process.

Mastering Linux commands and secure remote access techniques is a vital skill for anyone working with Linux servers. As you become more proficient in using these commands and tools, you'll be better equipped to handle various server management tasks and tackle any challenges that arise in maintaining a secure, efficient, and reliable server environment.

Updated