Skip to content
Author Nejat Hakan
eMail nejat.hakan@outlook.de
PayPal Me https://paypal.me/nejathakan


Linux Networking Intermediate - Configuration and Services

Introduction

In the previous chapter, we learned the fundamental concepts and how to view our network configuration using tools like ip and ping. Now, it's time to take the next step. How do we make these settings permanent? How do we interact with other machines securely? What tools can help us diagnose problems beyond a simple ping?

This chapter builds directly on the basics. We'll explore how Linux systems typically manage persistent network configurations, introduce essential network services like SSH for remote access, and equip you with more sophisticated troubleshooting tools. We'll also touch upon the critical concept of firewalls for basic network security. By the end of this chapter, you'll be able to configure your network settings reliably, access other Linux systems remotely, and use common utilities to understand network traffic flow and listening services.

We will cover:

  1. Persistent Network Configuration: Using NetworkManager (nmcli) and traditional methods (/etc/network/interfaces).
  2. DHCP (Dynamic Host Configuration Protocol): Automatic configuration.
  3. Essential Network Services: SSH (Secure Shell) for remote login and scp for secure file transfer.
  4. Intermediate Troubleshooting Tools: ss/netstat (Network Statistics), traceroute/tracepath (Path Discovery), dig/nslookup (DNS Querying).
  5. Basic Firewall Concepts: Understanding ports and using ufw (Uncomplicated Firewall).

Let's learn how to manage and interact with our network more effectively.

Prerequisites:

  • Understanding of concepts from Chapter 1 (IP, Mask, Gateway, DNS, ip, ping).
  • A Linux system (Virtual Machine recommended for configuration changes).
  • Root or sudo privileges are required for configuration changes and installing packages.
  • Potentially a second Linux system (or VM) for practicing SSH/SCP, although loopback tests are possible.

1. Persistent Network Configuration: Making Settings Stick

In Chapter 1, we saw how to view settings. Often, these settings are acquired automatically via DHCP (more on that soon). But what if you need to set a static IP address that doesn't change, or manually configure DNS servers? We need a way to make these settings survive a reboot. There are two primary methods commonly found in Linux distributions:

  • Method 1: NetworkManager (Modern Desktop/Server)

    • What is it? NetworkManager is a dynamic network control and configuration system that aims to keep network devices and connections up and active when available. It's the default on most modern desktop Linux distributions (Ubuntu, Fedora, CentOS/RHEL GUI) and many servers.
    • Why use it? It handles complex scenarios well (multiple interfaces, Wi-Fi, VPNs, mobile broadband), provides graphical applets, and offers a powerful command-line tool (nmcli).
    • Using nmcli (Command Line Interface):
      • List Devices: See physical network devices recognized by NetworkManager.
        nmcli device status
        # Or shorter: nmcli dev status
        
      • List Connections: See configured network profiles (which can be applied to devices).
        nmcli connection show
        # Or shorter: nmcli con show
        
        You'll likely see a connection name associated with your active interface (e.g., Wired connection 1, MyWifiNetwork).
      • View Connection Details: Show all settings for a specific connection profile.
        nmcli connection show "<connection_name>"
        # Example: nmcli con show "Wired connection 1"
        
        Scroll through this output to see ipv4.method (auto/dhcp or manual), ipv4.addresses, ipv4.gateway, ipv4.dns, etc.
      • Modifying a Connection (Example: Setting Static IP): Let's change the active connection named "Wired connection 1" on interface eth0 to use a static IP.
        # Find your active connection name first using 'nmcli con show'
        CONN_NAME="Wired connection 1" # Replace with your actual connection name
        IFACE_NAME="eth0"             # Replace with your actual interface name
        STATIC_IP="192.168.1.150/24"  # Choose an available IP in your subnet
        GATEWAY_IP="192.168.1.1"      # Your gateway IP
        DNS_SERVERS="8.8.8.8,1.1.1.1" # Google & Cloudflare DNS
        
        # 1. Change method from auto (DHCP) to manual (static)
        sudo nmcli connection modify "$CONN_NAME" ipv4.method manual
        
        # 2. Set the IP address and subnet mask (CIDR)
        sudo nmcli connection modify "$CONN_NAME" ipv4.addresses "$STATIC_IP"
        
        # 3. Set the default gateway
        sudo nmcli connection modify "$CONN_NAME" ipv4.gateway "$GATEWAY_IP"
        
        # 4. Set the DNS servers (comma-separated)
        sudo nmcli connection modify "$CONN_NAME" ipv4.dns "$DNS_SERVERS"
        
        # 5. (Optional) Make the connection auto-connect on boot
        sudo nmcli connection modify "$CONN_NAME" connection.autoconnect yes
        
        # 6. Apply the changes by bringing the connection down and up
        sudo nmcli connection down "$CONN_NAME"
        sudo nmcli connection up "$CONN_NAME"
        
        # 7. Verify the changes
        ip addr show dev "$IFACE_NAME"
        ip route show
        cat /etc/resolv.conf
        
      • Switching back to DHCP:
        sudo nmcli connection modify "$CONN_NAME" ipv4.method auto
        # Clear manual settings (optional but good practice)
        sudo nmcli connection modify "$CONN_NAME" ipv4.addresses ""
        sudo nmcli connection modify "$CONN_NAME" ipv4.gateway ""
        sudo nmcli connection modify "$CONN_NAME" ipv4.dns ""
        # Reactivate
        sudo nmcli connection down "$CONN_NAME"
        sudo nmcli connection up "$CONN_NAME"
        
  • Method 2: /etc/network/interfaces (Traditional Debian/Ubuntu Server)

    • What is it? This is the classic method used by Debian, Ubuntu (especially server versions), and derivatives. Network configuration is defined directly in the /etc/network/interfaces text file, often in conjunction with helper scripts like ifup and ifdown.
    • Why use it? It's simple, declarative, and doesn't rely on a running daemon like NetworkManager. Often preferred for servers where network settings rarely change. Note: If NetworkManager is active, it might control interfaces even if this file exists. Distributions often use one method or the other by default. Check your system documentation.
    • Editing /etc/network/interfaces: You need root privileges to edit this file (e.g., sudo nano /etc/network/interfaces).
    • Example: DHCP Configuration:
      # This file describes the network interfaces available on your system
      # and how to activate them. For more information, see interfaces(5).
      
      source /etc/network/interfaces.d/*
      
      # The loopback network interface
      auto lo
      iface lo inet loopback
      
      # The primary network interface (e.g., eth0) configured via DHCP
      auto eth0
      iface eth0 inet dhcp
      
      • auto <interface>: Bring this interface up automatically at boot time.
      • iface <interface> inet dhcp: Configure this interface using DHCP.
    • Example: Static IP Configuration:
      # ... (loopback section as above) ...
      
      # The primary network interface (e.g., eth0) with static config
      auto eth0
      iface eth0 inet static
          address 192.168.1.150
          netmask 255.255.255.0
          # Or use CIDR notation (newer ifupdown versions): address 192.168.1.150/24
          gateway 192.168.1.1
          dns-nameservers 8.8.8.8 1.1.1.1
          # Optional: dns-search mydomain.local
      
      • iface <interface> inet static: Indicates static configuration.
      • address: The static IP address.
      • netmask: The subnet mask (or use CIDR on the address line).
      • gateway: The default gateway IP.
      • dns-nameservers: Space-separated list of DNS server IPs (requires the resolvconf package to be installed and properly configured to update /etc/resolv.conf).
    • Applying Changes: After saving the file, you typically need to bring the interface down and then up again:
      sudo ifdown eth0
      sudo ifup eth0
      # Or restart networking service (methods vary)
      # sudo systemctl restart networking # Systemd based
      # sudo service networking restart # Older init systems
      
    • Verification: Use ip addr, ip route, cat /etc/resolv.conf as before.

2. DHCP (Dynamic Host Configuration Protocol): Automatic Configuration

  • What is it? Instead of manually setting an IP, subnet mask, gateway, and DNS on every single device, DHCP allows devices to request and obtain this information automatically from a central DHCP server on the network.
  • Why use it? It drastically simplifies network administration, especially in large networks or networks where devices frequently join and leave (like Wi-Fi). It prevents IP address conflicts by managing a pool of available addresses. Your home router usually acts as a DHCP server for your local network.
  • How it works (Simplified):
    1. Discover: When a device boots up or connects (and is configured for DHCP), it broadcasts a "DHCP Discover" message ("Is there a DHCP server out there?").
    2. Offer: A DHCP server on the network hears the broadcast and replies with a "DHCP Offer" message ("I'm a DHCP server, and here's an IP address configuration you could use: IP, mask, lease time, gateway, DNS...").
    3. Request: The client receives one or more offers and chooses one. It broadcasts a "DHCP Request" message ("I'd like to accept the offer from server X").
    4. Acknowledge (ACK): The chosen DHCP server confirms the assignment with a "DHCP Acknowledge" message ("Okay, that IP configuration is yours for this lease duration"). The server records the lease.
  • Client Configuration: As seen above, you configure a client to use DHCP by setting the method to auto (NetworkManager) or dhcp (/etc/network/interfaces).

3. Essential Network Services: SSH and SCP

Once basic connectivity is established, you'll often want to interact with other machines. Secure Shell (SSH) is the standard way to do this in the Linux/Unix world.

  • SSH (Secure Shell): Remote Command Execution

    • What is it? SSH provides a secure (encrypted) channel over an unsecured network (like the internet) to log into and execute commands on a remote machine. It replaces older, insecure protocols like Telnet and rlogin.
    • Why use it? Securely manage servers, access your workstation from home, automate tasks on multiple machines.
    • Components:
      • SSH Server (sshd): A daemon (background service) that runs on the machine you want to connect to. It listens for incoming connections (typically on TCP port 22) and handles authentication and encryption.
      • SSH Client (ssh): A command-line tool you run on your local machine to connect from.
    • Basic Usage:
      ssh <username>@<remote_hostname_or_ip>
      # Example: ssh student@192.168.1.200
      # Example: ssh admin@server.example.com
      
    • First Connection: The first time you connect to a new server, the client will show the server's public key fingerprint and ask if you want to continue connecting. Type yes. This fingerprint gets stored in ~/.ssh/known_hosts on your client machine. If the server's key changes later (which could indicate a man-in-the-middle attack, or just a server reinstall), the client will warn you.
    • Authentication: Usually done via password (you'll be prompted) or, more securely and conveniently, using SSH key pairs (public/private keys). Key-based authentication is beyond this intermediate scope but highly recommended for regular use.
    • Server Installation: On the machine you want to connect to, you need to install and enable the SSH server.
      • Debian/Ubuntu: sudo apt update && sudo apt install openssh-server then sudo systemctl enable --now sshd (or ssh).
      • Fedora/CentOS/RHEL: sudo dnf install openssh-server then sudo systemctl enable --now sshd.
  • SCP (Secure Copy): Secure File Transfer

    • What is it? SCP uses SSH to securely transfer files between hosts.
    • Why use it? To copy configuration files, deployment packages, log files, etc., between machines without exposing data.
    • Basic Usage:
      • Copy local file to remote host:
        scp /path/to/local/file <username>@<remote_host>:/path/to/remote/destination/
        # Example: scp my_script.sh student@192.168.1.200:/home/student/scripts/
        
      • Copy remote file to local host:
        scp <username>@<remote_host>:/path/to/remote/file /path/to/local/destination/
        # Example: scp student@192.168.1.200:/var/log/syslog ./downloaded_logs/
        
      • Copy directory recursively (-r flag):
        scp -r /path/to/local/directory <username>@<remote_host>:/path/to/remote/parent_dir/
        # Example: scp -r ./my_project student@192.168.1.200:/home/student/
        

4. Intermediate Troubleshooting Tools

When ping isn't enough, these tools provide more detailed insights.

  • ss (Socket Statistics): The Modern netstat

    • What is it? ss is a utility used to dump socket statistics. It can display TCP, UDP, RAW, and UNIX domain sockets. It's generally faster and provides more information than the older netstat command (though netstat is still often available).
    • Why use it? To see which network services are listening for incoming connections on your machine, view established connections, check which process is using a particular port.
    • Common Options:
      • ss -t: Show TCP sockets.
      • ss -u: Show UDP sockets.
      • ss -l: Show only listening sockets.
      • ss -p: Show the process (program) using the socket (often requires sudo).
      • ss -n: Do not resolve service names (show port numbers instead of names like 'http').
      • ss -a: Show both listening and non-listening (e.g., established) sockets.
      • Combining options:
        sudo ss -tulnp # Show TCP & UDP Listening sockets with Process names & Numeric ports
        sudo ss -tnp   # Show established/active TCP connections with Process & Numeric ports
        
    • Output: Look for LISTEN state for servers waiting for connections, and ESTAB state for active connections. The Local Address:Port and Peer Address:Port columns show the source and destination of connections.
  • traceroute / tracepath: Tracing the Path

    • What is it? These tools attempt to trace the route that network packets take to reach a specific destination host. They work by sending packets with increasing Time-To-Live (TTL) values. Each router along the path decrements the TTL; when TTL reaches zero, the router sends back an ICMP "Time Exceeded" message, revealing its IP address.
    • Why use it? To identify where network slowdowns or failures are occurring along the path between your machine and a destination.
    • Differences:
      • traceroute: The classic tool. Often uses UDP packets by default (can vary) and usually requires root privileges. Offers more options for fine-tuning.
      • tracepath: A simpler tool, often available without root. Uses UDP. It also discovers the Path MTU along the way. Generally recommended if you don't need traceroute's advanced options.
    • Basic Usage:
      tracepath <destination_hostname_or_ip>
      # Example: tracepath www.google.com
      
      # Or using traceroute (might need install: sudo apt install traceroute / sudo dnf install traceroute)
      traceroute <destination_hostname_or_ip>
      # Example: traceroute 8.8.8.8
      
    • Output: Shows a list of "hops" (routers) along the path, along with the round-trip time to each hop. Asterisks (* * *) indicate that no response was received from that hop within the timeout period (could be due to firewall rules or network issues).
  • dig / nslookup: DNS Querying

    • What is it? Tools specifically designed to query DNS servers. dig (Domain Information Groper) is generally considered more powerful and standard on Linux than nslookup.
    • Why use it? To troubleshoot DNS resolution problems, check specific DNS record types (like MX for mail servers, TXT for verification records), query specific DNS servers.
    • Basic Usage:
      • dig:
        dig <hostname>
        # Example: dig www.wikipedia.org
        
        # Query for a specific record type (e.g., MX):
        dig wikipedia.org MX
        
        # Query a specific DNS server:
        dig @8.8.8.8 www.wikipedia.org
        
        • Look for the ANSWER SECTION in the output for the resolved IP(s) or other records. Check the status: NOERROR (success) or other statuses (e.g., NXDOMAIN - Non-Existent Domain).
      • nslookup:
        nslookup <hostname>
        # Example: nslookup www.kernel.org
        
        # Query a specific DNS server:
        nslookup www.kernel.org 1.1.1.1
        
        • Shows the server used for the query and the resulting address(es).

5. Basic Firewall Concepts: Protecting Your System

  • What is a Firewall? A firewall acts like a security guard for your network connection. It inspects incoming and outgoing network traffic and decides whether to allow or block it based on a set of predefined rules.
  • Why use it? To prevent unauthorized access to your machine, block malicious traffic, and limit the network exposure of your services. Even if a service has a vulnerability, the firewall can prevent attackers from reaching it.
  • Ports: Network services "listen" for incoming connections on specific numerical ports (0-65535). For example, web servers typically listen on port 80 (HTTP) and 443 (HTTPS), while SSH listens on port 22. The firewall rules often specify which ports should be open (allow traffic) and which should be closed (block traffic).
  • ufw (Uncomplicated Firewall): A User-Friendly Frontend
    • What is it? ufw provides a simpler, more user-friendly command-line interface for managing Linux firewall rules. Underneath, it typically uses the standard iptables or nftables kernel infrastructure. It's often the default firewall tool on Ubuntu.
    • Installation: sudo apt update && sudo apt install ufw (if not already present).
    • Basic Usage:
      • Check Status:
        sudo ufw status verbose
        
        (inactive means it's not running).
      • Enable Firewall: (Sets default policy to DENY incoming, ALLOW outgoing)
        sudo ufw enable
        
        (Warning: Enabling a firewall over SSH without allowing SSH first will lock you out! Always allow SSH before enabling.)
      • Disable Firewall:
        sudo ufw disable
        
      • Allowing Traffic:
        # Allow incoming traffic on a specific port (e.g., SSH)
        sudo ufw allow 22/tcp  # Allow TCP traffic on port 22
        # Or use the service name (if defined in /etc/services)
        sudo ufw allow ssh
        
        # Allow traffic from a specific IP address
        sudo ufw allow from 192.168.1.100
        
        # Allow traffic from a specific IP to a specific port
        sudo ufw allow from 192.168.1.100 to any port 80 proto tcp
        
      • Denying Traffic:
        sudo ufw deny 1234/udp # Deny UDP traffic on port 1234
        
      • Deleting Rules:
        sudo ufw status numbered # Show rules with numbers
        sudo ufw delete <rule_number> # Delete rule by number
        # Or delete by specification:
        sudo ufw delete allow ssh
        
      • Default Policies:
        sudo ufw default deny incoming
        sudo ufw default allow outgoing
        sudo ufw default allow routed # If using as a router
        

Conclusion

You've now moved beyond simply viewing network settings. You can configure persistent static or DHCP addresses using common Linux methods (nmcli, /etc/network/interfaces). You understand the importance of SSH for secure remote administration and scp for file transfers. Furthermore, you're equipped with essential troubleshooting tools like ss, traceroute/tracepath, and dig to diagnose connection issues and DNS problems. Finally, you have a grasp of basic firewall concepts and how to use ufw to protect your system.

These intermediate skills are crucial for effectively managing and maintaining Linux systems in networked environments. Let's apply some of these in the workshop.


Workshop: Static IP Configuration and Remote Access

Goal:

To configure a persistent static IP address on your Linux machine using nmcli (or fallback to /etc/network/interfaces if nmcli is unavailable/unsuitable). Then, install an SSH server, enable the firewall allowing SSH access, and connect to the machine via SSH from itself (loopback) or from another machine if available. Finally, copy a file using scp.

Scenario:

You need to set up a Linux server (or your workstation) with a fixed IP address so other devices can reliably connect to it. You also need to enable secure remote access via SSH and ensure the firewall permits this access while blocking other unwanted connections.

Prerequisites:

  • A Linux system (VM highly recommended).
  • Root or sudo privileges.
  • Network connectivity.
  • Determine your local network range (e.g., 192.168.1.x) and gateway IP (from Workshop 1 or ip route). Choose a static IP address within that range that is not currently in use and is outside the typical DHCP pool if possible (e.g., use .150 if DHCP assigns .100-.149).
  • Know your primary network interface name (e.g., eth0, enp0s3).
  • (Optional but recommended) A second machine (Linux/macOS/Windows with an SSH client like PuTTY) on the same network to test SSH/SCP from a different host.

Part 1: Static IP Configuration (Using nmcli)

(If your system uses /etc/network/interfaces primarily, skip to Part 1 Alternate below)

1. Identify Connection and Interface:

nmcli device status # Note your primary interface name (e.g., eth0)
nmcli connection show # Note the active connection name for that interface
  • Explanation: We confirm the interface name and the NetworkManager connection profile associated with it. Record these.

2. Define Network Parameters:

Set shell variables for clarity (replace with your actual values).

# --- BEGIN USER CONFIGURATION ---
CONN_NAME="Wired connection 1" # Replace with your connection name from step 1
IFACE_NAME="eth0"             # Replace with your interface name from step 1
STATIC_IP="192.168.1.150/24"  # Choose an available static IP + CIDR mask
GATEWAY_IP="192.168.1.1"      # Your network's gateway IP
DNS_SERVERS="8.8.8.8,1.1.1.1" # Example: Google & Cloudflare DNS
# --- END USER CONFIGURATION ---
  • Explanation: We store our desired network settings in variables to make the following commands easier to read and modify. Ensure these values are correct for your network!

3. Configure Static Settings:

echo "Applying static configuration to '$CONN_NAME'..."
sudo nmcli connection modify "$CONN_NAME" ipv4.method manual
sudo nmcli connection modify "$CONN_NAME" ipv4.addresses "$STATIC_IP"
sudo nmcli connection modify "$CONN_NAME" ipv4.gateway "$GATEWAY_IP"
sudo nmcli connection modify "$CONN_NAME" ipv4.dns "$DNS_SERVERS"
sudo nmcli connection modify "$CONN_NAME" connection.autoconnect yes
  • Explanation: We use nmcli connection modify to change the connection profile: set the method to manual (static), assign the IP address/mask, gateway, and DNS servers. We also ensure it tries to connect automatically.

4. Apply Changes:

echo "Reactivating connection '$CONN_NAME'..."
sudo nmcli connection down "$CONN_NAME"
# Wait a second or two for the interface to fully go down
sleep 2
sudo nmcli connection up "$CONN_NAME"
  • Explanation: We take the connection profile down and bring it back up to apply the newly saved settings.

5. Verify Configuration:

echo "Verifying settings for interface $IFACE_NAME..."
ip addr show dev "$IFACE_NAME" | grep inet # Should show your static IP
ip route show | grep default            # Should show your gateway
cat /etc/resolv.conf | grep nameserver  # Should show your DNS servers
  • Explanation: We use standard commands to confirm the IP address, default route, and DNS servers are now set to the static values we configured.

6. Test Connectivity:

ping -c 3 "$GATEWAY_IP" # Test gateway reachability
ping -c 3 8.8.8.8      # Test internet IP reachability
ping -c 3 www.google.com # Test DNS and internet reachability
  • Explanation: Perform basic ping tests to ensure the static configuration allows network access. If pings fail, double-check the IP, mask, and gateway settings you applied.

(Proceed to Part 2)


Part 1 Alternate: Static IP Configuration (Using /etc/network/interfaces)

(Use this part only if your system primarily uses this method, e.g., older Debian/Ubuntu server, or if NetworkManager is not installed/used)

1. Define Network Parameters:

Choose your settings (replace with your actual values).

# --- BEGIN USER CONFIGURATION ---
IFACE_NAME="eth0"             # Replace with your interface name
STATIC_IP="192.168.1.150"     # Choose an available static IP
NETMASK="255.255.255.0"       # Corresponding subnet mask
# Or use CIDR: STATIC_IP_CIDR="192.168.1.150/24"
GATEWAY_IP="192.168.1.1"      # Your network's gateway IP
DNS_SERVERS="8.8.8.8 1.1.1.1" # Space-separated DNS servers
# --- END USER CONFIGURATION ---
  • Explanation: Define the necessary parameters for your static configuration.

2. Edit the Interfaces File:

sudo cp /etc/network/interfaces /etc/network/interfaces.backup # Backup first!
sudo nano /etc/network/interfaces # Or use vim, gedit, etc.
  • Explanation: Always back up configuration files before editing. Open the file with a text editor using sudo.

3. Configure the Interface:

Find the section for your interface (e.g., iface eth0 inet dhcp). Comment out or delete the DHCP line(s) and add the static configuration. It should look something like this:

# Comment out or remove existing DHCP line for the interface:
# iface eth0 inet dhcp

# Add static configuration:
auto eth0
iface eth0 inet static
    address 192.168.1.150
    netmask 255.255.255.0
    # Alternatively, if supported: address 192.168.1.150/24
    gateway 192.168.1.1
    dns-nameservers 8.8.8.8 1.1.1.1
  • Explanation: Replace the example values with your defined parameters. Ensure auto <IFACE_NAME> exists to bring it up on boot. iface <IFACE_NAME> inet static declares static mode. address, netmask (or CIDR), gateway, and dns-nameservers define the settings. (Note: dns-nameservers relies on the resolvconf package being functional). Save and close the editor.

4. Apply Changes:

echo "Applying changes to interface $IFACE_NAME..."
sudo ifdown "$IFACE_NAME"
sleep 2
sudo ifup "$IFACE_NAME"
# If ifdown/ifup doesn't work or apply DNS, try restarting the service:
# sudo systemctl restart networking # Or sudo service networking restart
  • Explanation: Use ifdown and ifup to reread the configuration file and apply it to the interface. Sometimes restarting the whole service is needed.

5. Verify Configuration and Test Connectivity:

Follow steps 5 and 6 from the nmcli section above to verify using ip addr, ip route, cat /etc/resolv.conf, and ping.


Part 2: Setting up SSH and Firewall

1. Install SSH Server:

# Debian/Ubuntu:
sudo apt update && sudo apt install -y openssh-server

# Fedora/CentOS/RHEL:
# sudo dnf update && sudo dnf install -y openssh-server
  • Explanation: Install the OpenSSH server package, which provides the sshd service.

2. Enable and Start SSH Service:

sudo systemctl enable sshd # Enable it to start on boot
sudo systemctl start sshd  # Start it now
sudo systemctl status sshd # Check that it's active (running)
  • Explanation: We ensure the SSH server starts automatically when the system boots and start it immediately. We then check its status.

3. Install and Configure Firewall (UFW):

# Install UFW (if not installed, common on Ubuntu)
# sudo apt update && sudo apt install -y ufw

# VERY IMPORTANT: Allow SSH traffic BEFORE enabling the firewall!
sudo ufw allow ssh # Allows traffic on port 22/tcp
# Or explicitly: sudo ufw allow 22/tcp

# Enable the firewall
sudo ufw enable # Answer 'y' to the prompt

# Check the status - should show active and rule for ssh
sudo ufw status verbose
  • Explanation: We install ufw if needed. Crucially, we add a rule to allow incoming SSH connections (ssh maps to port 22/tcp). Only after allowing SSH do we enable the firewall. Enabling ufw typically sets the default policy to deny incoming traffic, so the allow ssh rule is essential for remote access.

Part 3: Testing Remote Access

1. Test SSH Locally (Loopback):

Find your username with whoami.

MY_USER=$(whoami)
MY_IP="127.0.0.1" # Use loopback address for local test
echo "Attempting SSH connection to $MY_USER@$MY_IP..."
ssh "$MY_USER@$MY_IP"
# Type 'yes' if prompted about authenticity.
# Enter your user password when prompted.
# Once logged in, type 'exit' to close the SSH session.
  • Explanation: We try to SSH into the machine from itself using the loopback address. This verifies the sshd server is running, accepting connections, and authentication works.

2. Test SSH Remotely (Optional - Requires Second Machine):

On your second machine (the client), open a terminal or SSH client (like PuTTY on Windows). Use the static IP address you configured in Part 1.

# On the OTHER machine:
ssh <your_username>@<static_ip_configured_in_part_1>
# Example: ssh student@192.168.1.150
# Type 'yes' if prompted, enter password.
# Type 'exit' when done.
  • Explanation: This tests if you can connect from another device over the network, verifying the static IP and firewall rule work correctly. If this fails but the local test worked, check firewalls on both machines and ensure the static IP is correct and reachable on the network.

3. Test Secure Copy (SCP):

  • Create a test file on the machine where you set the static IP (the "server"):
    # On the SERVER machine (where SSHD is running):
    echo "This is a test file for SCP." > ~/scp_test.txt
    echo "File created at ~/scp_test.txt"
    
  • Copy the file FROM the server TO your client machine:
    # On the CLIENT machine (or locally if testing loopback):
    # Define server IP and user (replace with actual values)
    SERVER_IP="192.168.1.150" # The static IP you set
    SERVER_USER="student"     # The username on the server
    
    echo "Attempting to copy file from server..."
    # Create a destination directory if needed: mkdir ~/Downloads
    scp "$SERVER_USER@$SERVER_IP":~/scp_test.txt ~/Downloads/
    # Enter password when prompted.
    
    echo "Checking if file was copied:"
    ls -l ~/Downloads/scp_test.txt
    cat ~/Downloads/scp_test.txt
    
  • Explanation: We first create a simple text file on the server. Then, from the client machine (or using the loopback address 127.0.0.1 or the static IP if testing locally), we use scp to securely copy that file over SSH to the client's ~/Downloads directory. We verify the file arrived and has the correct content.

Workshop Cleanup (Optional - Revert to DHCP):

If you want to revert the static IP configuration back to DHCP:

  • Using nmcli:
    # Use the same CONN_NAME as before
    sudo nmcli connection modify "$CONN_NAME" ipv4.method auto
    sudo nmcli connection modify "$CONN_NAME" ipv4.addresses ""
    sudo nmcli connection modify "$CONN_NAME" ipv4.gateway ""
    sudo nmcli connection modify "$CONN_NAME" ipv4.dns ""
    sudo nmcli connection down "$CONN_NAME" ; sleep 2 ; sudo nmcli connection up "$CONN_NAME"
    echo "Reverted '$CONN_NAME' to DHCP. Verify with 'ip a' and 'ip route'."
    
  • Using /etc/network/interfaces:
    sudo nano /etc/network/interfaces # Or editor of choice
    # Comment out the static lines, uncomment/add the DHCP line:
    # auto eth0
    # iface eth0 inet static
    #     address ...
    #     netmask ...
    #     gateway ...
    #     dns-nameservers ...
    auto eth0
    iface eth0 inet dhcp
    
    # Apply changes
    sudo ifdown "$IFACE_NAME" ; sleep 2 ; sudo ifup "$IFACE_NAME"
    echo "Reverted '$IFACE_NAME' to DHCP in interfaces file. Verify."
    
  • Disable Firewall (Optional):
    sudo ufw disable
    
  • Stop/Disable SSH (Optional):
    sudo systemctl stop sshd
    sudo systemctl disable sshd
    

Workshop Conclusion:

Well done! You have successfully configured a persistent static IP address on a Linux system, making it reliably accessible on the network. You also installed and enabled the essential SSH service for secure remote access and file transfer (scp), and configured the ufw firewall to allow SSH while maintaining a basic level of security. These are core skills for managing any Linux machine that needs to provide or access network services.