# Linux System Administration

### 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

| Feature | Vi | Vim |
| --- | --- | --- |
| Graphical Interface | Terminal-based | Includes a graphical user interface (GUI) |
| Extended Features | Basic functionality | Syntax highlighting, multiple undo/redo levels, language support |
| Visual Mode Improvements | Limited visual mode capabilities | Enhanced visual mode with block selection, visual line mode |
| Plugin System | N/A | Supports a wide range of plugins for extensibility |
| Backward Compatibility | Standard Vi commands and configs | Maintains backward compatibility with Vi |

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707918408336/e1d88583-be0f-4459-9f10-489d7a762423.png align="center")

* Websites [to learn “](https://www.openvim.com)[vim” -](https://vim-adventures.com) [intera](https://www.openvim.com)cti[ve learning tools](https://www.openvim.com)
    
    * [https://www.openvim.com](https://www.openvim.com)
        
    * [https://www.vimgenius.com](https://www.vimgenius.com)
        
    * [https:/https://vim-adventures.com](https://vim-adventures.com)
        

### “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

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

if you want to remove any word

```bash
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

```bash
sed '/suraj/d' suarjkumar00
```

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

```bash
sed -i '/^$/d' surajkumar00
```

If you want to **remove the first line** of your file

```bash
sed -i '1d' filename
```

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

```bash
sed -i '1,2d' filename
```

If you want to **remove the tab space** in your file

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

if you want to add tab spaces

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

If you want to see files starting from specific lines

```bash
sed -n 12,18p filename
```

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

```bash
sed 12,18d filename
```

If you want to empty lines also in your content file

```bash
sed -i G filename
```

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

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

Name changes while you are in the vi editor:

```bash
:%/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:
    
    ```bash
    usermod -G groupname username
    ```
    

**Files**

* /etc/passwd
    

```bash
cat /etc/passwd
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707918994971/78f97c76-8b8c-4a6c-ae23-988fc119109f.png align="center")

* /etc/group
    

```bash
cat /etc/group
```

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

* /etc/shadow : it is strictly for passwords for users we create
    

```bash
cat /etc/shadow
```

* if you do not set the password in /etc/shadow for any name you not see the encrypted password
    

Example:

```bash
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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707919051694/6d83c470-5860-4246-b73e-81ebcd9e9f96.png align="center")

## 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
        
    
    ```bash
    chage [-m mindays] [-M maxdays] [-d lastday] [-I inactive] [-E expiredate] [-W warndays] user
    ```
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707919108513/5daafc72-1c4a-4857-99a7-fb52f4961f04.png align="center")

* File = /etc/login.defs
    
    * PASS\_MAX\_DAYS 99999
        
    * PASS\_MIN\_DAYS 0
        
    * PASS\_MIN\_LEN 5
        
    * PASS\_WARN\_AGE 7
        

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707919148720/8cde8cbb-31d4-4b50-9950-f8d26cefb54d.png align="center")

## Switch users and sudo access

Commands

* `su - username`
    
* `sudo command`
    
* `visudo`
    

used for:

```bash
usermod -aG wheel username
```

to verify

```bash
grep wheel /etc/group
```

used for:

```bash
sudo dmidecode
```

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

```bash
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
    

```bash
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:

```bash
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.
    

```bash
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
    

```bash
wall 
// then write you message here and press Ctrl + D
```

* write
    

```bash
write username
//then write you message here
```

## Linux Account Authentication

* Types of accounts
    
    * Local accounts
        
    * Domain/Directory accounts
        

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707919362136/4d64921d-87a9-46e2-81fb-2b3b7fdb456a.png align="center")

## Difference between these:

| Technology | Description |
| --- | --- |
| Active Directory | Microsoft's proprietary directory service for centralized management of network resources and authentication. |
| LDAP | Protocol used for accessing and maintaining distributed directory information services over an IP network. |
| IDM | Identity Management is a broader term encompassing various technologies to manage user identities, access, and policies. A product by Red Hat. |
| WinBIND | Part of Samba facilitates the integration of Linux/UNIX systems with Windows domains by providing a bridge between the two. |
| OpenLDAP | An 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
    

```bash
uptime
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707919406036/0560c459-155d-4aee-93c0-55550109acac.png align="center")

* `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.
    

```bash
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:

```bash
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[:](https://vim-adventures.com)

* **UNIT**: The **systemd** unit name
    
* **LOAD**: Whether the unit's configuration has been parsed by systemd. The confi[g](https://vim-adventures.com)uration 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

```bash
/etc/systemd/system/servicename.service
```

To control the system with systemctl

```bash
systemctl poweroff
systemctl halt
systemctl reboot
```

### **ps(process status) command**

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

Usage example:

```bash
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

```bash
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.

```bash
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:

```bash
kill [option] [PID]
```

OPTION = Signal name or signal number

PID = Process ID

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

The most used signals are:

```bash
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:

```bash
killall
pkill
```

### crontab command

* crontab command is used to schedule tasks
    

Usage:

```bash
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
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707916998776/4e42f9e4-5167-4cdd-825b-f41e7363a31f.png align="center")

Create a crontab entry by scheduling a task:

```bash
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:

```bash
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:

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

Other commands:

```bash
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
    
    ```bash
    /etc/cron.__(directory)
    ```
    
* The timing for each is set in
    
    ```bash
    /etc/anacrontab -- except hourly
    ```
    
* For hourly
    
    ```bash
    /etc/cron.d/0hourly.
    ```
    

### Process management

* Background = Ctrl -z, jobs, and bg
    
* Foreground = fg
    
* Run process even after exit = nohup process &
    
    OR = nohup process &gt; /dev/null 2&gt;&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

```bash
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.
    

```bash
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.
    

| Aspect | 32-bit CPU | 64-bit CPU |
| --- | --- | --- |
| Number of Bits | 32 | 64 |
| Calculation Speed | Slower | Faster |
| Multi-core Support | Yes | Yes |
| Memory Limitations | Limited to 4 GB RAM | Can address more |
| Software Compatibility | Limited | Extensive |
| Performance Benefits | Limited | Enhanced |
| OS Support | Supported | Supported |
| Upgrade Considerations | Software Compatibility | Software Compatibility |

### To check the Architecture

* In Linux
    

```bash
arch
```

* In Windows
    

```bash
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:

```bash
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

```bash
clear = to clear your screen
```

```bash
exit = exit out of the shell, terminal or a user session
```

```bash
 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

```bash
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:

```bash
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:
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707918170425/9a4ee83d-2582-4407-8716-89272142b27a.png align="center")

* To view all environment variable
    
    ```bash
    printevn OR env
    ```
    
* To view ONE environment variable
    
    ```bash
    echo $SHELL OR
    echo $PATH
    ```
    
* To set the environment variable
    
    ```bash
    export TEST=1
    echo $TEST
    ```
    
* To set environment variables permanently
    
    ```bash
    vi .bashrc
    TEST='123'
    export TEST
    ```
    
* To set global environment variables permanently
    
    ```bash
    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
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1707919640422/23311491-b92b-40e9-acd7-5490ce727993.png align="center")

* 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
    

```bash
chmod u+s xyz.sh
```

* To assign special permissions at the group level
    

```bash
chmod g+s xyz.sh
```

* To assign special permission at the user or group level
    

```bash
chmod u-s xyz.sh
chmod g-s xyz.sh
```

* To find all executables in Linux with setuid and setgid permissions
    

```bash
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
    

```bash
-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 👋.
