Server Command Line Interface: Mastering the Terminal
- Navigating the Command Line Interface
- System Services and Configuration
This chapter covers the most important aspect of Linux: the terminal. The terminal is the beating heart of Linux, enabling you to accomplish virtually anything. For the first eight years I used Linux, I relied exclusively on the terminal, never even considering a graphical interface. The terminal is reliable, quick, and efficient, making it an indispensable tool for Linux users.
Pro Tip: The terminal is always accessible. If you're stuck on a black screen or graphical interface, press Ctrl + Alt + F2
or Ctrl + Alt + F3
to switch to a terminal. To return to the graphical interface, press Ctrl + Alt + F7
.
Navigating the Command Line Interface
Videos: How to Make Bash Terminal look and feel GREAT! https://links.thelinuxbook.com/prettybash
Types of Terminals
- TTY: A terminal connected to a physical device, such as a keyboard and monitor
- GUI Terminal: A terminal emulator that provides a graphical interface for command-line operations, such as GNOME Terminal, Konsole, or xterm
TTY is used for direct interaction with the system, while GUI terminals provide a more user-friendly experience with features like tabs, copy-paste, and customizable appearance. TTY is often used for system recovery or when the graphical interface is unavailable or malfunctioning.
To access a TTY terminal, you can use the following key combinations:
Ctrl + Alt + F1
toCtrl + Alt + F6
: Switch to different TTY terminals (TTY1 to TTY6)Ctrl + Alt + F7
: Return to the graphical interface (usually TTY7)
GUI Terminals are typically launched from the applications menu or by pressing Ctrl + Alt + T
in most desktop environments or hotkey like Super + Enter
in many Tiled Window Managers (TWM).
Recommended GUI Terminals:
- GNOME Terminal: Default terminal for GNOME desktop environments, supports tabs and profiles
- Konsole: Default terminal for KDE Plasma, highly customizable with split views and profiles
- Alacritty: A fast, GPU-accelerated terminal emulator with a focus on performance and simplicity
- Kitty: A feature-rich terminal emulator with support for graphics
- Terminator: Allows multiple terminal windows in a single window, with customizable layouts
Directory Movement Commands and Examples:
cd
(change directory):cd ..
(move up a directory)cd name
(move into the specified directory)cd /
(move to the root directory)cd ~
(move to the home directory, e.g.,/home/titus
)zoxide
- A better package for navigating the file system, using fuzzy finding and remembering past directories. _Note:zoxide
is a third-party tool that can be installed via your package manager. Watch the video I did on Zoxide: https://links.thelinuxbook.com/zoxide
ls
(list files):ls -a
(show all files, including hidden ones)ls -l
(long listing format showing permissions)
rm
(remove files):rm -rf
(remove files/directories recursively and forcefully)rmdir
(remove empty directories)trash-cli
- An alternative torm
that moves files to the trash instead of permanently deleting them.
cp
(copy files):cp -r
(copy files and subdirectories recursively)rsync
- A more efficient tool for copying or syncing large amounts of files.
mv
(move files):mv file1.txt file2.txt
(rename or move files)mv /path/to/file /new/path/
(move a file to a new location)
pwd
(print working directory):- Displays the current directory path.
find
(search for files):find /path/to/search -name "filename"
(search for a file by name)find /path/to/search -type d -name "dirname"
(search for a directory by name)fd
- A faster alternative tofind
with a simpler syntax.
locate
(find files by name):locate filename
(find files by name using a pre-built index)updatedb
(update the locate database, usually run automatically by the system)
tree
(display directory structure):tree
(display the directory structure in a tree-like format)tree -L 2
(limit the depth of the tree display to 2 levels)
ln
(create links):ln -s /path/to/original /path/to/link
(create a symbolic link)ln /path/to/original /path/to/link
(create a hard link)
chmod
(change file permissions):chmod 755 file
(set permissions to read, write, and execute for owner, and read and execute for group and others)chmod +x script.sh
(make a script executable)
chown
(change file ownership):chown user:group file
(change ownership of a file to a specific user and group)chown -R user:group /path/to/directory
(change ownership recursively for a directory)
stat
(display file or filesystem status):stat file
(show detailed information about a file, including size, permissions, and timestamps)stat /path/to/directory
(show information about a directory)
du
(disk usage):du -h
(display disk usage in human-readable format)du -sh /path/to/directory
(show total size of a directory)
df
(disk space usage):df -h
(display disk space usage in human-readable format)df -i
(show inode usage instead of disk space)
Directory Layout and File System Overview
/
- Root directory/bin
- System executable files/boot
- Bootloader files/dev
- Device files (requires mounting to browse)/etc
- System configuration files/home
- User files and configuration files/media
- Mounted external media/mnt
- Temporary mount points/opt
- Optional files/root
- Root user files and configurations/tmp
- Temporary files/usr
- System resources/var
- Logs, databases, and other variable data
Most interactions with the file system occur within the /home/user
directory. This includes configuration files and executable programs. Direct editing of system-wide configuration files in /etc
or adding programs to /bin
should be done sparingly.
System Services and Configuration
Modern Linux distributions use an "init system" to control system operations, primarily systemd. Systemd manages services, boot processes, networking, and more.
Controlling Services and Units
systemctl
is the primary tool for managing services and units in systemd. Units can represent services, device drivers, network mounts, timers (similar to crontab
), and more.
Common systemctl
Commands:
systemctl status servicename
- View the current status of a service.systemctl start servicename
- Start a service.systemctl stop servicename
- Stop a service.systemctl restart servicename
- Restart a service (stop and start).systemctl reload servicename
- Reload the configuration file without restarting the service.systemctl enable servicename
- Enable a service to start at system boot.systemctl is-enabled servicename
- Check if a service is enabled at startup.systemctl is-active servicename
- Check if a service is running and active.systemctl list-units
- List all running systemd units.systemctl list-units --all
- List all units, both active and inactive.systemctl list-units --all --state=inactive
- List all inactive units.systemctl list-units --all --type=service
- List all units of type "service."
Unit File Locations
Systemd unit files are typically located in the following directories:
/usr/lib/systemd
- The main location for system-created unit files./etc/systemd/system
- Contains system-wide unit files, often symbolic links to/usr/lib/systemd
. This directory has top priority when reading unit files.~/.config/systemd/user/
- Contains user-specific unit files. This directory is not created by default and requires the--user
option for systemctl commands.
Example System Unit File
Below is an example of a system unit file:
[Unit]
Description=service_description
After=network.target
[Service]
ExecStart=path_to_executable
Type=forking
[Install]
WantedBy=default.target
For a full reference, Systemd Unit Documentation https://links.thelinuxbook.com/systemd.
User-Based Systemd Services and Unit Files
User-specific unit files are stored in the ~/.config/systemd/user/
directory. These files can be managed using the --user
option with systemctl
.
Example Command:
systemctl --user start usercreatedfile.service
This command starts a user-created service file located in the user's home directory.
Example User Unit File:
[Unit]
Description=Run service as user
DefaultDependencies=no
After=network.target
[Service]
Type=simple
User=titus
Group=users
ExecStart=/home/titus/scripts/startup_script.sh
TimeoutStartSec=0
RemainAfterExit=yes
[Install]
WantedBy=default.target
Bluetooth Configuration
To configure Bluetooth, you can use the bluetoothctl
command-line tool. This tool allows you to manage Bluetooth devices and settings directly from the terminal.
Syntax for bluetoothctl
commands:
bluetoothctl [command]
Common bluetoothctl
Commands:
power on
- Turn on the Bluetooth adapter.power off
- Turn off the Bluetooth adapter.agent on
- Enable the agent for pairing.scan on
- Start scanning for nearby Bluetooth devices.scan off
- Stop scanning for Bluetooth devices.pair <device_address>
- Pair with a specific Bluetooth device.connect <device_address>
- Connect to a paired Bluetooth device.disconnect <device_address>
- Disconnect from a connected Bluetooth device.devices
- List all known Bluetooth devices.info <device_address>
- Show detailed information about a specific Bluetooth device.
Example Usage:
bluetoothctl
power on
agent on
scan on
This will turn on the Bluetooth adapter, enable the agent for pairing, and start scanning for nearby Bluetooth devices.
Note: blueman
is a graphical Bluetooth manager that can be used as an alternative to bluetoothctl
for those who prefer a GUI.
Audio Configuration
Linux provides several command-line tools for managing audio. The two main sound systems are ALSA (Advanced Linux Sound Architecture) and PulseAudio, with PulseAudio running on top of ALSA.
PulseAudio Commands (pactl
)
The pactl
command is used to control the PulseAudio sound server:
# List audio sources and sinks
pactl list sources # List input devices
pactl list sinks # List output devices
# Volume control
pactl set-sink-volume @DEFAULT_SINK@ 50% # Set volume to 50%
pactl set-sink-mute @DEFAULT_SINK@ toggle # Toggle mute
# List loaded modules
pactl list modules
ALSA Mixer (alsamixer
)
alsamixer
is a terminal-based mixer program for ALSA:
alsamixer # Open the mixer interface
Navigation in alsamixer
:
- Arrow keys: Navigate between channels
- Up/Down: Adjust volume
- M: Toggle mute
- F6: Select sound card
- Esc: Exit
Common Audio Troubleshooting Commands
# Restart PulseAudio
pulseaudio -k # Kill the PulseAudio daemon
pulseaudio --start # Start PulseAudio
# Check audio devices
aplay -l # List all ALSA playback devices
arecord -l # List all ALSA recording devices
# Test audio output
speaker-test -c 2 # Test stereo speakers
Audio Device Management with pavucontrol
While pavucontrol
is technically a GUI application, it can be installed and launched from the terminal:
sudo apt install pavucontrol # Install on Debian/Ubuntu
pavucontrol # Launch the control interface
Pipewire Audio System
Pipewire is the modern replacement for both PulseAudio and JACK. It maintains compatibility with PulseAudio clients, so pactl
commands work with Pipewire. Additionally, Pipewire provides its own tools:
# Check Pipewire status
pw-cli status
pw-top # Show real-time audio processing graph
# List audio devices
pw-dump # Detailed info about audio devices and nodes
pw-cli list-objects # List all Pipewire objects
# Control specific nodes
pw-cli node-id # Get ID of audio nodes
pw-metadata -n settings 0 clock.force-rate 48000 # Set sample rate
# Monitor audio
pw-mon # Monitor Pipewire events in real-time
You can still use PulseAudio tools with Pipewire:
pactl
commands work as shown abovepavucontrol
works normally- ALSA applications work without modification
Note: Most modern Linux distributions are transitioning to Pipewire as their default audio system due to its improved latency, Bluetooth handling, and compatibility with both PulseAudio and JACK applications.
Typical Pipewire Package Names:
pipewire
- Core Pipewire packagepipewire-pulse
- PulseAudio compatibility layerpipewire-jack
- JACK compatibility layerpipewire-alsa
- ALSA compatibility layerwireplumber
- Session manager for Pipewire
Note: Do NOT use pipewire-media-session, as it is deprecated and replaced by wireplumber.
Remote Access and SSH
Remote access is a crucial aspect of server management. The most common method for remote access in Linux is through SSH (Secure Shell). SSH allows you to securely connect to a remote machine and execute commands as if you were physically present.
Setting Up SSH
To set up SSH on your Linux server, follow these steps:
-
Install OpenSSH Server:
sudo apt install openssh-server # Debian/Ubuntu sudo dnf install openssh-server # Fedora/RHEL sudo pacman -S openssh # Arch Linux
-
Start and Enable the SSH Service:
sudo systemctl start sshd # Start the SSH service sudo systemctl enable sshd # Enable SSH to start on boot
-
Check SSH Status:
sudo systemctl status sshd # Check the status of the SSH service
-
Configure SSH: Edit the SSH configuration file located at
/etc/ssh/sshd_config
to customize settings such as port number, allowed users, and authentication methods.sudo nano /etc/ssh/sshd_config
Common configurations include:
Port 22
(change to a different port for security)PermitRootLogin no
(disable root login for security)PasswordAuthentication yes/no
(enable or disable password authentication)
-
Restart SSH Service:
sudo systemctl restart sshd # Restart the SSH service to apply changes
For more advanced SSH configurations, you can set up key-based authentication, which is more secure than password-based authentication. To do this, generate an SSH key pair on your local machine and copy the public key to the server:
ssh-keygen
This command generates a public/private key pair. You can then copy the public key to the server using: Note: id_rsa.pub is the default public key file generated by ssh-keygen with default options.
ssh-copy-id user@server_ip -i ~/.ssh/id_rsa.pub
This command copies your public key to the server's ~/.ssh/authorized_keys
file, allowing you to log in without a password.
Connecting to a Remote Server
To connect to a remote server using SSH, use the following command:
ssh user@server_ip
Replace user
with your username on the remote server and server_ip
with the server's IP address or hostname. If you changed the SSH port, use the -p
option:
ssh -p port_number user@server_ip
Common SSH Options
-i /path/to/private_key
: Specify a private key file for authentication.-X
: Enable X11 forwarding to run graphical applications over SSH.-C
: Enable compression for faster transfers.-v
: Enable verbose mode for debugging connection issues.
SSH Configuration File
You can create a configuration file at ~/.ssh/config
to simplify SSH connections. Here’s an example configuration:
Host myserver
HostName server_ip
User user
Port 22
IdentityFile ~/.ssh/id_rsa
This allows you to connect to the server using:
ssh myserver
Remote File Transfer with SCP and SFTP
To transfer files between your local machine and a remote server, you can use scp
(Secure Copy Protocol) or sftp
(SSH File Transfer Protocol).
Using SCP
To copy a file from your local machine to a remote server:
scp /path/to/local/file user@server_ip:/path/to/remote/directory
To copy a file from a remote server to your local machine:
scp user@server_ip:/path/to/remote/file /path/to/local/directory
Using SFTP
To start an SFTP session with a remote server:
sftp user@server_ip
Once connected, you can use commands like get
, put
, ls
, and cd
to navigate and transfer files:
get remote_file.txt # Download a file from the server
put local_file.txt # Upload a file to the server
ls # List files in the current directory
cd /path/to/directory # Change directory on the server
Remote Desktop Access
For graphical remote access, you can use tools like VNC (Virtual Network Computing) or RDP (Remote Desktop Protocol). These tools allow you to access the graphical desktop environment of a remote server.
VNC allows you to remotely control a graphical desktop environment. To set up a VNC server, you can use TigerVNC or x11vnc.
Debian/Ubuntu
sudo apt update
sudo apt install tigervnc-standalone-server tigervnc-common
Fedora
sudo dnf install tigervnc-server tigervnc-server-module
Arch Linux
sudo pacman -S tigervnc
Configuration
1. Set VNC Password
vncpasswd
2. Create VNC Service Configuration
For Debian/Ubuntu and Arch:
Create a systemd service file:
sudo nano /etc/systemd/system/[email protected]
Add the following content:
[Unit]
Description=Start TigerVNC server at startup
After=syslog.target network.target
[Service]
Type=forking
User=your-username
Group=your-username
WorkingDirectory=/home/your-username
PIDFile=/home/your-username/.vnc/%H:%i.pid
ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
ExecStart=/usr/bin/vncserver -depth 24 -geometry 1024x768 -localhost :%i
ExecStop=/usr/bin/vncserver -kill :%i
[Install]
WantedBy=multi-user.target
For Fedora:
Copy the example service file:
sudo cp /lib/systemd/system/[email protected] /etc/systemd/system/vncserver@:1.service
Edit the service file:
sudo nano /etc/systemd/system/vncserver@:1.service
Replace <USER>
with your username in the file.
3. Configure VNC Startup Script
Create or edit the VNC startup script:
nano ~/.vnc/xstartup
Add the following content:
#!/bin/bash
xrdb $HOME/.Xresources
startxfce4 &
Make it executable:
chmod +x ~/.vnc/xstartup
Starting VNC Server
Manual Start
vncserver :1 -geometry 1024x768 -depth 24 -localhost
Using Systemd (recommended)
# Enable and start the service
sudo systemctl enable vncserver@:1.service
sudo systemctl start vncserver@:1.service
# Check status
sudo systemctl status vncserver@:1.service
Connecting to VNC
Local Connection
vncviewer localhost:5901
SSH Tunnel (recommended for remote access)
ssh -L 5901:localhost:5901 username@remote-server
# Then connect to localhost:5901
Security Considerations
- Always use SSH tunneling for remote connections
- Bind to localhost only using the
-localhost
option - Use strong passwords with
vncpasswd
- Consider using x11vnc for sharing existing X sessions instead of creating new ones
Troubleshooting
Check VNC server status
vncserver -list
Kill VNC session
vncserver -kill :1
View VNC logs
tail -f ~/.vnc/*.log
Common Issues
- Display not starting: Check
~/.vnc/xstartup
permissions and desktop environment availability - Connection refused: Verify firewall settings and that VNC is listening on the correct port
- Black screen: Ensure your desktop environment is properly configured in the startup script
Alternative: x11vnc for Existing Sessions
If you want to share your current desktop session instead of creating a new one:
Installation
# Debian/Ubuntu
sudo apt install x11vnc
# Fedora
sudo dnf install x11vnc
# Arch
sudo pacman -S x11vnc
Usage
x11vnc -display :0 -auth ~/.Xauthority -localhost -rfbauth ~/.vnc/passwd
LAMP Stack (Linux, Apache, MySQL, PHP) Website Setup
The LAMP stack is a popular web server configuration that includes Linux, Apache, MySQL (or MariaDB), and PHP. This stack is widely used for hosting dynamic websites and web applications.
Installing the LAMP Stack
Debian/Ubuntu
# Update package index
sudo apt update
# Install Apache
sudo apt install apache2
# Install MariaDB (MySQL alternative)
sudo apt install mariadb-server
# Install PHP and common modules
sudo apt install php libapache2-mod-php php-mysql php-cli php-curl php-gd php-mbstring php-xml php-zip
# Enable Apache modules
sudo a2enmod rewrite
sudo systemctl restart apache2
# Secure MariaDB installation
sudo mysql_secure_installation
# Start and enable services
sudo systemctl enable apache2
sudo systemctl enable mariadb
sudo systemctl start apache2
sudo systemctl start mariadb
Fedora/RHEL
# Update system
sudo dnf update
# Install Apache
sudo dnf install httpd
# Install MariaDB
sudo dnf install mariadb-server
# Install PHP and modules
sudo dnf install php php-mysqlnd php-cli php-curl php-gd php-mbstring php-xml php-zip
# Start and enable services
sudo systemctl enable httpd
sudo systemctl enable mariadb
sudo systemctl start httpd
sudo systemctl start mariadb
# Secure MariaDB installation
sudo mysql_secure_installation
# Configure firewall
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
Arch Linux
# Update system
sudo pacman -Syu
# Install Apache
sudo pacman -S apache
# Install MariaDB
sudo pacman -S mariadb
# Install PHP and modules
sudo pacman -S php php-apache php-mysql php-gd php-curl
# Initialize MariaDB
sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
# Configure PHP with Apache
sudo nano /etc/httpd/conf/httpd.conf
# Add these lines:
# LoadModule php_module modules/libphp.so
# AddHandler php-script .php
# Include conf/extra/php_module.conf
# Start and enable services
sudo systemctl enable httpd
sudo systemctl enable mariadb
sudo systemctl start httpd
sudo systemctl start mariadb
# Secure MariaDB installation
sudo mysql_secure_installation
Testing the LAMP Stack
Test PHP installation
echo "" | sudo tee /var/www/html/info.php
Create a test database (optional)
sudo mysql -u root -p
# CREATE DATABASE testdb;
# CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
# GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
# FLUSH PRIVILEGES;
# EXIT;
Set proper permissions
# Set ownership of the web directory
sudo chown -R www-data:www-data /var/www/html # Debian/Ubuntu
sudo chown -R apache:apache /var/www/html # Fedora/Arch
Access the test page
Open a web browser and navigate to http://your_server_ip/info.php
. You should see the PHP information page, confirming that PHP is working correctly with Apache.
Remove the test page
sudo rm /var/www/html/info.php
Enable HTTPS in Apache
To enable HTTPS, you need to install an SSL certificate. You can use Let's Encrypt for free SSL certificates.
Install Certbot
# Debian/Ubuntu
sudo apt install certbot python3-certbot-apache
# Fedora/RHEL
sudo dnf install certbot python3-certbot-apache
# Arch Linux
sudo pacman -S certbot certbot-apache
Obtain and Install SSL Certificate
sudo certbot --apache -d your_domain.com -d www.your_domain.com
This command will automatically configure Apache to use the SSL certificate. Follow the prompts to complete the installation.
Verify SSL Configuration
After obtaining the SSL certificate, you can verify the configuration by accessing your website using https://your_domain.com
. You should see a secure connection with a padlock icon in the browser's address bar.
Renew SSL Certificate
Let's Encrypt certificates are valid for 90 days. To renew the certificate automatically, you can set up a cron job or use the systemd timer.
# Test renewal process
sudo certbot renew --dry-run
Set up a cron job for automatic renewal
# Open the crontab editor
crontab -e
# Add the following line to run the renewal command daily
0 0 * * * /usr/bin/certbot renew --quiet
Finding IP Address and Hostname
To find your server's IP address and hostname, you can use the following commands:
# Find IP address
curl ifconfig.me # Get the public IP address
curl ipinfo.io/ip # Another way to get the public IP address
ip addr show # Show all network interfaces and their IP addresses
ip a # Shorter version of the above command
ip route get 1 # Get the default route and associated IP address
# Find private IP address
hostname -I # Get the private IP address(es) of the server
Find hostname
hostname # Get the hostname
hostname -f # Get the fully qualified domain name (FQDN)