Module 5 – Linux System Administration
Module 5 – Linux System Administration
These are the basic commands for managing user accounts in Linux. Depending on your
specific requirements and distribution, there may be additional options or tools available for
user management. Always ensure you have the appropriate permissions and understand the
implications of the actions you take when managing user accounts.
Switch users and Sudo access
In Linux, switching users and using `sudo` for administrative tasks are common operations
that help manage system resources securely. Here's how you can do both:
Switching Users:
1. su Command: The `su` command allows you to switch to another user account. By
default, if you don't specify any username, it switches to the root user.
bash
su [username]
For example, to switch to the user named "john":
bash
su john
2. su with Dash: If you want to simulate a full login for the user (source their login
environment), use `-` after `su`.
bash
su - [username]
This ensures that the environment variables and paths are set up as if you had logged in
directly as that user.
3. exit Command: To return to your original user account, simply type `exit`.
Using sudo:
`sudo` is used to execute commands with administrative privileges. Users need to be granted
permission to use `sudo` via the `/etc/sudoers` file, typically by being added to the `sudo`
group.
1. Running a Single Command: You can use `sudo` followed by the command you want to
execute with elevated privileges.
bash
sudo [command]
For example:
bash
sudo apt update
2. Running a Shell with Elevated Privileges: You can also start a shell with elevated
privileges.
bash
sudo -i
This will start a root shell, allowing you to execute multiple commands with elevated
privileges without prepending each with `sudo`.
3. sudo su: Although not recommended due to potential security risks, you can also switch
to the root user shell directly using `sudo su`.
bash
sudo su
This essentially switches to the root user's shell until you exit from it.
Monitor users
Monitoring users in Linux can involve several aspects, including tracking user activities,
resource usage, login/logout times, and more. Here are some methods you can use:
1. Monitoring User Activities:
a. Using the `last` Command:
The `last` command displays a list of last logged in users and their login/logout times.
bash
last
b. Using the `who` Command:
The `who` command displays who is currently logged in and what they are doing.
bash
who
2. Monitoring Resource Usage:
a. Using `top` Command:
The `top` command displays real-time information about system resources, including CPU,
memory, and processes. It can help identify users consuming significant resources.
bash
top
b. Using `htop` Command:
Similar to `top`, `htop` provides a more user-friendly interface for monitoring system
resources.
bash
htop
3. Monitoring User Commands:
a. Using `history` Command:
The `history` command shows the command history of the current user, which can help track
their recent activities.
bash
history
4. Monitoring Login Attempts:
a. Using `auth.log` File:
The `/var/log/auth.log` file records authentication activities, including successful and failed
login attempts.
bash
cat /var/log/auth.log | grep "user"
5. Monitoring User Processes:
a. Using `ps` Command:
The `ps` command displays information about active processes, including those owned by
specific users.
bash
ps -u username
6. Monitoring File System Activities:
a. Using `auditd` (Audit Framework):
The `auditd` service can be used to monitor file system activities, such as file access,
modifications, and deletions.
7. Monitoring Network Activities:
a. Using `tcpdump` Command:
The `tcpdump` command captures and displays network traffic, which can help monitor
network activities associated with specific users.
bash
sudo tcpdump -i any -n host [user_ip_address]
Talking to users (users, wall, write)
In Linux, you can communicate with other users who are logged into the system using
various commands such as `write`, `wall`, or simply by sending messages through the
terminal. Here's how you can do it:
Note:
- To use the `write` command, the recipient user must have allowed messages from you.
They can enable or disable message reception using the `mesg` command.
- Using `wall` and sending messages via terminal typically require appropriate permissions,
such as being a superuser or having write access to certain system files.
These commands can be useful for system administrators or users collaborating on a shared
system to communicate important information or coordinate tasks. However, ensure to use
them responsibly and respect other users' privacy and workflow.
Linux Directory Service - Account Authentication
Linux Directory Service refers to a centralized system used in Linux environments to
manage user accounts, groups, and authentication. One of the most common
implementations of this is LDAP (Lightweight Directory Access Protocol).
Here's a breakdown of how it works:
2. Client Applications: Linux machines and applications can be configured to use LDAP for
authentication. This means that instead of maintaining user account information locally, they
query the LDAP server to authenticate users and authorize access.
4. NSS (Name Service Switch): NSS is used to provide system-wide configuration for
managing various sources of naming information, such as users, groups, hosts, etc. NSS can
also be configured to query LDAP for user and group information.
Overall, LDAP provides a centralized and scalable solution for managing user accounts and
authentication in Linux environments. It simplifies administration tasks by centralizing user
account information and provides a single point of authentication for multiple systems and
applications.
System utility commands (date, uptime, hostname, which, cal, bc etc.)
Here are some common system utility commands in Linux:
1. `date`: Displays the current date and time.
$ date
2. `uptime`: Shows how long the system has been running, including the current time, the
number of users, and the load average.
$ uptime
3. `hostname`: Prints the name of the current host system.
$ hostname
4. `which`: Locates the executable file associated with a given command.
$ which command_name
5. `cal`: Displays a calendar of the current month or any specified month/year.
$ cal [month] [year]
6. `bc`: An arbitrary precision calculator language. It can perform mathematical calculations
interactively or as part of a script.
$ bc
7. `top`: Provides dynamic real-time information about running processes, system memory,
and CPU usage.
$ top
8. `ps`: Reports a snapshot of the current processes.
$ ps
9. `df`: Shows disk space usage of file systems.
$ df
10. `du`: Estimates file space usage.
$ du [options] [files or directories]
Processes and schedules (systemctl, ps, top, kill, crontab and at)
In Linux, various commands and tools are used for managing processes and schedules.
Here's a brief overview of each:
Sure, let's delve a bit deeper into each of these commands:
1. systemctl:
- Usage: `systemctl [command] [service]`
- Description: Used for controlling systemd services on modern Linux distributions.
Common commands include `start`, `stop`, `restart`, `enable`, `disable`, and `status`.
2. ps:
- Usage: `ps [options]`
- Description: Provides information about processes currently running on the system.
Options can be used to filter the output and display specific information about processes,
such as their PID, CPU and memory usage, user ownership, etc.
3. top:
- Usage: Simply type `top` in the terminal.
- Description: An interactive task manager that displays real-time information about
system processes, CPU usage, memory usage, and more. It continuously updates the display
and allows users to interactively manage processes.
4. kill:
- Usage: `kill [options] [PID]`
- Description: Used to terminate processes by sending them signals. The default signal sent
by `kill` is SIGTERM (15), which gracefully terminates the process. `kill -9` sends the
SIGKILL signal, which forcefully terminates the process.
5. crontab:
- Usage: `crontab [options]`
- Description: Used to manage user-specific cron jobs. Cron jobs are scheduled tasks that
run at specific intervals. The `crontab` command allows users to create, edit, list, and delete
their cron jobs. Jobs are defined in a cron table (`crontab`) file.
6. at:
- Usage: `at [options] time`
- Description: Used to schedule one-time tasks to be executed at a specific time in the
future. Unlike cron jobs, `at` jobs are executed only once at the specified time. The `at`
command allows users to specify the time when the command should be executed.
These commands and utilities are fundamental to managing processes and scheduling tasks
in a Linux environment, providing users with control over system resources and automation
capabilities.
System Monitoring Commands (top, df, dmesg, iostat 1, netstat, free etc.)
1. top command
The top command is super useful for monitoring what processes are using the most CPU and
memory on your Linux system. It gives you a dynamic real-time view that updates
frequently to show any changes. To use it simply open a terminal type “top” and hit enter.
You then see a table with different columns like CPU and MEM usage percentages, process
IDs, user accounts running each process, and the actual command names.
Command:
top
This command continuously updates a screen, displaying various system metrics. Processes
are sorted by default based on CPU usage in descending order, presenting the most resource-
intensive processes at the top for quick monitoring and identification.
Network Connections, Open Ports, Packets & Protocols using netstat Command
\
6. iotop command
The iotop command is great for monitoring disk I/O usage on a Linux system. It shows a live
view of the processes doing the heaviest disk read and write operations at any given moment.
Command:
sudo iotop
It will display columns with the I/O bandwidth used by each process, similar to how the top
shows CPU usage. It also calculates totals and percentages of disk activity. The main goal is
to identify processes that may be slowing your system down from disk I/O overloading.
Higher batch counts on the right often relate to heavier disk usage.
Display columns with the I/O bandwidth used by Each System Process
7. htop command
The htop command is a handy interactive process viewer that’s like an upgraded top version.
You see a real-time table of running processes with their CPU and memory usage, similar to
the top.
Color coding so you can easily spot high-usage processes.
Ability to scroll vertically and horizontally to see full commands, environment
variables, etc.
Tree view to see parent-child process relationships.
Easier process sorting and priority config.
Send signals like pause, and kill directly in the interface.
Command:
sudo htop
Linux system performance and CPU, memory, disk I/O, network, and processes
9. nmon command
The nmon command stands for Nigel’s performance Monitor. It’s a handy tool for graphing
and monitoring live system statistics like CPU, memory, disks, network, processes, and
temperatures.
Command:
nmon
This will bring up an interactive interface showing graphs and measurements updating in
real-time on the terminal. It logs everything for later analysis.
Nmon Tool Interface
Use these keys to get the results you want from the Table:
C: Shows CPU statistics and charts.
N: Shows network statistics and charts.
D: Shows disk statistics and charts.
M: Shows memory statistics and charts.
P: Shows detailed process statistics and charts.
T: Shows temperature/sensor readings.
/: Zooms graphs out/in on the time axis.
R: Provides resource monitoring advice.
s: Saves logs to CSV files for later analysis.
c: Configuration menu to customize stats intervals, durations, etc.
q: Quits and exits nmon.
3. halt: The halt command stops all processes on the system and powers off the computer.
Example:
halt # Halt the system immediately
4. init: This command is used to change the runlevel of the system. However, modern Linux
distributions often use systemd or other alternatives to manage system initialization and
service management.
Example:
init 0 # Shut down the system
init 6 # Reboot the system
6. systemctl: If your Linux distribution uses systemd, you can use systemctl to manage
system services, including starting, stopping, enabling, or disabling them.
Example:
bash
systemctl poweroff # Shuts down the system
systemctl reboot # Reboots the system
These commands are essential for system administrators to manage system shutdowns,
reboots, and maintenance tasks.
System logs monitor (/var/log)
Monitoring system logs in Linux, located in the `/var/log` directory, is crucial for
maintaining system health, diagnosing issues, and detecting potential security threats. Here's
a comprehensive guide on how to effectively monitor system logs in Linux:
1. Understanding Log Files:
- Linux systems generate various log files in the `/var/log` directory, each serving a
specific purpose. Common log files include:
- `syslog`: General system log capturing messages from system services, daemons, and
the kernel.
- `messages`: Similar to `syslog`, contains system messages including kernel and service
logs.
- `auth.log`: Records authentication attempts and related information.
- `kern.log`: Kernel-specific logs.
- `apache2/access.log` and `apache2/error.log`: Apache web server access and error logs.
- `mysql/error.log`: MySQL server error log.
- Other application-specific logs based on installed software.
4. Real-time Monitoring:
- Monitor log files in real-time using the `tail` command with the `-f` option.
tail -f /var/log/syslog
5. Log Rotation:
- Log files can grow large over time, consuming disk space. Use the `logrotate` utility to
rotate and compress log files periodically, managing disk space efficiently.
7. Customizing Logging:
- Configure logging behavior by modifying configuration files like `/etc/rsyslog.conf` or
`/etc/syslog-ng/syslog-ng.conf`. Customize log levels, destinations, and formatting to suit
specific requirements.
Changing System Hostname (hostnamectl)
To change the system hostname in Linux using `hostnamectl`, you can follow these steps:
4. Reboot (Optional):
Sometimes, a system reboot might be required for the changes to fully take effect. You can
either reboot your system or restart the `systemd-hostnamed` service:
sudo systemctl restart systemd-hostnamed
5. Verify Again:
After rebooting or restarting the service, verify the hostname once more to ensure it
persists after a reboot:
hostnamectl
By following these steps, you can effectively change the hostname of your Linux system
using `hostnamectl`.
Finding System Information (uname, cat /etc/redhat-release, cat
/etc/*rel*, dmidecode)
To find system information on a Linux system using the specified commands, you can open
a terminal and execute each command individually:
1. uname: Displays basic system information like kernel version, architecture, etc.
uname -a
2. cat /etc/redhat-release: Specifically, outputs information about the Red Hat release,
applicable to Red Hat-based systems like CentOS, Fedora, or RHEL.
cat /etc/redhat-release
3. cat /etc/*rel*: Displays release information from various Linux distributions. It looks for
files in the /etc directory that contain "rel" in their names.
cat /etc/*rel*
4. dmidecode: Provides detailed hardware information from the system's DMI (Desktop
Management Interface) table. This command usually requires root privileges.
sudo dmidecode
1. Ctrl+C: Sends an interrupt signal to the currently running process, typically stopping it.
It's often used to terminate a running command or program.
2. Ctrl+Z: Suspends the currently running process, returning control to the shell. You can
later resume the suspended process in the foreground or background using the `fg`
(foreground) or `bg` (background) commands.
3. Ctrl+D: Sends an end-of-file (EOF) marker to the shell, indicating the end of input. If
typed at the beginning of a line, it will log out of the current session (similar to typing `exit`).
6. Ctrl+K: Deletes all text from the cursor position to the end of the line.
7. Ctrl+U: Deletes all text from the cursor position to the beginning of the line.
9. Ctrl+R: Initiates a reverse search through command history, allowing you to search for
previously entered commands.
11. Ctrl+T: Swaps the current character under the cursor with the previous one.
12. Ctrl+Y: Pastes text that was previously deleted using Ctrl+U, Ctrl+K, or Ctrl+W.
13. Ctrl+S: Suspends terminal output (XOFF), useful for temporarily stopping terminal
output. Pressing Ctrl+Q resumes output (XON).
14. Ctrl+Q: Resumes terminal output (XON) after it has been stopped with Ctrl+S.
These are just a few of the many control keys available in Linux terminals, but they cover
some of the most commonly used ones for navigation, editing, and process management.
Terminal Commands (clear, exit, script)
In Linux, terminal commands are fundamental for navigating and interacting with the
system. Here are explanations for the commands you mentioned:
1. `clear`: This command is used to clear the terminal screen, which means it removes all the
previous commands and output from the terminal window. It's useful when the terminal
becomes cluttered, and you want to start with a clean slate.
Example:
clear
2. `exit`: This command is used to exit the current shell or terminal session. When you type
`exit` and press Enter, it terminates the current shell session and returns you to the previous
shell or logs you out of the system if you're in the main shell session.
Example:
exit
3. `script`: This command is used to record everything displayed on the terminal during a
session. It can be helpful for logging purposes or to capture the output of a series of
commands for later reference. When you run `script`, it starts recording the session to a file
specified or defaults to `typescript`.
Example:
script mysession.log
This will start recording the session into a file named `mysession.log`. To stop recording,
simply type `exit` or press `Ctrl + D`.
These commands are quite handy for managing your Linux terminal sessions efficiently.
Recover root Password (single user mode)
Recovering the root password in Linux using single-user mode involves booting into a
special mode where you have root access without needing the root password. Here's a
general procedure to do this:
1. Boot into GRUB menu: Restart your computer and when the GRUB menu appears
(usually after the BIOS/UEFI screen), select the Linux kernel you want to boot into but don't
press Enter yet.
2. Edit boot options: Press the "e" key to edit the boot parameters for the selected kernel.
3. Modify kernel parameters: Find the line that starts with "linux" or "linuxefi" and add
"init=/bin/bash" at the end of that line. This tells Linux to boot directly into a bash shell
instead of starting the usual init process.
4. Boot into single-user mode: Press Ctrl+X or F10 to boot with the modified parameters.
5. Remount the root filesystem: When the bash prompt appears, the root filesystem is
typically mounted as read-only. Remount it as read-write with the command:
mount -o remount,rw /
6. Change the root password: Now you can change the root password with the `passwd`
command:
passwd
After rebooting, you should be able to log in as root using the new password you set.
It's worth noting that accessing the system in this way can potentially pose a security risk, so
it's important to take appropriate precautions and ensure physical security of the machine.
SOS Report
An SOS report (or Supportability and Operating System Report) in Linux is a diagnostic data
collection utility used primarily in Red Hat-based distributions like Red Hat Enterprise
Linux (RHEL) and CentOS. It gathers comprehensive information about the system's
hardware, software, configuration, and logs, which can be useful for troubleshooting issues
or requesting support from vendors.
To generate an SOS report:
1. Install the sos package: If the `sos` package is not already installed on your system, you
can install it using your package manager. For example, on RHEL/CentOS, you can use the
following command:
sudo yum install sos
2. Run the sosreport command: Once installed, you can generate the SOS report by
running the `sosreport` command as root:
sudo sosreport
3. Follow the prompts: The `sosreport` command will prompt you for additional
information, such as whether to include additional logs or specific subsystem data. You can
generally accept the defaults unless you have a specific reason to include or exclude certain
information.
4. Wait for the report to be generated: Depending on the size and complexity of your
system, generating the SOS report may take some time. Once complete, the report will
typically be saved as a compressed archive file (e.g., `sosreport-<hostname>-
<timestamp>.tar.xz`) in the current directory.
5. Share the report: You can share the generated SOS report with your support provider or
analyze it yourself to troubleshoot issues.
The SOS report contains a wealth of information, including system configuration files,
hardware information, kernel parameters, network configuration, logs, and more. This
comprehensive data can be invaluable for diagnosing and resolving issues on Linux systems.
Environment variables
The environment variables are dynamic values that are stored within a system and used by
applications launched in shells or sub-shells. These variables have a name and their
respected value. The environment variable customizes the system performance and the
behavior of an application.
The environment is the track for a computer application to interact with the system. The
environment variable can have information about the default applications of the system, the
system locale, the path of the executable file and the keyboard layout setting, and more. The
environment variable makes an app available as per the system.
Common Environment Variables
Some standard environment variables are as follows:
1. PATH: Defines the directories where the system looks for executable files. When you type
a command in the terminal, the system searches for the executable file in these directories.
For example:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
5. LANG or LC_ALL: Specifies the system's default locale. It determines the language and
cultural conventions used by the system and applications.
LANG=en_US.UTF-8
9. DISPLAY: Defines the X display server to which GUI applications should connect.
DISPLAY=:0.0
10. TERM: Specifies the terminal type being used.
TERM=xterm
These environment variables play a significant role in configuring and customizing the
Linux environment, affecting how processes execute and interact with the system.