Linux: Troubleshooting network connectivity issues

Troubleshooting network connectivity issues in Linux involves identifying and diagnosing the root cause of the problem by checking various network components and configurations. Here’s a systematic approach to troubleshoot network connectivity issues in Linux:

  1. Check Physical Connections:
    • Ensure that all network cables are securely connected, and network interfaces (Ethernet, Wi-Fi) are properly seated in their respective ports.
  2. Verify Network Interface Status:
    • Use the ip or ifconfig command to check the status of network interfaces.ip addr show orcssCopy codeifconfig -a
    • Ensure that the network interface is up (UP state) and has an IP address assigned.
  3. Check IP Configuration:
    • Use the ip or ifconfig command to verify the IP address, subnet mask, gateway, and DNS server settings of the network interface.
    • Ensure that the IP configuration is correct and matches the network configuration of your environment.
  4. Verify DNS Resolution:
    • Use the ping command to test DNS resolution by pinging a domain name.ping example.com
    • If DNS resolution fails, check the /etc/resolv.conf file for correct DNS server configurations and try using alternative DNS servers.
  5. Test Local Network Connectivity:
    • Use the ping command to test connectivity to other devices on the local network by pinging their IP addresses.ping <IP_address>
    • If local pings fail, check the network configuration of the local device, including IP address, subnet mask, and gateway settings.
  6. Check Firewall Settings:
    • Disable the firewall temporarily using the appropriate command for your firewall software (e.g., ufw disable for Uncomplicated Firewall).
    • If network connectivity improves after disabling the firewall, adjust firewall rules to allow necessary network traffic.
  7. Inspect Routing Table:
    • Use the ip route command to view the routing table and ensure that the default gateway is configured correctly.ip route show
    • If necessary, add or modify routing entries using the ip route add command.
  8. Check Network Services:
    • Verify that essential network services (such as DHCP client, network manager, and DNS resolver) are running using the systemctl command.systemctl status NetworkManager systemctl status systemd-resolved
    • Restart or troubleshoot network services as needed.
  9. Review System Logs:
    • Check system logs (e.g., /var/log/syslog, /var/log/messages) for any network-related errors or warnings that may provide clues about the issue.bashCopy codetail -n 50 /var/log/syslog
  10. Test Connectivity to External Resources:
    • Use the ping or traceroute command to test connectivity to external servers and websites.ping google.com traceroute google.com
    • If external pings or traceroutes fail, check for network issues outside your local network, such as ISP problems or internet service disruptions.

By following these steps and systematically checking network components and configurations, you can effectively troubleshoot and resolve network connectivity issues in Linux.

Linux: systemd target units examples

Here is a list of some systemd target units along with examples of how to use them:

  1. multi-user.target:
    • This target is used for a multi-user system without a graphical interface. It includes services required for a text-based or command-line environment.
    • Example: To switch to the multi-user target, you can use the following command: sudo systemctl isolate multi-user.target
  2. graphical.target:
    • Represents a multi-user system with a graphical interface (GUI). It includes services required for a graphical desktop environment.
    • Example: To switch to the graphical target, you can use the following command:sudo systemctl isolate graphical.target
  3. rescue.target:
    • Similar to runlevel 1 or single-user mode in traditional SysVinit systems. It provides a minimal environment with a root shell for system recovery and maintenance tasks.
    • Example: To switch to the rescue target, you can use the following command:sudo systemctl isolate rescue.target
  4. emergency.target:
    • Provides the most minimal environment possible, intended for emergencies where the system is in an unusable state. It drops the system into a single-user shell without starting any services.
    • Example: To switch to the emergency target, you can use the following command:sudo systemctl emergency
  5. shutdown.target:
    • Used to gracefully shut down the system. All services are stopped, and the system is powered off or rebooted, depending on the shutdown command used.
    • Example: To initiate a shutdown using this target, you can use the following command:sudo systemctl shutdown
  6. network.target:
    • Represents the availability of the network. Other services that depend on network connectivity may be started after this target is reached.
    • Example: To view the status of the network target, you can use the following command:systemctl status network.target
  7. sockets.target:
    • Represents the availability of system sockets. Services that provide network services via sockets may be started after this target is reached.
    • Example: To view the status of the sockets target, you can use the following command:systemctl status sockets.target

These are some of the systemd target units along with examples of how to use them. Depending on your specific distribution and configuration, there may be additional targets or custom targets defined. You can explore more targets and their usage by referring to the systemd documentation or using the systemctl list-units --type=target command.

Linux: Systemd target units

Systemd target units are used to group and manage services and other units in Linux distributions that use systemd as the init system. Targets are similar to runlevels in traditional SysVinit systems but offer more flexibility and granularity in defining system states and dependencies between units.

Here are some common systemd target units:

  1. default.target:
    • This is the default target unit that the system boots into. It typically represents the normal operational state of the system.
  2. multi-user.target:
    • Represents a multi-user system without a graphical interface. It includes services required for a text-based or command-line environment.
  3. graphical.target:
    • Represents a multi-user system with a graphical interface (GUI). It includes services required for a graphical desktop environment.
  4. rescue.target:
    • Similar to runlevel 1 or single-user mode in traditional SysVinit systems. It provides a minimal environment with a root shell for system recovery and maintenance tasks.
  5. emergency.target:
    • Provides the most minimal environment possible, intended for emergencies where the system is in an unusable state. It drops the system into a single-user shell without starting any services.
  6. shutdown.target:
    • Used to gracefully shut down the system. All services are stopped, and the system is powered off or rebooted, depending on the shutdown command used.
  7. poweroff.target:
    • Initiates a system poweroff, shutting down the system and powering off the hardware.
  8. reboot.target:
    • Initiates a system reboot, shutting down the system and restarting the hardware.
  9. network.target:
    • Represents the network being available. Other services that depend on network connectivity may be started after this target is reached.
  10. basic.target:
    • A minimal target that is reached early during the boot process. It includes basic system initialization and dependency handling.
  11. sockets.target:
    • Represents the availability of system sockets. Services that provide network services via sockets may be started after this target is reached.
  12. timers.target:
    • Represents the availability of system timers. Services that depend on timers for scheduling tasks may be started after this target is reached.

These are some of the common systemd target units used in Linux distributions. Depending on the specific distribution and configuration, there may be additional targets or custom targets defined. You can view the available targets on your system using the systemctl list-units --type=target command.

Basic Rules of Discrete Probability

In this reading, we’ll introduce discrete and continuous probability, walk through basic probability notation, and describe a few common rules of discrete probability.

Types of Probability

When working with probability in the real world, it’s common to see probability broken down into two categories: discrete probability and continuous probability.

Discrete Probability

Discrete probability deals with discrete variables – that is, variables that have countable values, like integers. Examples of discrete variables include the number of fish in a lake and the number of hobbies that an adult in the U.S. enjoys. 

Therefore, the probability of discrete variables describes the probability of occurrence of each specific value of a discrete variable. As an example, the probability of there being exactly 142 fish in the lake. In another example, the probability of a particular person enjoying exactly 4 hobbies. 

Each possible value of these discrete variables has its own respective non-zero probability of occurring in a dataset. 

Continuous Probability

Continuous probability deals with continuous variables – that is, variables that have infinite and uncountable values. Examples of continuous variables include an individual’s weight and how long it takes to run a kilometer.

Similarly to discrete probability, the probability of continuous variables describes the probability of occurrence of each specific value of a continuous variable. However, these probability values are always close to zero for continuous variables – this is because of the infinite set of outcomes! Any individual outcome, like 2.0000001, is highly unlikely.

We’ll cover more on continuous probability later in this course, but we’ll focus on discrete probability for now.

Probability Notation

In order to learn the basics of discrete probability, it’s important to understand the basics of probability notation.

To symbolize the probability of a discrete event occurring, we use the following notation: P(A) = 0.5

This reads as “the probability of Event A occurring is equal to 0.5.” This can be interpreted as a 50 percent chance of Event A occurring.

Let’s consider a common real-world example: flipping a coin. Below, we write the probability of a flipped standard coin landing heads-up.

P(Heads) = 0.5

To shorten this, we will commonly represent the outcome (Heads) with a single letter. In this case, we are shorting Heads as a capital H.

P(H) = 0.5

Let’s take a look at an example with more possible outcomes: rolling a standard six-sided die. Each of the six outcomes are equally likely to occur when the die is rolled.

P(1) = P(2) = P(3) = P(4) = P(5) = P(6) = 1/6 or about 0.167.

It’s important to note that these examples are theoretical. They are based on what we know about coins and dice, rather than recording actual observations from the real world. In reality, the theoretical probability will most likely not be exactly the same as the actual number of times the event occurs. For example, we might roll a 4 slightly more often, or slightly less often, than 1 in 6 times. So based on recorded data, we might find: P(4) = # of rolls where 4 occurred / # of total rolls = 3/20 = 0.15

However, whether we are working with theoretical or recorded probabilities, the following must be true:

  1. The probability of each outcome must be between 0 and 1: 0 ≤ P(x) ≤ 1.
  2. The sum of the probabilities of each outcome must equal 1: PP(x) = 1.

Common Discrete Probability Rules

When we work with discrete probability, we’re often interested in the more complex questions than the likelihood of a single event occurring in a single trial or draw. Sometimes, we’re interested in the probability that one of a set of non-mutually-exclusive events occurs or in the probability that multiple events occur simultaneously.

In order to answer these questions, we need to understand some of the basic rules of discrete probability. Two common rules are the additive rule and the multiplicative rule.

Additive Rule

The additive rule states that for two events in a single-trial probability experiment, the probability of either event occurring is equal to the sum of their individual probabilities, as long as those events are mutually exclusive. 

Consider the following theoretical examples from our coin and die examples:

P(H or T) = P(H) + P(T) = 0.5 + 0.5 = 1

P(1 or 4) = P(1) + P(4) = ⅙ + ⅙ = ⅓

This rule can be generally stated as:

P(A or B) = P(A) + P(B)

The above rule holds when the events are mutually exclusive, because both events cannot occur – a single coin flip can only bring up heads or tails, not both. And the single roll of a die cannot land on the number 1 and the number 4.

But what about if both events can occur? Let’s look at an example including a standard deck of cards. Assuming that we’re interested in the probability that a single drawn card is a king, denoted by K, or is of the heart suit, denoted by H.

The probabilities of each of these single events are below:

P(K) = 4/52

P(H) = 13/52

If these events were mutually exclusive, meaning there’s no card that is simultaneously a king and of a heart suit, we’d just add P(K) and P(H) together. However, there is a single card that is a king and of a heart suit. 

Its probability is denoted below:

P(K and H) = 1/52

In order to correctly calculate the probability of a single drawn card being a king or of the heart suit, we need to subtract the probability of drawing the king of hearts card. This is because that card is counted as both part of P(K) and P(H) – we’re simply making sure to not count it twice.

P(K or H) = P(K) + P(H) – P(K and H) = 4/52 + 13/52 – 1/52 = 16 / 52

This rule can be generally stated as:

P(A or B) = P(A) + P(B) – P(A and B)

The additive rule can be used to help us understand the probability of a single event of a set of events occurring. Depending on whether the set of events are mutually exclusive from one another, we might need to subtract the probability that they both occur.

Multiplicative Rule

The multiplicative rule states that the probability of two events both occurring is equal to the probability of the first event occurring multiplied by the probability of the second event occurring, as long as those events are independent.

Let us combine our coin and die examples by using the multiplicative rule to compute the probability that a flip of the coin lands heads-up and the die lands with the number 4 facing up.

P(H and 4) = P(H) * P(4) = ½ * ⅙ = 1/12

This rule can be generally stated as:

P(A and B) = P(A) * P(B)

The above rule holds when the two events are independent of one another. The outcome of flipping a coin has absolutely no impact on the outcome of rolling a die.

However, if the events are not independent of one another, then the multiplicative rule states that the probability of two events both occurring is equal to the probability of the first event occurring multiplied by the probability of the second event occurring given that the first event occurred. This last condition accounts for the dependence of the two events.

This rule can be generally stated as:

P(A and B) = P(A) * P(B|A)

Let’s consider our playing card example. Assuming that you want to know the probability of drawing a card that is both a king and of the hearts suit. In order to determine this, you need to know the probability of a card being a king and the probability of the card being of the hearts suit given that it is a king.

These probabilities are denoted below:

P(K) = 4/52

P(H|K) = ¼

Because these events are not independent from one another, we need to multiply these two probabilities by one another to compute P(K and H).

P(K and H) = P(K) * P(H|K) = P(4/52) * P(¼) = 1/52

The multiplicative rule can be used to help us understand the probability of two events occurring. Depending on whether the set of events are independent from one another, we might use the probability of the second event occurring if the first event has occurred, too.

Linux: using netstat -tulpn

The netstat -tulpn command is used to display active network connections and their corresponding processes on a system. Here’s a breakdown of each option:

  • -t: Display TCP connections.
  • -u: Display UDP connections.
  • -l: Show only listening sockets.
  • -p: Show the PID (process ID) and name of the program to which each socket belongs.
  • -n: Show numerical addresses instead of resolving hostnames.

So, netstat -tulpn will list all TCP and UDP connections, show the listening sockets, display the associated process with each connection (along with its PID), and show numerical addresses instead of resolving hostnames. This can be useful for network troubleshooting and monitoring purposes.

How to fix “network ‘default’ is not active” error in libvirt

root@debian01:~# virsh net-list –all

Name State Autostart Persistent

default inactive no yes

root@debian01:~# virsh net-start default
Network default started

root@debian01:~# virsh net-autostart default
Network default marked as autostarted

root@debian01:~# virsh net-list –all

Name State Autostart Persistent

default active yes yes

root@debian01:~#

Xen open-source hypervisor command line reference

Xen is a popular open-source hypervisor that allows for running multiple virtual machines on a single physical host. Here are some common command-line references for managing Xen:

  1. Starting and Stopping Xen:
    • xl create <config_file>: Start a virtual machine defined in the specified configuration file.
    • xl destroy <domain_name>: Forcefully shutdown a virtual machine.
    • xl shutdown <domain_name>: Gracefully shutdown a virtual machine.
    • xl list: List all running domains.
    • xl console <domain_name>: Connect to the console of a running virtual machine.
  2. Managing Virtual Machine Configurations:
    • xl list: List all virtual machines and their states.
    • xl info: Display information about the Xen hypervisor.
    • xl config-list: List all defined VM configurations.
    • xl config-edit <domain_name>: Edit the configuration file of a virtual machine.
    • xl save <domain_name> <state_file>: Save the state of a virtual machine to a file.
    • xl restore <state_file>: Restore a virtual machine from a saved state.
  3. Resource Management:
    • xl mem-set <domain_name> <memory_in_mb>: Set the memory allocation for a virtual machine.
    • xl vcpu-set <domain_name> <num_vcpus>: Set the number of virtual CPUs for a virtual machine.
  4. Networking:
    • Xen usually relies on Linux networking configuration for virtual networking. You can use brctl or ip commands for managing bridges and interfaces.
  5. Snapshot Management:
    • Xen doesn’t have built-in snapshot management like some other hypervisors. You can achieve similar functionality by saving the state of a VM and restoring it later.
  6. XenStore:
    • XenStore is a shared configuration database used by Xen. You can interact with it using the xenstore command. Example:perlCopy codexenstore-ls xenstore-read /local/domain/<domain_id>/memory/target
  7. Debugging and Troubleshooting:
    • xl dmesg: Display Xen hypervisor debug messages.
    • xl top: Display real-time information about the system’s virtualization.
    • xl debug-keys: Print the list of available debug key combinations.

These are some of the basic commands for managing Xen virtual machines and resources. For more detailed information and advanced usage, you can refer to the official documentation for Xen or consult the man pages for the xl command.

KVM (Kernel-based Virtual Machine) is a virtualization solution

KVM (Kernel-based Virtual Machine) is a virtualization solution for Linux that enables users to run multiple virtual machines (VMs) on a single physical host. Below are some common command-line references for managing KVM:

  1. Creating a Virtual Machine:
    • virt-install: Command-line tool for creating new virtual machines. Example:cssCopy codevirt-install --name=myvm --memory=2048 --vcpus=2 --disk path=/var/lib/libvirt/images/myvm.qcow2,size=20 --cdrom /path/to/install.iso --network bridge=br0
  2. Managing Virtual Machines:
    • virsh: Command-line interface for managing virtual machines. Some useful commands include:
      • virsh list: List all running VMs.
      • virsh start <domain>: Start a VM.
      • virsh shutdown <domain>: Shutdown a VM gracefully.
      • virsh destroy <domain>: Forcefully shutdown a VM.
      • virsh reboot <domain>: Reboot a VM.
      • virsh suspend <domain>: Suspend a VM.
      • virsh resume <domain>: Resume a suspended VM.
  3. Managing Virtual Networks:
    • virsh net-list: List all defined virtual networks.
    • virsh net-start <network>: Start a virtual network.
    • virsh net-destroy <network>: Destroy a virtual network.
    • virsh net-edit <network>: Edit a virtual network configuration.
  4. Cloning Virtual Machines:
    • You can use virt-clone or qemu-img to clone virtual machine disk images. Example with qemu-img:cssCopy codeqemu-img create -f qcow2 -b source_image.qcow2 cloned_image.qcow2
  5. Snapshot Management:
    • virsh snapshot-create <domain>: Create a snapshot of a VM.
    • virsh snapshot-list <domain>: List snapshots of a VM.
    • virsh snapshot-revert <domain> <snapshot>: Revert a VM to a specific snapshot.
    • virsh snapshot-delete <domain> <snapshot>: Delete a snapshot of a VM.
  6. Virtual Disk Management:
    • qemu-img: Command-line tool for managing disk images. Examples:
      • qemu-img info disk_image.qcow2: Get information about a disk image.
      • qemu-img resize disk_image.qcow2 +10G: Resize a disk image.
      • qemu-img convert -f qcow2 -O raw disk_image.qcow2 disk_image.raw: Convert disk image formats.

These are some of the basic commands for managing KVM virtual machines and resources. For more detailed information and advanced usage, you can refer to the official documentation for KVM and associated tools.

The os module in Python

The os module in Python provides a portable way to interact with the operating system, including Linux. While it doesn’t cover every aspect of Linux system administration, it offers functionalities for basic operations like file and directory manipulation, process management, and environment variables. Below are some of the key functions and classes in the os module:

  1. File and Directory Operations:
    • os.getcwd(): Get the current working directory.
    • os.chdir(path): Change the current working directory to the specified path.
    • os.listdir(path='.'): Return a list of the entries in the directory given by path.
    • os.mkdir(path): Create a directory named path.
    • os.makedirs(path): Recursive directory creation function.
    • os.remove(path): Remove (delete) the file path.
    • os.rmdir(path): Remove (delete) the directory path.
  2. Process Management:
    • os.system(command): Execute the command in a subshell.
    • os.spawn*(): Functions for spawning a new process.
    • os.fork(): Fork a child process.
    • os.kill(pid, sig): Send a signal to the process pid.
  3. Environment Variables:
    • os.environ: Dictionary containing the environment variables.
    • os.getenv(var, default=None): Get an environment variable, optionally returning a default value if the variable is not set.
  4. Miscellaneous:
    • os.path: Submodule for common pathname manipulations.
    • os.name: String representing the current operating system.
    • os.utime(path, times=None): Set the access and modified times of the file specified by path.
  5. Permissions:
    • os.chmod(path, mode): Change the mode (permissions) of path to the numeric mode.
    • os.access(path, mode): Check if a user has access to a file.

Remember, the os module provides basic functionalities. For more advanced operations, you might need to use other modules like subprocess, shutil, or os.path. Additionally, for system administration tasks on Linux, modules like subprocess, sys, shutil, socket, multiprocessing, and os.path are often used in conjunction with os.