0% found this document useful (0 votes)
28 views

Module V - System Administration

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Module V - System Administration

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

SYSTEM ADMINISTRATION

There are three types of accounts on a Unix system −


Root account
This is also called superuser and would have complete and unfettered control of the
system. A superuser can run any commands without any restriction. This user should be
assumed as a system administrator.
System accounts
System accounts are those needed for the operation of system-specific components for
example mail accounts and the sshd accounts. These accounts are usually needed for
some specific function on your system, and any modifications to them could adversely
affect the system.
User accounts
User accounts provide interactive access to the system for users and groups of users.
General users are typically assigned to these accounts and usually have limited access
to critical system files and directories.
Unix supports a concept of Group Account which logically groups a number of accounts.
Every account would be a part of another group account. A Unix group plays important
role in handling file permissions and process management.
Managing Users and Groups
There are four main user administration files −
• /etc/passwd − Keeps the user account and password information. This file holds
the majority of information about accounts on the Unix system.
• /etc/shadow − Holds the encrypted password of the corresponding account. Not
all the systems support this file.
• /etc/group − This file contains the group information for each account.
• /etc/gshadow − This file contains secure group account information.

• The following table lists out commands that are available on majority
of Unix systems to create and manage accounts and groups −

Sr.No. Command & Description

1 useradd Adds accounts to the system

2 usermod Modifies account attributes

3 userdel Deletes accounts from the system


4 groupadd Adds groups to the system

5 groupmod Modifies group attributes

6 groupdel Removes groups from the system

Create a Group
We need to create groups before creating any account otherwise, we can make use of the
existing groups in our system. We have all the groups listed in /etc/groups file.
All the default groups are system account specific groups and it is not recommended to
use them for ordinary accounts. So, following is the syntax to create a new group account

groupadd [-g gid [-o]] [-r] [-f] groupname
The following table lists out the parameters −

Sr.No. Option & Description

-g GID
1
The numerical value of the group's ID

-o
2
This option permits to add group with non-unique GID

-r
3
This flag instructs groupadd to add a system account

-f
4 This option causes to just exit with success status, if the specified group already exists. With
specified GID already exists, other (unique) GID is chosen

groupname
5
Actual group name to be created

If you do not specify any parameter, then the system makes use of the default values.
Following example creates a developers group with default values, which is very much
acceptable for most of the administrators.
$ groupadd developers
Modify a Group
To modify a group, use the groupmod syntax −
$ groupmod -n new_modified_group_name old_group_name
To change the developers_2 group name to developer, type −
$ groupmod -n developer developer_2
Here is how you will change the financial GID to 545 −
$ groupmod -g 545 developer
Delete a Group
We will now understand how to delete a group. To delete an existing group, all you need
is the groupdel command and the group name. To delete the financial group, the
command is −
$ groupdel developer
This removes only the group, not the files associated with that group. The files are still
accessible by their owners.
Create an Account
Following is the syntax to create a user's account −
useradd -d homedir -g groupname -m -s shell -u userid accountname
The following table lists out the parameters −

Sr.No. Option & Description

-d homedir
1
Specifies home directory for the account

-g groupname
2
Specifies a group account for this account

-m
3
Creates the home directory if it doesn't exist

-s shell
4
Specifies the default shell for this account
-u userid
5
You can specify a user id for this account

accountname
6
Actual account name to be created

If you do not specify any parameter, then the system makes use of the default values.
The useradd command modifies the /etc/passwd, /etc/shadow, and /etc/group files
and creates a home directory.
Following is the example that creates an account mcmohd, setting its home directory
to /home/mcmohd and the group as developers. This user would have Korn Shell
assigned to it.
$ useradd -d /home/mcmohd -g developers -s /bin/ksh mcmohd
Before issuing the above command, make sure you already have the developers group
created using the groupadd command.
Once an account is created you can set its password using the passwd command as
follows −
$ passwd mcmohd20
Changing password for user mcmohd20.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
When you type passwd accountname, it gives you an option to change the password,
provided you are a superuser. Otherwise, you can change just your password using the
same command but without specifying your account name.
Modify an Account
The usermod command enables you to make changes to an existing account from the
command line. It uses the same arguments as the useradd command, plus the -l
argument, which allows you to change the account name.
For example, to change the account name mcmohd to mcmohd20 and to change home
directory accordingly, you will need to issue the following command −
$ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20
Delete an Account
The userdel command can be used to delete an existing user. This is a very dangerous
command if not used with caution.
There is only one argument or option available for the command .r, for removing the
account's home directory and mail file.
For example, to remove account mcmohd20, issue the following command −
$ userdel -r mcmohd20
If you want to keep the home directory for backup purposes, omit the -r option. You can
remove the home directory as needed at a later time.

STARTING UP AND SHUTTING DOWN THE SYSTEM


1.
o init or systemd (depending on your Unix variant) manages system services
and starts essential services.
o System services like networking, logging, and other background processes
are launched.
2. Login Prompt:
o When the startup process completes, you’ll see a login prompt in terminal
mode or a login screen in GUI mode.
o Enter your username and password to access the system.
2. Shutting Down the Unix System
Shutting down the system properly is critical to prevent data corruption or file system
issues. Only administrators (root or users with sudo privileges) can shut down the
system.
Common Shutdown Commands:
1. Shut Down Immediately:
sudo shutdown now
o This will immediately begin the shutdown process.
2. Shut Down with a Delay:
sudo shutdown +m
o Replace +m with the number of minutes you want to wait before shutdown.
o Example: sudo shutdown +10 will shut down the system in 10 minutes.
3. Shut Down at a Specific Time:
sudo shutdown hh:mm
o Replace hh:mm with the specific time (24-hour format) you want the
system to shut down.
o Example: sudo shutdown 22:00 will shut down at 10:00 PM.
4. Shut Down with a Custom Message:
sudo shutdown +m "Custom message"
o This sends a notification to logged-in users about the shutdown, with your
custom message.
5. Reboot the System:
sudo reboot
o This command will immediately reboot the system.
6. Halt the System:
sudo halt
o This command stops all processes and halts the system, but it does not
power it off.
7. Power Off the System:
sudo poweroff
o This command shuts down the system and turns off the power.
Example Shutdown Command:
sudo shutdown -h now
The -h flag specifies that the system should halt (shutdown) after completing the
shutdown sequence.
3. Important Considerations
• Warn Users: If you are shutting down a multi-user system, notify all users with
shutdown messages to allow them time to save their work.
• Check for Running Processes: Use commands like ps or top to ensure no critical
tasks are running before shutdown.
• Emergency Shutdown: In cases where the system is unresponsive, a forced
shutdown (e.g., holding down the power button) may be necessary but should be
avoided if possible as it can lead to file system corruption.

DISK MANAGEMENT IN UNIX


Disk management in Unix involves organizing, partitioning, and maintaining disk storage
to ensure optimal system performance, efficient storage use, and data safety. Here’s a
comprehensive guide on disk management in Unix:
1. Disk Partitioning and Formatting
Partitions divide the disk into separate sections, allowing you to manage different types
of data or systems more efficiently.
Partitioning Tools:
• fdisk: Common tool for managing MBR (Master Boot Record) partitions.
• parted: For creating both MBR and GPT (GUID Partition Table) partitions, often
used for larger disks.
Basic Partitioning Commands:
1. List Disk Partitions:
sudo fdisk -l
This shows all connected disks and their partitions.
2. Create or Modify Partitions (fdisk):
sudo fdisk /dev/sdX
o Replace /dev/sdX with the actual disk name (e.g., /dev/sda).
o You can then use commands like n for a new partition, d to delete a
partition, and w to write changes.
3. Formatting Partitions: After partitioning, format the partition to a filesystem:
sudo mkfs -t ext4 /dev/sdX1
o Replace /dev/sdX1 with the partition you want to format.
o ext4, xfs, and btrfs are common filesystems.
2. Mounting and Unmounting Partitions
Mounting attaches a partition or device to the filesystem, while unmounting safely
detaches it.
Basic Commands:
1. Mount a Partition:
sudo mount /dev/sdX1 /mnt/mountpoint
o Replace /dev/sdX1 with the partition and /mnt/mountpoint with the
directory you want to mount to.
2. Unmount a Partition:
sudo umount /mnt/mountpoint
o Or specify the device name directly:
sudo umount /dev/sdX1
3. Permanent Mounts (Edit /etc/fstab):
o To automatically mount partitions at boot, add entries to the /etc/fstab file:
/dev/sdX1 /mountpoint ext4 defaults 0 2
o Each line specifies the device, mount point, filesystem type, mount
options, and dump/pass values.
3. Managing Disk Space
Monitoring and managing disk usage helps prevent issues with storage limits.
Common Tools and Commands:
1. Check Disk Usage:
df -h
o Displays the amount of used and available disk space on each filesystem
in a human-readable format.
2. Check Directory Size:
du -sh /path/to/directory
o Shows the size of a specified directory.
3. Disk Usage Analysis Tools:
o ncdu: A more interactive way to see which directories are taking up the
most space.
o lsblk: Lists block devices, showing the hierarchy of mounted and
unmounted disks and partitions.
4. LVM (Logical Volume Management)
LVM is a powerful tool for flexible disk management, especially useful for managing
dynamic storage needs.
Basic LVM Commands:
1. Create Physical Volume:
sudo pvcreate /dev/sdX1
2. Create Volume Group:
sudo vgcreate my_volume_group /dev/sdX1
3. Create Logical Volume:
sudo lvcreate -L 10G -n my_logical_volume my_volume_group
o -L 10G: Sets the logical volume size to 10GB.
o -n: Specifies the name of the logical volume.
4. Extend Logical Volume:
sudo lvextend -L +5G /dev/my_volume_group/my_logical_volume
o Increases the logical volume size by 5GB.
5. Resize Filesystem on Logical Volume:
sudo resize2fs /dev/my_volume_group/my_logical_volume
o This resizes the filesystem to match the new logical volume size.
5. Swap Management
Swap space acts as additional memory when RAM is full, preventing the system from
crashing due to memory shortages.
Managing Swap Space:
1. Create a Swap File:
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
2. Make Swap Permanent: Add the swap file to /etc/fstab:
/swapfile none swap sw 0 0
3. Check Swap Usage:
free -h
6. Disk Error Checking
Regularly checking for errors on disks is essential for system health.
Commands:
1. Check Filesystem Health:
sudo fsck /dev/sdX1
o fsck scans the specified filesystem for errors and repairs them if possible.
2. SMART Disk Monitoring:
sudo smartctl -a /dev/sdX
o Provides detailed health information on disks that support S.M.A.R.T. (Self-
Monitoring, Analysis, and Reporting Technology).

MONITORING SYSTEM USAGE IN UNIX


Monitoring system usage in Unix is essential for maintaining performance, diagnosing
issues, and optimizing resource utilization. Here’s a comprehensive guide on how to
monitor CPU, memory, disk, network, and process usage in Unix.
1. CPU Usage Monitoring
Monitoring CPU usage helps identify processes that consume excessive CPU resources,
which can lead to slower performance.
Common Commands:
1. top:
o Displays a dynamic, real-time view of running processes and system
resource usage.
o To run:
top
o Key columns: %CPU for CPU usage and %MEM for memory usage.
2. htop (Improved version of top):
o Offers a more interactive view, with color-coded resource usage.
o Often needs to be installed separately:
htop
3. mpstat:
o Provides detailed information about CPU utilization per core.
o Often included in the sysstat package:
mpstat -P ALL
4. iostat:
o Shows CPU and I/O usage, ideal for checking how much CPU time is spent
on I/O processes.
o Run with:
iostat

2. Memory Usage Monitoring


Monitoring memory usage helps ensure that the system is not overcommitted and helps
detect memory leaks.
Common Commands:
1. free:
o Provides a quick overview of used, free, and available memory.
o Run with:
free -h
o The -h flag displays values in human-readable format.
2. vmstat:
o Shows information on memory, processes, I/O, and CPU in real-time.
o Run with:
vmstat 2
o The number 2 updates the output every 2 seconds.
3. top / htop:
o Both top and htop also display real-time memory usage under the %MEM
column.
3. Disk Usage Monitoring
Tracking disk usage helps avoid running out of storage, which can lead to system crashes
or degraded performance.
Common Commands:
1. df:
o Reports free and used disk space on all mounted filesystems.
o Run with:
df -h
o The -h flag outputs in a human-readable format (e.g., GB, MB).
2. du:
o Shows the disk usage of files and directories, useful for identifying large
files.
o Run with:
du -sh /path/to/directory
o -s summarizes the total size, while -h formats it for readability.
3. iostat (also for disk I/O):
o In addition to CPU usage, iostat provides insights into disk I/O operations,
useful for identifying disk-intensive processes.
4. Network Usage Monitoring
Monitoring network usage is critical for managing bandwidth and troubleshooting
connectivity issues.
Common Commands:
1. ifconfig (for checking network interfaces):
o Shows network interfaces and basic stats.
o Run with:
ifconfig
o For newer systems, ip may be preferred:
ip addr show
2. netstat:
o Displays active connections, listening ports, and network statistics.
o Run with:
netstat -tuln
o -tuln lists TCP and UDP connections in numeric format.
3. ss:
o A faster alternative to netstat, provides detailed socket statistics.
o Run with:
ss -tuln
4. iftop (real-time bandwidth monitoring):
o Shows a real-time view of network traffic by connection.
o May require installation:
sudo apt install iftop
iftop
5. nload:
o A visual, real-time monitor for incoming and outgoing network traffic.
o May need to be installed:
sudo apt install nload
nload
5. Process Monitoring
Identifying and managing resource-hungry processes is essential for stable system
performance.
Common Commands:
1. ps:
o Displays the currently running processes.
o For a snapshot of all processes:
ps aux
o Columns like %CPU and %MEM show CPU and memory usage for each
process.
2. top / htop:
o Both top and htop give real-time views of processes, with sortable columns
like CPU and memory usage.
o Press k in top to kill a process by entering its PID (Process ID).
3. pgrep / pkill:
o pgrep searches for processes by name:
pgrep process_name
o pkill terminates processes by name:
sudo pkill process_name
4. lsof:
o Lists open files and the processes that opened them, useful for
troubleshooting resource locks or open network connections.
o Run with:
sudo lsof
6. System Logs for Usage and Errors
Logs are essential for diagnosing system performance and usage issues.
1. /var/log/syslog or /var/log/messages:
o General system log that records events, warnings, and errors.
o View logs with:
tail -f /var/log/syslog
2. dmesg:
o Displays messages from the kernel ring buffer, useful for hardware-related
errors and startup messages.
o Run with:
dmesg | less
3. journalctl (for systems using systemd):
o Shows logs managed by systemd, including boot logs.
o Run with:
journalctl -xe

7. Automating Monitoring with Tools


1. sar:
o Part of the sysstat package, sar collects and reports historical data on
system activity.
o Example command to view CPU usage over time:
sar -u 1 5
2. Nagios, Zabbix, and Prometheus:
o These are dedicated monitoring tools that can track multiple system
metrics, send alerts, and provide dashboards.
3. Monitoring Scripts:
o Simple scripts can automate alerts for high CPU/memory/disk usage. For
example:
#!/bin/bash
if [ $(df / | awk 'NR==2 {print $5}' | sed 's/%//') -gt 90 ]; then
echo "Disk usage is above 90%" | mail -s "Disk Alert" [email protected]
fi
Summary
Monitoring system usage in Unix involves:
• CPU Usage: Using top, htop, mpstat.
• Memory Usage: Using free, vmstat.
• Disk Usage: Using df, du, iostat.
• Network Usage: Using netstat, iftop, nload.
• Process Monitoring: Using ps, top, pgrep.
• Logs: Checking /var/log and using journalctl.
Regular monitoring ensures stable, optimized, and reliable system performance.

Ensuring System Security


Ensuring system security in Unix is crucial to protect sensitive data, prevent unauthorized
access, and maintain system integrity. Here’s a comprehensive guide on key security
practices in Unix systems:
1. User and Access Management
Managing user accounts, groups, and permissions is essential to prevent unauthorized
access and control user privileges.
Key Practices:
1. Least Privilege Principle:
o Grant users only the permissions they need for their roles.
o Avoid giving root privileges to regular users.
o Use sudo for granting temporary admin rights instead of logging in as root.
2. User Accounts:
o Create new users with limited permissions:
sudo adduser username
o Disable unused accounts by locking them:
sudo usermod -L username
o Delete unnecessary accounts:
sudo deluser username
3. Use Strong Passwords:
o Enforce strong password policies using tools like chage to set password
expiration policies.
o Password Complexity: Use a mix of uppercase, lowercase, numbers, and
special characters.
o Example command to set password expiration:
sudo chage -M 90 -m 10 username # Set max days, min days for password change
4. Use SSH Keys Instead of Passwords:
o Disable password-based login and enable SSH key-based login for secure
access.
o Generate SSH key pairs with:
ssh-keygen -t rsa
5. Disable Root Login:
o Prevent direct root login over SSH by setting PermitRootLogin no in the
/etc/ssh/sshd_config file.
o Restart SSH to apply changes:
sudo systemctl restart sshd
2. File and Directory Permissions
Configuring file permissions ensures that sensitive files and directories are accessible
only to authorized users.
Commands:
1. Set File Permissions:
o Use chmod to set file and directory permissions based on user, group, and
others.
o Example:
chmod 640 filename
2. Set Ownership:
o Use chown to change the owner and group of files and directories.
o Example:
chown user:group filename
3. Use Access Control Lists (ACLs) for Fine-Grained Control:
o ACLs provide more granular permissions beyond the basic Unix
permissions.
o Example of setting an ACL:
setfacl -m u:username:rwx /path/to/file
3. Network Security
Securing network connections and limiting exposure to external threats is essential to
protect Unix systems from unauthorized access.
Key Practices:
1. Firewall Configuration (Using ufw or iptables):
o UFW (Uncomplicated Firewall) for easy firewall management:
sudo ufw enable
sudo ufw allow ssh
sudo ufw allow 80/tcp # Allow HTTP
sudo ufw allow 443/tcp # Allow HTTPS
o iptables for advanced configuration:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
2. Disable Unused Ports and Services:
o Identify and stop unnecessary services to minimize attack surfaces.
o List services:
sudo systemctl list-unit-files --type=service
3. SSH Hardening:
o Disable Password Authentication:
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/'
/etc/ssh/sshd_config
sudo systemctl restart sshd
o Limit SSH Access:
▪ Allow specific users to connect via SSH by adding:
AllowUsers user1 user2
▪ Set this in /etc/ssh/sshd_config.
4. Enable TCP Wrappers:
o Configure /etc/hosts.allow and /etc/hosts.deny files to control which IP
addresses can access the system.
4. System Updates and Patching
Keeping the system and its software up-to-date is vital to protect against known
vulnerabilities.
Key Practices:
1. Update the OS Regularly:
o For Debian-based systems:
sudo apt update && sudo apt upgrade -y
o For Red Hat-based systems:
sudo yum update -y
2. Enable Automatic Updates (Optional but recommended):
o Install and configure automatic updates on Debian-based systems with:
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
5. Logging and Auditing
Logging and monitoring activities allow you to track potential security incidents and
investigate unusual behavior.
Key Practices:
1. System Logs:
o Monitor /var/log/syslog or /var/log/messages for important system events.
o Check /var/log/auth.log (on Debian-based systems) for login attempts and
authentication events.
2. Auditd:
o The Linux Audit Daemon (auditd) helps track security-relevant events.
o Install auditd:
sudo apt install auditd
sudo systemctl start auditd
o Configure rules in /etc/audit/audit.rules for specific monitoring (e.g.,
tracking file changes).
3. Intrusion Detection Systems (IDS):
o Use tools like AIDE (Advanced Intrusion Detection Environment) to
monitor filesystem changes.
o Install and initialize AIDE:
sudo apt install aide
sudo aideinit
o Compare the filesystem against the baseline with:
sudo aide --check
6. Security Hardening
Security hardening minimizes vulnerabilities by reducing the system’s attack surface.
Key Practices:
1. Disable Unnecessary Services:
o Use systemctl or chkconfig (on older systems) to disable services not
needed for system operation.
2. Remove Unused Packages:
o Regularly remove packages and dependencies not required for system
functionality.
o Example:
sudo apt remove package_name
3. Disable Core Dumps:
o Prevent core dumps, which could expose sensitive data, by setting:
echo '* hard core 0' | sudo tee -a /etc/security/limits.conf
4. Enforce Secure Kernel Parameters:
o Edit /etc/sysctl.conf to apply secure kernel parameters. Common settings
include:
net.ipv4.ip_forward = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.tcp_syncookies = 1
5. Use SELinux or AppArmor:
o Enabling SELinux (on Red Hat-based systems) or AppArmor (on Debian-
based systems) enhances access control.
o To check and configure SELinux:
sestatus
7. Backup and Recovery
Regular backups ensure data is safe and can be restored in case of data loss or a security
incident.
Key Practices:
1. Automate Regular Backups:
o Use rsync, tar, or dedicated backup tools to create regular backups.
o Example using rsync:
rsync -av /source/directory /backup/directory
2. Offsite and Encrypted Backups:
o Store backups offsite or on cloud storage, and ensure they are encrypted.
3. Test Backup Restores:
o Periodically test the backup restore process to ensure data integrity.
Summary
Securing a Unix system involves multiple layers:
• User and Access Management: Control who has access.
• File Permissions: Limit file access to authorized users.
• Network Security: Harden network access points.
• System Updates: Keep software patched.
• Logging and Auditing: Track and investigate events.
• System Hardening: Reduce potential vulnerabilities.
• Backups: Ensure data can be restored if compromised.
Adopting these practices will strengthen your Unix system’s security and help safeguard
it against unauthorized access and potential threats.

You might also like