Skip to content

Linux command

lsblk

The lsblk command in Linux is a utility used to list information about all available block devices. It provides a view of how storage is connected in your system, including hard drives, solid state drives, USB drives, and their partitions.

Useful Options for lsblk

-f: Shows the filesystem type and mountpoint. -o: Allows you to specify which columns to display, such as NAME, FSTYPE, SIZE, MOUNTPOINT, etc. -m: Displays permission and ownership information.

The lsblk command is particularly useful for quickly understanding storage layouts, especially when managing multiple drives and partitions on a Linux system.


df

The df command in Linux stands for "disk filesystem." It is used to display the amount of disk space used and available on filesystems. This command is very useful for system administrators and users to monitor and manage disk space usage.

Common Options for df

Here are some commonly used options with the df command:

-h, --human-readable: Print sizes in a human-readable format (e.g., 1K, 234M, 2G). -T, --print-type Show the type of each filesystem. -a, --all: Include dummy file systems in the output. -i, --inodes: List inode information instead of block usage. --total: Produce a grand total of disk usage for all filesystems.


date

The date command in Unix-like operating systems is used to display or set the system's date and time. It is a versatile command with options to format the output according to specific needs, which makes it particularly useful for scripting, logging, and file naming based on timestamps.

Commonly Used Options

  • -d, --date=STRING: Display time described by STRING, not 'now'. This can be used to convert dates or to display different time specifications.
  • -u, --utc, --universal: Display or set Coordinated Universal Time (UTC).
  • -R, --rfc-email: Output date and time in RFC 5322 format. Useful for timestamps in emails.
  • -I, --iso-8601[=TIMESPEC]: Output date/time in ISO 8601 format. TIMESPEC can be 'date', 'hours', 'minutes', or 'seconds'.

Formatting the Output

The date command can be customized to output different date and time formats by specifying a FORMAT string. Some common format specifiers include:

  • %Y: year (e.g., 2023)
  • %m: month (01..12)
  • %d: day of month (e.g., 01)
  • %H: hour (00..23)
  • %M: minute (00..59)
  • %S: second (00..60)
  • %A: full weekday name (e.g., Sunday)
  • %B: full month name (e.g., January)

Examples of Using date

  1. Current Date and Time:
    date
    
    This will output the current system date and time based on the system's default format.
  2. Custom Format Output:
    date "+%Y-%m-%d %H:%M:%S"
    
    This command will output the date and time in the format YYYY-MM-DD HH:MM:SS.
  3. Display Date in ISO 8601 Format:
    date --iso-8601=seconds
    
    Outputs the current date and time with timezone information, accurate to seconds.
  4. Convert String to Date:
    date -d "yesterday"
    
    This displays the date and time for yesterday.
  5. Set System Date and Time:
    sudo date --set="2024-01-01 12:34:56"
    
    This sets the system date and time to January 1, 2024, at 12:34:56. It requires superuser privileges.

Using date in Scripts

The date command is often used in shell scripts for logging, generating filenames with timestamps, or performing date arithmetic. For example, to create a backup file with a timestamp:

cp important_file.txt backup_$(date "+%Y%m%d_%H%M%S").txt
This command copies important_file.txt to a backup file, appending the current date and time to the filename.


seq

The seq command in Linux is a utility for generating sequences of numbers. It is commonly used in shell scripts and command line operations when a sequence of numbers is needed. The seq command is simple to use and highly customizable.

Basic Usage of seq

The basic syntax of seq is:

seq [OPTION]... LAST
seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST
Here's what you need to know about the parameters: - FIRST: The starting number of the sequence (defaults to 1 if omitted). - INCREMENT: The step between each number in the sequence (defaults to 1 if omitted). - LAST: The last number of the sequence (mandatory unless the --help or --version option is used).


test

The test command in Unix-like operating systems is used to evaluate conditional expressions. The syntax for test can involve checking file types and characteristics, comparing strings, and evaluating integer values.

Common Uses of test

Here are some of the common uses of the test command:

  • File tests: Checking if a file exists, if it is writable, readable, or executable.
    test -e filename
    
  • String tests: Comparing two strings to see if they are equal or if a string is empty.
    test "string1" = "string2"
    test -z "string"
    
  • Integer tests: Comparing two integers.
    test 1 -eq 2
    

Exit Status

  • 0: The expression evaluated is true.
  • 1: The expression evaluated is false.
  • >1: An error occurred.

Using -n option

The test -n in shell scripting is used to check if a string has a non-zero length, i.e., if the string is not empty. When used with the test command or within conditional expressions like [[ ]] with -n evaluates to true if the string specified as an argument is non-empty.


systemctl

systemctl is a command-line utility that is central to managing the systemd system and service manager in modern Linux distributions. systemd serves as the init system that initializes user space components and manages system processes after the Linux kernel has booted. It has largely replaced older init systems such as SysV init and Upstart in many Linux distributions.

Key Features of systemctl

  • Service Management: systemctl allows users to start, stop, restart, reload, enable, disable, and check the status of systemd services.
  • System Management: It can be used to reboot, shut down, suspend, and hibernate the system.
  • Unit Management: systemctl manages all systemd "units" — which include services (.service files), mount points (.mount files), sockets (.socket files), and other resources.

Common Commands and Their Uses

  1. Start/Stop/Restart Services:
  2. Start a service: systemctl start [service_name]
  3. Stop a service: systemctl stop [service_name]
  4. Restart a service: systemctl restart [service_name]
  5. Enable/Disable Services:
  6. Enable a service to start at boot: systemctl enable [service_name]
  7. Disable a service from starting at boot: systemctl disable [service_name]
  8. Check Status:
  9. Status of a service: systemctl status [service_name] This command displays detailed information about a service, including its current status, recent log entries, and more.
  10. List Services and Units:
  11. List active services: systemctl list-units --type=service --state=active
  12. List all services, including inactive ones: systemctl list-units --type=service
  13. System Power Management:
  14. Reboot the system: systemctl reboot
  15. Shutdown the system: systemctl poweroff
  16. Suspend the system: systemctl suspend
  17. Hibernate the system: systemctl hibernate

What about systemctl is-active?

The systemctl is-active command is used to determine whether a specified systemd service is currently active. "Active" typically means that the service is running, but for services that start up and complete their task immediately, it may simply mean that they successfully ran and completed.

Example: Checking the psacct Service

To check if the psacct service, which is used for monitoring process activities and accounting, is active, you would use:

systemctl is-active psacct

Output

  • active: The service is currently running.
  • inactive: The service is not running.
  • unknown: The service status cannot be determined, possibly because the service does not exist.

The command will also return an exit status that can be programmatically used: - 0: The service is active. - 3: The service is inactive, dead, or not loaded.


ps aux

The shell command ps aux is used in Unix-like operating systems to display information about the currently running processes. Here’s what each part of the command means:

  • ps: Stands for "process status," which is the command used to display information about active processes.
  • a: Lists all processes with a terminal (TTY), including those belonging to other users.
  • u: Displays the process's owner/user name and other detailed information like CPU and memory usage.
  • x: Includes processes that do not have a controlling terminal, often including daemon processes (background services). When you run ps aux, it provides a detailed snapshot of every running process on the system, along with information like the user ID, CPU and memory usage, start time, command used to launch the process, and more. This command is commonly used for monitoring system activity and managing system resources.

| aka pipeline

In shell commands, the pipe symbol | is used as a pipeline operator. It takes the output of one command (on its left) and uses it as the input to another command (on its right). This allows you to chain together multiple commands in a sequence, creating a pipeline that processes the data step-by-step.


grep

The shell command grep is used to search for text in files or input provided by another command, based on a specified pattern. The pattern can be a simple text string or a regular expression. grep stands for "global regular expression print." Here's a basic overview of how to use grep and some of its common options:

Basic Syntax

grep [options] pattern [file...]

Common Options

  • -i: Ignore case (case insensitive search).
  • -v: Invert the search, displaying lines that do not match the pattern.
  • -r: Recursively search through directories.
  • -n: Display the line number along with the text of each matching line.
  • -l: Only show the names of files with matching lines, not the lines themselves.
  • -c: Count the number of lines that match the pattern.
  • -E: Interpret pattern as an extended regular expression (ERE).

Examples

  1. Basic Search: Search for the word "example" in a file named "test.txt":
    grep "example" test.txt
    
  2. Case Insensitive Search: Search for "example" in "test.txt", ignoring case:
    grep -i "example" test.txt
    
  3. Recursive Search: Search for "example" in all files under the current directory and its subdirectories:
    grep -r "example" .
    
  4. Invert Match: Show all lines that do not contain "example":
    grep -v "example" test.txt
    
  5. Count Matches: Count the number of lines that contain "example":
    grep -c "example" test.txt
    ````
    
    ---
    
    ## `at`
    The at command in Unix-like operating systems is used to schedule commands to be executed once at a specific time in the future. It reads commands from standard input or a specified file which are to be executed at a later time, using /bin/sh.
    
    ### Syntax of the at Command
    ```bash
    at [options] time [date]
    

Common Options

  • -f file: Tells at to read the commands to be executed from a specified file instead of standard input.
  • -l or atq: Lists the user's pending jobs, scheduled by at.
  • -d or -r or atrm: Deletes jobs, specified by their job number.
  • -m: Sends mail to the user when the job has completed.
  • -v: Displays the time at which the job will run before reading the job.

Time Specifications

The time argument can be specified in several formats: - HH:MM: Executes at a specific time on the current day, or the next day if the time is already past. - midnight, noon, teatime (4pm): Keywords that specify common times of day. - tomorrow, noon tomorrow: Specifies the next day at the given time. - next week, next Monday: Specifies a day of the week.

Examples of Using at

  1. Schedule a Job for Later Today:
    echo "echo 'Reminder: Meeting at 3 PM' > /dev/pts/0" | at 14:55
    
    This schedules a reminder to be printed on your terminal at 14:55 today.
  2. Schedule a Script to Run Tomorrow Morning:
    at 08:00 tomorrow -f /path/to/script.sh
    
    This schedules a script located at /path/to/script.sh to run at 8:00 AM the next day.
  3. List Scheduled Jobs:
    at -l
    
    or
    atq
    
    Both commands list all scheduled jobs for the current user.
  4. Remove a Scheduled Job:
    at -d job_number
    
    or
    atrm job_number
    
    This removes the job identified by job_number.

Using at in Scripts

at can be used in scripts for delaying job execution or setting up tasks that need to run later without requiring a daemon or more complex scheduling system like cron.

Permissions and Configuration

The ability to use at might be restricted to certain users, typically controlled by files in /etc/, namely /etc/at.allow and /etc/at.deny. at.allow lists users allowed to use at, and at.deny lists users denied access. If at.allow exists, only users listed in it can use at; if it does not exist, users not listed in at.deny can use at.


watch

The watch command in Unix-like operating systems is a handy utility used to run any designated command at regular intervals and display its output in fullscreen. This allows users to monitor the output of a command in real time, which is especially useful for tracking changes, such as viewing updates in a directory's contents or monitoring system processes.

Syntax of the watch Command

The basic syntax of the watch command is:

watch [options] command

Key Options

  • -n or --interval: Sets the interval between executions of the command in seconds. The default is 2 seconds.
  • -d or --differences: Highlights the differences between successive updates. You can use -d=cumulative to leave highlighted changes displayed permanently.
  • -b or --beep: Beeps if the command has a non-zero exit.
  • -t or --no-title: Turns off the header showing the interval, command, and current time at the top of the display.
  • -p or --precise: Attempts to ensure that the specified interval is the minimum time between updates.

Examples of Using watch

  1. Monitor Changes in the Current Directory:

    watch ls -l
    
    This command will repeatedly execute ls -l every 2 seconds, allowing you to see how the contents of the current directory change.

  2. Check Free Disk Space:

    watch df -h
    
    Use this to monitor the free disk space on your drives, updating the display every 2 seconds.

  3. Highlight Differences in Network Connections:

    watch -d netstat -a
    
    This command will run netstat -a every 2 seconds and highlight what changes from one snapshot to the next.

  4. Monitor CPU or Memory Usage:

    watch -n 1 free -m
    
    This example sets watch to update every second, running free -m to show memory usage in megabytes.

Practical Uses

The watch command is particularly useful for system administrators and developers who need to track changes in real time, such as watching for changes in the output of a server status script, or monitoring system resource usage. It provides a simple yet powerful way to keep an eye on processes, resources, or any command that can change over time.


`less``

The less command is a pager program used to view the contents of a text file one screen at a time. It is particularly useful for reading large files because it doesn’t load the entire file into memory but reads it as needed.

Purpose and Usage:

  • Usage: less [options] filename
  • Basic Functionality: Opens the specified file and allows you to scroll through it using keyboard commands.
  • Space or f: Move forward one screen.
  • b: Move backward one screen.
  • Enter or j: Move forward one line.
  • k: Move backward one line.
  • /pattern: Search forward for a pattern.
  • ?pattern: Search backward for a pattern.
  • n: Repeat the last search in the same direction.
  • N: Repeat the last search in the opposite direction.
  • q: Quit less.

Advantages:

  • Efficiency: Uses less memory than loading the entire file.
  • Interactivity: Allows for real-time searching and navigation within the file.
  • Adaptability: Can be used to view the output of other commands when piped (e.g., dmesg | less).

tail

The tail command is used to display the last part of a file. It’s frequently used to monitor logs and other continuously updating files.

Purpose and Usage:

  • Usage: tail [options] filename
  • Basic Functionality: Outputs the last 10 lines of the specified file by default.

Options:

  • -n <number>: Show the last <number> lines.
  • -f: Follow the file as it grows. Useful for real-time monitoring of log files.
  • -c <number>: Output the last <number> bytes of the file.

Examples:

  • Basic Use: tail /var/log/syslog - Displays the last 10 lines of the syslog file.
  • Custom Lines: tail -n 20 /var/log/syslog - Displays the last 20 lines.
  • Follow Mode: tail -f /var/log/syslog - Continuously outputs new lines added to the syslog, useful for monitoring logs in real-time.

Advantages:

  • Monitoring: Ideal for keeping an eye on log files as they are being written to.
  • Simplicity: Straightforward command options make it easy to use.

Summary on less vs tail

  • less: Used for comfortably reading large files by paging through them, searching within the file, and navigating in both directions.
  • tail: Used for displaying the end of a file, with the ability to dynamically follow updates, making it invaluable for real-time log monitoring.

systemd-journald

Overview

  • Functionality: systemd-journald is a component of the systemd suite that collects and stores logging data.
  • Storage: Logs are stored in a binary format in /run/log/journal/ (volatile, not persistent) and /var/log/journal/ (persistent).
  • Integration: Tight integration with other systemd components.

Features

  • Structured Logging: Supports structured, indexed logs.
  • Metadata: Retains metadata alongside log entries (such as the UID, GID, and SELinux context).
  • Querying: Logs can be queried efficiently using journalctl.
  • Rotation: Integrates log rotation and cleanup.
  • Security: Provides features to increase log integrity, such as Forward Secure Sealing.

Commands and Usage

  • View Logs: journalctl - Used to view and query logs.
  • journalctl -u <service>: View logs for a specific service.
  • journalctl --since=yesterday: View logs since a specified time.

Advantages

  • Integration: Works seamlessly with other systemd components.
  • Efficiency: Faster querying and filtering due to indexed logs.
  • Detail: Rich metadata and structured log entries.

Disadvantages

  • Binary Format: Logs are stored in a binary format, which may not be straightforward for direct reading or manipulation without specific tools.
  • Compatibility: May not be compatible with some legacy systems or tools that expect text-based logs.

rsyslog

Overview

  • Functionality: rsyslog is a high-performance logging daemon that extends the syslog protocol, providing more capabilities and flexibility.
  • Storage: Stores logs in plain text files by default, typically in /var/log/.

Features

  • Protocol Support: Can receive and forward logs via various protocols, including TCP, UDP, and RELP.
  • Configuration: Highly configurable with advanced filtering and routing options.
  • Modules: Extensible via modules for features like database storage, encryption, and more.
  • Compatibility: Complies with syslog protocol standards, making it compatible with a wide range of devices and legacy systems.

Commands and Usage

  • Configuration: /etc/rsyslog.conf and /etc/rsyslog.d/*.conf - Configuration files for setting up log sources, destinations, and rules.
  • Example Configuration:
  • *.info;mail.none;authpriv.none;cron.none /var/log/messages: Logs all .info level messages except mail, authpriv, and cron messages to /var/log/messages.

Advantages

  • Flexibility: Can be configured for a wide array of logging scenarios.
  • Standard Compliance: Adheres to syslog protocol, ensuring wide compatibility.
  • Text-Based: Logs are easily readable and parsable with standard text processing tools.

Disadvantages

  • Performance: May not be as efficient in querying and filtering logs as systemd-journald.
  • Complexity: Advanced configurations can be complex and harder to manage.

Summary systemd-journald vs rsyslog

Both systemd-journald and rsyslog are tools used for logging in Unix-like systems, but they serve different purposes and have distinct characteristics. Here’s the comparison:

  • systemd-journald:
  • Strengths: Integration with systemd, structured logging, efficient querying.
  • Use Case: Best used in environments heavily relying on systemd where metadata and structured logs are valuable.

  • rsyslog:

  • Strengths: Flexibility, compatibility with syslog protocol, text-based logs.
  • Use Case: Suitable for heterogeneous environments requiring advanced configurations and compatibility with traditional syslog systems.

Both tools can be used independently or together, with rsyslog forwarding logs to systemd-journald or vice versa, depending on the requirements of your logging strategy.


chronyc

Overview

chronyc is the command-line interface and control utility for chronyd, which is a versatile and robust Network Time Protocol (NTP) daemon. chronyd is used for keeping computer clocks synchronized with NTP servers, and chronyc provides commands to monitor and manage its operation.

chronyc is part of the Chrony suite, which is designed to perform well in a variety of network conditions, including intermittent connectivity and virtualized environments.

Key Features

  • Monitor NTP Daemon: Check the status and behavior of the chronyd service.
  • Management: Modify the behavior of chronyd at runtime.
  • Diagnostics: Gather diagnostic and performance information.

dnf install

Overview

The dnf install command is used to install software packages on Red Hat-based Linux distributions, such as Fedora, Red Hat Enterprise Linux (RHEL), and CentOS. DNF (Dandified YUM) is the next-generation version of the Yellowdog Updater, Modified (YUM), designed to manage software packages and dependencies with improved performance and usability.

Key Features

  • Dependency Resolution: Automatically handles the resolution and installation of package dependencies.
  • Repository Management: Sources packages from configured repositories.
  • Rollback: Supports automatic transaction rollback in case of errors.
  • Speed: Improved speed and performance over its predecessor, YUM.
  • Compatibility: Compatible with YUM repositories and metadata.

Summary

The dnf install command is a robust tool for managing software installations on Red Hat-based Linux distributions. It automatically handles dependencies, sources packages from repositories, and offers options for seamless package management.


systemctl

Overview

systemctl is a command-line utility used to control and manage the systemd system and service manager. systemd is an initialization system and service manager for Linux operating systems, designed to start, stop, and manage services and system components.

Key Features

  • Service Management: Start, stop, restart, enable, and disable system services.
  • System State: Reboot, shut down, or suspend the system.
  • Unit Management: Handle various systemd units, including services, sockets, devices, mounts, and targets.
  • Status Monitoring: Check the status of services and system components.

Summary

The systemctl command is an essential tool for managing services, units, and the overall system state on Linux distributions that use systemd. It provides a wide range of commands for starting, stopping, enabling, and checking the status of services, as well as managing various types of units and performing system operations like rebooting and shutting down.

By mastering systemctl, system administrators can efficiently manage system services and ensure the smooth operation of their Linux systems.


chcon Command

Overview

The chcon command stands for "Change Context" and is used to change the SELinux (Security-Enhanced Linux) security context of files and directories. SELinux is a security architecture integrated into the kernel that provides a mechanism for supporting access control security policies, including mandatory access controls (MAC).

Key Concepts

  • Security Context: SELinux uses security contexts to enforce its policies. Each file, directory, and process has an associated security context that consists of a user, role, type, and optionally a level.
  • Changing Context: The chcon command changes the SELinux context directly on the file or directory, but these changes might not persist after a relabeling operation.

Syntax

chcon [OPTIONS] CONTEXT FILE...
- CONTEXT: The new security context to apply. - FILE...: The files or directories to modify.

Commonly Used Options

  • -t, --type=TYPE: Set the type part of the security context. This is the most commonly used option.
chcon -t httpd_sys_content_t /var/www/html/index.html
  • -u, --user=USER: Set the user part of the security context.
chcon -u system_u /var/www/html/index.html
  • -r, --role=ROLE: Set the role part of the security context.
chcon -r object_r /var/www/html/index.html
  • -l, --range=RANGE: Set the level part of the security context (used in MLS/MCS policies).
chcon -l s0 /var/www/html/index.html
  • -R, --recursive: Apply changes recursively to directories and their contents.
chcon -R -t httpd_sys_content_t /var/www/html/

Example Usage

Change the Type Context

To change the type context of a file to be accessible by an HTTP server:

sudo chcon -t httpd_sys_content_t /var/www/html/index.html

Recursively Change Context

To change the SELinux context of all files and directories under /var/www/html recursively:

sudo chcon -R -t httpd_sys_content_t /var/www/html

Verify the Change

To verify the SELinux context of a file:

ls -Z /var/www/html/index.html

The output will show the security context, including the type you set.

Important Notes

  • Non-Persistent Changes: Changes made with chcon may not be persistent after a system relabel (e.g., using the restorecon command or when filesystems are relabeled). To make persistent changes, modify the SELinux policy or use the semanage fcontext command to associate the correct context with a file path pattern.

  • Restore Context: To restore the default SELinux context for a file, use the restorecon command:

sudo restorecon /var/www/html/index.html

Summary

The chcon command is a powerful utility for changing the SELinux security context of files and directories, allowing administrators to modify access controls as required by their security policies. While chcon provides direct and immediate context changes, these changes might not be persistent across system relabels, and modifying SELinux policies or using semanage is recommended for long-term adjustments.


semanage

Overview

The semanage command is used in SELinux (Security-Enhanced Linux) to manage various aspects of SELinux policy, including modifying and querying SELinux configurations. It provides an interface for making policy modifications that persist across reboots and relabels, unlike the chcon command.

Key Functionality

  • Manage File Contexts: Add, modify, and delete file context definitions for specific paths.
  • Manage Booleans: Enable or disable SELinux Booleans, which tune SELinux policy behavior.
  • Manage Ports: Assign and manage SELinux types for network ports.
  • Manage Interfaces: Configure SELinux types for network interfaces.
  • Manage Users and Login Mappings: Configure SELinux users and their mapping to Linux users.

Example Usages

Manage File Contexts

Add a File Context

Persistently assign a specific SELinux context to a directory or file path:

sudo semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
  • -a: Add a new context.
  • -t httpd_sys_content_t: Set the type to httpd_sys_content_t.
  • "/web(/.*)?": The path and regex pattern for the files or directories.

Apply the Context

After adding the context, apply it using restorecon:

sudo restorecon -R /web

Modify a File Context

Change an existing file context definition:

sudo semanage fcontext -m -t httpd_sys_content_t "/web(/.*)?"

Delete a File Context

Remove a specific file context definition:

sudo semanage fcontext -d "/web(/.*)?"

Manage SELinux Booleans

View, enable, or disable SELinux Booleans that affect the system’s security policy.

View Booleans

List all SELinux Booleans and their current states:

sudo semanage boolean -l

Enable a Boolean

Turn on a specific Boolean:

sudo setsebool -P httpd_can_network_connect on
  • -P: Make the change persistent across reboots.

Disable a Boolean

Turn off a specific Boolean:

sudo setsebool -P httpd_can_network_connect off

Manage Ports

Add a Port Type

Associate a port with a specific SELinux type:

sudo semanage port -a -t http_port_t -p tcp 8080
  • -a: Add a new port type.
  • -t http_port_t: Set the type to http_port_t.
  • -p tcp 8080: Specify the protocol (tcp) and the port number (8080).

Remove a Port Type

Remove the association of a port with a specific SELinux type:

sudo semanage port -d -p tcp 8080

Manage Interfaces

Add an Interface Type

Assign an SELinux type to a network interface:

sudo semanage interface -a -t netif_t eth0
  • -a: Add a new interface type.
  • -t netif_t: Set the type to netif_t.
  • eth0: The interface to be modified.

Important Notes

  • Persistence: Changes made using semanage are persistent across system reboots and relabels, unlike changes made with chcon.
  • Permissions: Running semanage typically requires root privileges.

Summary

The semanage command is a powerful tool for managing and configuring SELinux policy settings, providing persistent and flexible control over file contexts, Booleans, ports, interfaces, and user mappings. It is essential for administrating SELinux policies and maintaining a secure Linux environment.

Common Commands

  • Add File Context:
    sudo semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
    
  • Apply Context:
    sudo restorecon -R /web
    
  • Enable Boolean:
    sudo setsebool -P httpd_can_network_connect on
    
  • Add Port Type:
    sudo semanage port -a -t http_port_t -p tcp 8080
    

getsebool

Overview

The getsebool command is used in SELinux (Security-Enhanced Linux) to query the current state of SELinux Boolean variables. SELinux Booleans are used to enable or disable certain security policies dynamically. Booleans allow administrators to modify the behavior of SELinux policies without requiring a full policy rebuild.

Key Concepts

  • SELinux Booleans: These are toggles that enable or disable specific SELinux policy features. They provide a flexible way to customize SELinux behavior.
  • State: Booleans can be either on (enabled) or off (disabled).

Syntax

getsebool [OPTIONS] BOOLEAN...
  • BOOLEAN...: One or more Boolean variables you want to query.

Usage

Query a Single Boolean

To check the state of a specific SELinux Boolean, use the getsebool command followed by the Boolean name:

getsebool httpd_enable_cgi

Output:

httpd_enable_cgi --> off

Query Multiple Booleans

You can also query the state of multiple Booleans by listing them one after the other:

getsebool httpd_enable_cgi ftp_home_dir

Output:

httpd_enable_cgi --> off
ftp_home_dir --> on

Query All Booleans

While getsebool cannot directly list all Booleans, you can combine it with getsebool -a, where -a will display states for all Booleans:

getsebool -a

Output:

allow_user_postgresql_connect --> on
httpd_enable_cgi --> off
ftp_home_dir --> on

Example Commands

Checking the Status of a Web Server Boolean

To verify if CGI scripts are allowed to run by the Apache web server (httpd), you can query the relevant Boolean:

sudo getsebool httpd_enable_cgi

If you manage a Linux server with multiple web services, you might want to check several Booleans at once:

sudo getsebool httpd_enable_cgi httpd_can_network_connect httpd_can_sendmail

Checking All Booleans

To get a list of all Booleans and their states on your system:

sudo getsebool -a

Important Notes

  • Root Privileges: You typically do not need root privileges to query the state of SELinux Booleans, but it’s common to use sudo when dealing with SELinux for comprehensive administrative tasks.
  • Scripts and Automation: The getsebool command can be used in scripts to programmatically check and log the state of SELinux Booleans.

Setting Boolean Values

To change the state of an SELinux Boolean, you use the setsebool command. For example, to enable httpd_enable_cgi:

sudo setsebool httpd_enable_cgi on

To make the change persistent across reboots, use the -P flag:

sudo setsebool -P httpd_enable_cgi on

Listing All Booleans with Their Descriptions

An extended and descriptive listing of all Booleans can be achieved with semanage boolean -l:

sudo semanage boolean -l

Output:

SELinux boolean                State  Default Description
allow_user_postgresql_connect  (on   ,   on)  Allow user processes to connect to postgresql
...

Summary

The getsebool command is a simple yet powerful tool for querying the state of SELinux Booleans. It allows system administrators to quickly check which security features are enabled or disabled, providing flexibility in managing SELinux policies.

Key Commands

  • Query a Single Boolean:

    sudo getsebool httpd_enable_cgi
    

  • Query Multiple Booleans:

    sudo getsebool httpd_enable_cgi ftp_home_dir
    

  • Query All Booleans:

    sudo getsebool -a
    

By understanding and utilizing getsebool, administrators can effectively monitor and manage the security posture of their SELinux-enabled systems.