Linux System Administration

SurajSuraj
16 min read

Linux file editor(vi):

  • A text editor is a program that enables you to create and manipulate data (text) in a Linux file

  • There are several standard text editors available on most Linux systems

    • vi - visual editor

    • ed - standard line editor

    • ex - extended line editor

    • emacs - a full-screen editor

    • pico - beginner’s editor

    • vim - advanced version of vi

  • Our editor = vi ( available in almost every Linux distribution)

  • vi supplies commands for:

    • inserting and deleting text

    • replacing text

    • moving around the file

    • finding and substituting strings

    • cutting and pasting text

  • Most common keys:

    • i - insert

    • Esc - escape out of any mode

    • r - replace

    • d - delete

    • :q! - quit without saving

    • :wq! - quit and save

Difference Between vi and vim editor

FeatureViVim
Graphical InterfaceTerminal-basedIncludes a graphical user interface (GUI)
Extended FeaturesBasic functionalitySyntax highlighting, multiple undo/redo levels, language support
Visual Mode ImprovementsLimited visual mode capabilitiesEnhanced visual mode with block selection, visual line mode
Plugin SystemN/ASupports a wide range of plugins for extensibility
Backward CompatibilityStandard Vi commands and configsMaintains backward compatibility with Vi

“sed” Command:

  • Replace a string in a file with a newstring

  • Find and delete a line

  • Remove empty lines

  • Remove the first or n lines in a file

  • To replace tabs with spaces

  • Show defined lines from a file

  • Substitute within vi editor

If you want to change the name Kenny here with Lenny using sed command and “-i” used to insert this change permanently

sed -i 's/Kenny/lenny/g' surajkumar00

if you want to remove any word

sed 's/kumar//g' surajkumar00

If you want to delete all the lines that have the name suraj anyway it will be deleted. surajkumar00 here is the filename

sed '/suraj/d' suarjkumar00

If you have empty lines and want to get rid of those empty lines, $ here is nothing(empty)

sed -i '/^$/d' surajkumar00

If you want to remove the first line of your file

sed -i '1d' filename

If you want to remove the first two lines of your file

sed -i '1,2d' filename

If you want to remove the tab space in your file

sed -i 's/\\t/ /g' filename

if you want to add tab spaces

sed -i 's/ /\\t/g' filename

If you want to see files starting from specific lines

sed -n 12,18p filename

If you want to see the content of your files except lines 12 to 18

sed 12,18d filename

If you want to empty lines also in your content file

sed -i G filename

If you want to replace the name suraj with S but except line 8

sed '8!s/suraj/S/g' filename

Name changes while you are in the vi editor:

:%/suraj/mohit

this command is entered in the vi editor which changes the suraj with Mohit in all lines.

User Account Management:

Commands

  • useradd - adds new user

  • groupadd - adds a new group

  • userdel - delete a user

  • groupdel - delete a group

  • usermod :

    • I wanted to add goupname to a different group as well,

we can do it this way:

    usermod -G groupname username

Files

  • /etc/passwd
cat /etc/passwd

  • /etc/group
cat /etc/group

it shows group name:passwd(x): groupID(1003)

  • /etc/shadow : it is strictly for passwords for users we create
cat /etc/shadow
  • if you do not set the password in /etc/shadow for any name you not see the encrypted password

Example:

useradd -g superheroes -s /bin/bash -c "user description" -m -d /home/spiderman spiderman

-g is for the group, -s to give the shell environment, c is for user description, -m -d to define the user's home directory and the user itself.

Enable Password Aging

The /etc/login.defs file = Configuration control definitions for the login package.

The chage command

  • It is specifically used to set the parameters around the password. It’s not used to make any changes to the user account itself.

  • The chage command -per user

    • Example
    chage [-m mindays] [-M maxdays] [-d lastday] [-I inactive] [-E expiredate] [-W warndays] user

  • File = /etc/login.defs

    • PASS_MAX_DAYS 99999

    • PASS_MIN_DAYS 0

    • PASS_MIN_LEN 5

    • PASS_WARN_AGE 7

Switch users and sudo access

Commands

  • su - username

  • sudo command

  • visudo

used for:

usermod -aG wheel username

to verify

grep wheel /etc/group

used for:

sudo dmidecode

used for: tell you the size of the disk and all the information

sudo fdisk -l

File

  • /etc/sudoers : The /etc/sudoers file is used to configure sudo access for users and groups in Unix-like operating systems.

Monitor Users:

Commands:

  • who: to see how many people are logged into our system

  • last: give all information about the user who logged in since the first day

last | awk '{print $1}' | sort | uniq
  • w: It works pretty much the same as who but it will give you a little more information than who.

  • finger: It is the command that is added to your system. so, it does not come with your distribution. you have to add it, it’s a very powerful program. you need to install that.

Become root and run the below command:

yum install finger -y
  • id: if you run the id command it will give you information about the current directory user and if you place another user after the id command it’ll give that user’s information.
id 
id username

Talking to Users

Commands:

  • users: To check how many users are logged in

  • wall: to communicate with all users who are currently logged in

wall 
// then write you message here and press Ctrl + D
  • write
write username
//then write you message here

Linux Account Authentication

  • Types of accounts

    • Local accounts

    • Domain/Directory accounts

Difference between these:

TechnologyDescription
Active DirectoryMicrosoft's proprietary directory service for centralized management of network resources and authentication.
LDAPProtocol used for accessing and maintaining distributed directory information services over an IP network.
IDMIdentity Management is a broader term encompassing various technologies to manage user identities, access, and policies. A product by Red Hat.
WinBINDPart of Samba facilitates the integration of Linux/UNIX systems with Windows domains by providing a bridge between the two.
OpenLDAPAn open-source implementation of LDAP, offering a free, open, and extensible directory service.

System Utility Commands

Commands:

  • date: it shows you the date time and day and sets the date

  • uptime

uptime

  • hostname: Displays or sets the system's hostname.

  • uname / uname -a: Prints system information, including kernel version and system architecture.

  • which: Determines the location of an executable file in the user's PATH.

which pwd
// it will give /usr/bin/pwd
  • cal - simply gives you a calendar

  • bc - stands for binary calculator

Processes and Jobs

  • Applications = Service: Software programs designed to perform specific tasks, often provided as services to users or other programs.

  • Script: A sequence of executable commands, typically written in a scripting language, used to automate tasks.

  • Process: A running instance of a program in execution on a computer system.

  • Daemon: A background process that continuously runs and performs system-related tasks or provides services, such as network services.

  • Threads: Lightweight processes within a program that share the same memory space and resources, enabling concurrent execution.

  • Job: A unit of work or task scheduled or managed by an operating system or job scheduler.

Process/Service Commands

systemctl or service:

  • systemctl command is a new tool to control system services

  • It is available in version 7 and later and it replaces the service command

Usage example:

systemctl start | strop | status servicename.service (firewalld)
systemctl enable servicename.service
systemctl restart | reload servicename.service
systemctl list-units --all

The output has the following columns:

  • UNIT: The systemd unit name

  • LOAD: Whether the unit's configuration has been parsed by systemd. The configuration of loaded units is kept in memory.

  • ACTIVE: A summary state about whether the unit is active. This is usually a fairly basic way to tell if the unit has started successfully or not.

  • SUB: This is a lower-level state that indicates more detailed information about the unit. This often varies by unit type, state, and the actual method in which the unit runs.

  • DESCRIPTION: A short textual description of what the unit is/does.

To add a service under systemctl management:

create a unit file in

/etc/systemd/system/servicename.service

To control the system with systemctl

systemctl poweroff
systemctl halt
systemctl reboot

ps(process status) command

  • It displays all the currently running processes in the Linux system

Usage example:

ps = shows the processes of the current shell

PID = the unique process ID

TTY = terminal type the user logged in

TIME = amount of CPU in minutes and seconds that the process has been running

CMD = name of the command

Other commands

ps -e  = shows all running processes
ps aux = shows all running processes in BSD(Berkeley Software Distribution) format
ps -ef = shows all running processes in full format listing (most commonly used)
ps -u username = shows all processes by username

top command

  • used to show the Linux processes and it provides a real-time view of the running system.

  • This command shows the summary information of the system and the list of processes or threads which are currently managed by the Linux kernel

  • when the top command is executed then it goes into interactive mode and you can exit by hitting q.

Usage: top

PID: Shows the task’s unique process id

USER: Username of the owner of the task.

PR: The “PR” field shows the scheduling priorities of the process from the perspective of the kernel

NI: Represents a nice value of the task. a negative nice value implies higher priority and a positive nice value means lower priority.

VIRT: Total virtual memory used by the task

RES: Memory consumed by the process in RAM

SHR: Represents the amount of shared memory used by a task

S: This field shows the process state in the single-letter form

%CPU: Represents the CPU usage

%MEM: Shows the memory usage of task

TIME+: CPU time, the same as ‘TIME’ but reflecting more granularity through hundredths of a second.

top -u username = shows taks/processes by user owned
top then press c = shows commands absolute path
top then press k = kill a process by PID within top session
top then M and P = To sort all linux running process by Memory usage

kill Command

  • kill command is used to terminate processes manually

  • It sends a signal which ultimately terminates or kills a particular process or group of processes

Usage:

kill [option] [PID]

OPTION = Signal name or signal number

PID = Process ID

kill -l = to get a list of all signal names or signal number

The most used signals are:

kill PID = kill a process wiht default signal
kill -1 = restart
kill -2 = interrupt from the keyboard just like Ctrl C
kill -9 = Forcefully kill the process
kill -15 = kill a process gracefully.

other commands:

killall
pkill

crontab command

  • crontab command is used to schedule tasks

Usage:

crobtab -e = edit teh crontab
crontab -l = list the crontab entries
crontab -r = remove the crontab
crond = crontab daemon/service that manages scheduling
systemctl status crond = to manage the crond service

Create a crontab entry by scheduling a task:

crontab -e
schedule, echo "this is my first crontab entry" > crontab-entry

at command

  • at command is like crontab which allows you to schedule jobs but only once

  • When the command is run it will enter interactive mode and you can get out by pressing Ctrl D

Usage:

at HH:MM PM = Schedule a job
atq = lists the at entries
atrm # = remove at entry (the # here is the entry number what the job will have)
systemctl status atd = ro manage the atd service

Create an entry by scheduling a task:

at 4:45PM -> enter
echo "this is my first at entry" > at-entry
Ctrl D

Other commands:

at 2:34 AM 101621 = schedule a job to run on oct 16th, 2021 at 2:34am
at 4PM + 4 days   = schedule a job at 4pm four days from now
at now + 5 hours  = schedule a job to run five hours from now
at 8:00 AM Sun    = schedule a job to 8am on coming sunday
at 10:00 AM next month = schdule a job to 10am next month

Additional Cron Jobs

  • By default, there are 4 different types of cron jobs

    • Hourly

    • Daily

    • Weekly

    • Monthly

  • All the above crons are setup in

      /etc/cron.__(directory)
    
  • The timing for each is set in

      /etc/anacrontab -- except hourly
    
  • For hourly

      /etc/cron.d/0hourly.
    

Process management

  • Background = Ctrl -z, jobs, and bg

  • Foreground = fg

  • Run process even after exit = nohup process &

    OR = nohup process > /dev/null 2>&1 &

  • kill a process by name = pkill

  • process priority = nice (e.g. nice -n 5 process)

    • The niceness scale goes from -20 to 19. The lower the number more priority that task gets
  • Process monitoring = top

  • List process = ps .

System Monitoring

  • top: Displays real-time system process information.

  • df: Shows disk space usage.

  • dmesg: Prints kernel message buffer.

  • iostat: Reports CPU and input/output statistics.

  • netstat: Displays network connections.

  • free: Shows memory usage.

  • cat /proc/cpuinfo: Prints CPU information.

  • cat /proc/meminfo: Displays memory-related information.

Log Monitoring

Another and most important way of system administration is to log monitor:

  • Log Directory = /var/log: Location of system log files.

  • boot: Records system boot messages.

  • chronyd = NTP: Manages network time synchronization (NTP).

  • cron: Scheduler for running recurring tasks.

  • maillog: Logs mail server activity.

  • secure: Records security-related messages.

  • messages: General system messages log.

  • httpd: Apache HTTP Server log.

System Maintenance Commands

  • shutdown: Command used to safely power off or reboot the system.

  • init 0-6: Runlevel commands for system state management (0: Halt, 6: Reboot).

  • reboot: Command to restart the system.

  • halt: Command to halt or power off the system.Changing System Hostname

Changing the system Hostname

hostnamectl set-hostname newhostnaeme
  • Version 7 = Edit /etc/hostname: Set the system's hostname in Unix-like operating systems by editing the /etc/hostname file.

  • Version 6 = Edit /etc/sysconfig/network: Configure network settings, including hostname, in Unix-like operating systems by editing the /etc/sysconfig/network file.

Finding System Information

There are a few commands to do so:

  • cat /etc/redhat-release: Displays the version and release information of the Red Hat Enterprise Linux distribution.

  • uname -a: Prints system information including kernel version, architecture, and other details.

  • dmidecode: Retrieves hardware information from the system's Desktop Management Interface (DMI) table.

cat /etc/redhat-release
uname -a
dmidecode

System Architecture

  • The main difference between a 32-bit and 64-bit CPU is the number of calculations per second they can perform.
Aspect32-bit CPU64-bit CPU
Number of Bits3264
Calculation SpeedSlowerFaster
Multi-core SupportYesYes
Memory LimitationsLimited to 4 GB RAMCan address more
Software CompatibilityLimitedExtensive
Performance BenefitsLimitedEnhanced
OS SupportSupportedSupported
Upgrade ConsiderationsSoftware CompatibilitySoftware Compatibility

To check the Architecture

  • In Linux
arch
  • In Windows
go to my computer -> properties

Terminal Control Kyes

  • Several key combinations on your keyboard usually have a special effect on the terminal.

The most common control keys are listed below:

CTRL-u = erase everything you have typed on the command line
CTRL-c = stop/kill a command
CTRL-z = suspend a command
CTRL-d = exit from an interactive program (signal end of data).

Terminal Commands

clear = to clear your screen
exit = exit out of the shell, terminal or a user session
 script = the script command stores terminal activities in a log file that can be named by a user, when a name is not provided by a user, the default file name, typescript is used

To create a script, that'll record everything that you do in the terminal

script logfile-activity.log

Recover Root Password

These will be the steps to do so:

  • Restart your computer

  • Edit grub

  • Change password

  • reboot

SOS Report

  • When you are really in trouble and need help

  • Collect and package diagnostic and support data

Package name sos-version

Command:

sosreport

// after entering this command further proceed with it

Environment Variables

  • An environment variable is a dynamic-named value that can affect how running processes behave on a computer. They are part of the environment in which a process runs.

  • Simply put, it's a set of defined rules and values to build an environment.

  • For example see this house, it has defined places:

  • To view all environment variable

      printevn OR env
    
  • To view ONE environment variable

      echo $SHELL OR
      echo $PATH
    
  • To set the environment variable

      export TEST=1
      echo $TEST
    
  • To set environment variables permanently

      vi .bashrc
      TEST='123'
      export TEST
    
  • To set global environment variables permanently

      vi /etc/profile OR /etc/bashrc
      TEST='123'
      export TEST
    

Special Permissions with setuid, setgid, and sticky bit

  • All permissions on a file or directory are referred to as bits

  • There are 3 additional permissions in Linux

    • setuid: bit tells Linux to run a program with the effective user id of the owner instead of the executor: (e.g passwd command) → /etc/shadow

    • setgid: bit tells Linux to run a program with the effective group id of the owner instead of the executor: (e.g. locate or wall command)

      • Please note: This is present for only files that have executable permissions
    • sticky bit: a bit set on files/directories that allows only the owner or root to delete those files.

  • Note: setuid and setgid are not actual commands

  • To assign special permissions at the user level

chmod u+s xyz.sh
  • To assign special permissions at the group level
chmod g+s xyz.sh
  • To assign special permission at the user or group level
chmod u-s xyz.sh
chmod g-s xyz.sh
  • To find all executables in Linux with setuid and setgid permissions
find / -perm /6000 -type f

Please Note: These bits work on c programming executables not on bash shell scripts.

Sticky bit:

  • It is assigned to the last bit of permissions
-rwx rwx rwt (so this t here is sticky bit)
  • why? : Because everyone, any user in the Linux system can write to this directory, but that user, even though that user has their write permissions, cannot delete that directory. This is a way to protect that directory from accidental deletion from the system.

  • example of /tmp directory

So with this blog our Linux learning end that doesn't mean there nothing to explore more, we have just get familiar with very important topic here but we can go for more if we want. Okay then I'll see you in next Computer Networking Blog 👋.

10
Subscribe to my newsletter

Read articles from Suraj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Suraj
Suraj

I'm a passionate developer with a background in web development and a keen interest in emerging technologies. I'm currently expanding my skillset by learning DevOps and Cloud Native concepts. I contribute to open-source projects and share my knowledge as a technical writer on Hashnode. In addition, I'm exploring the exciting world of Artificial Intelligence and Machine Learning.