Linux Unit - 3

 What is a Root User? 

Root is the super user account in Unix and Linux. It is a user account for administrative  purposes, and typically has the highest access rights on the system. 

Usually, the root user account is called root. However, in Unix and Linux, any account  with user id 0 is a root account, regardless of the name. It is fairly common for certain  system administrators to have their own root accounts on a system, with their own  passwords. 

Root Access 

Root access means performing something using root privileges. In Linux-based systems, this  means being able to do something using the user id 0, i.e., as root. 

Having root access generally means being able to log into some root account on the server, or  being able to run commands as root on the server, for example by using some privilege  escalation tool such as sudo. 

Root Privileges 

The root account has root privileges. This means it can read and write any files on the  system, perform operations as any user, change system configuration, install and remove  software, and upgrade the operating system and/or firmware. In essence, it can do pretty  much anything on the system. 

It is usually preferable to use dedicated service accounts for running applications and for  managing various operating system subsystems. Access to the root account should be  limited to the absolute minimum number of people and uses. 

Root Password 

When the device is powered on for the first time, it is ready to be configured. Initially, you  log in as the user root with no password. You must configure a plain-text password for the  root-level user (whose username is root) the first time you modify and commit the  configuration. Configuring a plain-text password is one way to protect access to the root  level by unauthorized users. If you forget the root password for the device, you can use the  password recovery procedure to reset the root password. 

Configure the Root Password

When you power on the router or switch, it is ready to be configured. Initially, you log in as  the user root with no password. The root directory is the entry point to all other folders and  files on that device. As a result, access to the root directory is restricted by default to a  predefined user account known as the root user. The root user (also referred to as superuser)  has unrestricted access and full permissions within the system. The expression “log in as  root” is commonly used when an action requires the user to log in to the device as the root  user. 

After you log in, you should configure the root (superuser) password by including the root authentication statement at the [edit system] hierarchy level and configuring one of the  password options: 

If you configure the plain-text-password option, you are prompted to enter and confirm the  password: 

The default requirements for plain-text passwords are: 

The password must be between 6 and 128 characters long. 

You can include most character classes in a password (uppercase letters, lowercase letters,  numbers, punctuation marks, and other special characters). Control characters are not  recommended. 

Valid passwords must contain at least one uppercase letter or one lowercase letter, or one  character class. 

sudo command in Linux with 

sudo (Super User DO) command in Linux is generally used as a prefix of some command  that only superuser are allowed to run. If you prefix “sudo” with any command, it will run  that command with elevated privileges or in other words allow a user with proper  permissions to execute a command as another user, such as the superuser. This is the  equivalent of “run as administrator” option in Windows. The option of sudo lets us have  multiple administrators. 

These users who can use the sudo command need to have an entry in the sudoers file  located at “/etc/sudoers”. Remember that to edit or view the sudoers file you have to use 

sudo command. To edit the sudoers file it is recommended to use “visudo” command. By default, sudo requires that users authenticate themselves with a password which is the  user’s password, not the root password itself. 

Syntax: 

sudo -V | -h | -l | -v | -k | -K | -s | [ -H ] [-P ] [-S ] [ -b ] | [ -p prompt ] [ -c class|- ] [ -a auth_type ] [-r role ] [-t type ] [ -u username|#uid ] commandsudo -V | -h | -l | -L | -v | -k | -K | -s | [ -H ] [-P ] [-S ] [ -b ] | [ -p prompt ] [ -c class|- ] [ -a auth_type ] [-r role ] [-t type ] 

[ -u username|#uid ] command 

-V: The -V (version) option causes sudo to print the version number and exit. If the  invoking user is already root, the -V option will print out a list of the defaults sudo was  compiled with. 

-l: The -l (list) option will print out the commands allowed (and forbidden) the user on the  current host. 

-h or –help: The -h (help) option causes sudo to print a usage message and exit. -v: If, given the -v (validate) option, sudo will update the user’s timestamp, prompting for  the user’s password if necessary. This extends the sudo timeout for another 5 minutes (or  as given in sudoers) but does not run a command. This does not give any output. -k: The -k (kill) option to sudo invalidates the user’s timestamp.So, the next time sudo is  run a password will be required. This option does not require a password and was added  to allow a user to revoke sudo permissions from a .logout file. 

-K: Similar to the -k option, the -K (sure kill) option is used to remove the user’s timestamp  entirely. Likewise, this option does not require a password. 

-b: The -b (background) option tells sudo to run the given command in the background.  Note that if you use the -b option you cannot use shell job control to manipulate the  process. 

-p:The -p (prompt) option allows you to override the default password prompt and use a  custom one. The following percent (‘%’) escapes are supported: 

%u is expanded to the invoking user’s login name;

%U is expanded to the login name of the user the command will be run as (which defaults  to root); 

%h is expanded to the local hostname without the domain name; 

%H is expanded to the local hostname including the domain name (only if the machine’s  hostname is fully qualified or the “fqdn” sudoers option is set); 

%% (two consecutive % characters) are collapsed into a single % character. -n: Use -n option as shown below, which will execute the command without prompting for  the password. This is very helpful when we want to run some of the sudo commands as  background jobs (or in a shell script), where we don’t want sudo to ask for the password. - n option stands for non-interactive. 

-u: The -u (user) option causes sudo to run the specified command as a user other than  root. To specify a uid instead of a username, use #uid. 

-s: The -s (shell) option runs the shell specified by the SHELL environment variable if it is  set or the shell as specified in the file passwd. 

-H: The -H (HOME) option sets the HOME environment variable to the home directory of  the target user (root by default) as specified in passwd. By default, sudo does not modify  HOME. 

-S: The -S (stdin) option causes sudo to read the password from standard input instead of  the terminal device. 

-a: The -a (authentication type) option causes sudo to use the specified authentication type  when validating the user, as allowed by /etc/login.conf. The system administrator may  specify a list of sudo-specific authentication methods by adding an “auth-sudo” entry in  /etc/login.conf. 

–: The — flag indicates that sudo should stop processing command line arguments. It is  most useful in conjunction with the -s flag. 

Run Levels in Linux 

A run level is a state of init and the whole system that defines what system services are  operating. Run levels are identified by numbers. Some system administrators use run levels 

to define which subsystems are working, e.g., whether X is running, whether the network  is operational, and so on. 

Whenever a LINUX system boots, firstly the init process is started which is actually  responsible for running other start scripts which mainly involves initialization of you  hardware, bringing up the network, starting the graphical interface. 

Now, the init first finds the default runlevel of the system so that it could run the start  scripts corresponding to the default run level. 

A runlevel can simply be thought of as the state your system enters like if a system is in a  single-user mode it will have a runlevel 1 while if the system is in a multi-user mode it will  have a runlevel 5

A runlevel in other words can be defined as a preset single digit integer for defining the  operating state of your LINUX or UNIX-based operating system. Each runlevel designates  a different system configuration and allows access to different combination of processes. The important thing to note here is that there are differences in the runlevels according to  the operating system. The standard LINUX kernel supports these seven different runlevels  : 

0 – System halt i.e the system can be safely powered off with no activity. 1 – Single user mode. 

2 – Multiple user mode with no NFS(network file system). 

3 – Multiple user mode under the command line interface and not under the graphical user  interface. 

4 – User-definable. 

5 – Multiple user mode under GUI (graphical user interface) and this is the standard  runlevel for most of the LINUX based systems. 

6 – Reboot which is used to restart the system. 

By default most of the LINUX based system boots to runlevel 3 or runlevel 5. In addition to the standard runlevels, users can modify the preset runlevels or even create  new ones according to the requirement. Runlevels 2 and 4 are used for user defined  

runlevels and runlevel 0 and 6 are used for halting and rebooting the system. Changing runlevel

init is the program responsible for altering the run level which can be called  using telinit command. 

For example, to change a runlevel from 3 to runlevel 5 which will actually allow the GUI to  be started in multi-user mode the telinit command can be used as : 

/*using telinit to change 

runlevel from 3 to 5*/ 

telinit 5 

The changing of runlevels is a task for the super user and not the normal user that’s why it  is necessary to be logged in as super user for the successful execution of the above telinit  command or you can use sudo command as : 

// using sudo to execute telinit 

sudo telinit 5 

The default runlevel for a system is specified in /etc/initab file which will have an entry id : 5 : initdefault if the default runlevel is set to 5 or will have an entry id : 3 : initdefault if the  default runlevel is set to 3. 

Need for changing the runlevel 

There can be a situation when you may find trouble in logging in in case you don’t  remember the password or because of the corrupted /etc/passwd file (have all the user  names and passwords), in this case the problem can be solved by booting into a single user  mode i.e runlevel 1. 

You can easily halt the system by changing the runlevel to 0 by using telinit 0. How To Check The Runlevel In Linux 

Check the Runlevel In Linux (SysV init) 

Here is the list of runlevels in Linux distributions,which were distributed with SysV init as  default service manager. 

0 - Halt 

1 - Single-user text mode 

2 - Not used (user-definable)

3 - Full multi-user text mode 

4 - Not used (user-definable) 

5 - Full multi-user graphical mode (with an X-based login screen) 

6 - Reboot 

Now, let us see how to find the runlevels. 

To find out the system runlevel, open your Terminal and run the following command: $ runlevel 

Sample output: 

N 3 

In the above output, the letter 'N' indicates that the runlevel has not been changed since the  system was booted. And, 3 is the current runlevel i.e the system is in CLI mode. In newer versions of init, you can find the current and previous runlevel details using the  environment variables called RUNLEVEL and PREVLEVEL

Say for example, to find out the current runlevel, you need to run: 

$ echo $RUNLEVEL 

To find the previous runlevel: 

$ echo $PREVLEVEL 

If you'd like to change the RunLevel to something else, edit /etc/inittab file: $ sudo vi /etc/inittab 

Find and edit entry initdefault to the runlevel of your choice. Say for example, to set the  runlevel to multi-user graphical mode (runlevel 5), modify it as shown below. id:5:initdefault: 

Save and close the file. Reboot your system to login to your new runlevel. For more details about runlevels, refer man pages. 

$ man runlevel 

2. Check the Runlevel In Linux (Systemd) 

In recent versions of Linux systems (starting from RHEL 7, Ubuntu 16.04 LTS), the concept  of runlevels has been replaced with systemd targets. 

Here is the list of Systemd targets in Linux distributions,which were distributed  with Systemd as default service manager.

runlevel0.target, poweroff.target - Halt 

runlevel1.target, rescue.target - Single-user text mode 

runlevel2.target, multi-user.target - Not used (user-definable) 

runlevel3.target, multi-user.target - Full multi-user text mode 

runlevel4.target, multi-user.target - Not used (user-definable) 

runlevel5.target,graphical.target - Full multi-user graphical mode (with an X-based login  screen) 

runlevel6.target,reboot.target - Reboot 

In Linux systems that are using Systemd as default service manager, you can find the  current target using command: 

$ systemctl get-default 

Sample output: 

graphical.target 

As you see in the above output, my current runlevel (target in other words) is 5, which is  graphical mode. 

To view all currently loaded targets, run: 

$ systemctl list-units --type target 

The above command will show only the active targets. 

To view all loaded targets (active and inactive), run: 

$ systemctl list-units --type target --all 

If you'd like to change the RunLevel to something else, for example runlevel3.target, set it  as shown below: 

$ sudo systemctl set-default runlevel3.target 

To change to a different target unit in the current session only, run the following command: $ sudo systemctl isolate runlevel3.target 

For more details, refer Systemd man pages. 

$ man systemd 

Check Linux Runlevel Using 'who' command 

As one of the reader suggested in the comment section below, we can also find the runlevel  using who command like below:

$ Who -r 

Sample output: 

 run-level 5 2021-06-09 10:21 

PERFORMANCE ANALYSIS TOOLS AND PROCESSES 

Linux treats each task performed on your system as a process, which is assigned a number  and a name. You can examine these processes and even stop them. Red Hat provides  several tools for examining processes as well as your system performance. Easy monitoring  is provided by several GUI tools, like Red Hat's Procman System Monitor. 

ps Command 

From the command line, you can use the ps command to list processes. With the - aux option, you can list all processes. Piping the output to a grep command with a pattern  enables you to search for a particular process. A pipe funnels the output of a preceding  command as input to a following command. The following command lists all X Window  System processes: 

ps -aux | grep 'X' 

A number of utilities on your system provide detailed information on your processes, as  well as other system information such as CPU and disk use . Although these tools were  designed to be used on a shell command line, displaying output in text lines, several now  have KDE and GNOME versions that provide a GUI interface for displaying results and  managing processes. 

Vmstat — virtual memory statistics 

Vmstat (virtual memory statistics) is a common tool to monitor the memory in Linux.  It can monitor the virtual memory, process and CPU of the operating system. General usage of vmstat:  vmstat interval times, that is, sampling every interval second, a total of sampling times. If times is  Omitted, data will be collected until the user stops manually. For example:

You can use Ctrl + C to stop vmstat collecting data. 

The first line shows the average value of the system since it was started. 

The second line shows what is happening now.The next line shows what happens every 5 seconds. The meaning of each column is in the header. 

The procs: R column shows how many processes are waiting for the CPU, and the B column shows how many processes are sleeping without interruption (waiting for IO). 

Memory: the swap D column shows how many blocks have been swapped out of the disk (page  swapping), the remaining columns show how many blocks are free (Unused),  

how many blocks are being used as buffers, and how many are being used as operating system  Caches. 

Swap: Show swap activity: how many blocks are being swapped in (from disk) and out  (to disk) per second. 

IO: shows how many blocks are read (BI) and written (Bo) from the block device, usually  reflecting the hard disk I / O. 

System: displays the number of interrupts (in) and context switches (CS) per second. CPU: displays the percentage of all CPU time spent on various operations, including  executing user code (non kernel), executing system code (kernel), idle and waiting for Io. Performance of insufficient memory: Free With the rapid decrease of memory, it is useless to  recycle buffers and cachers. A lot of swpd is used, page swap is frequent, the number of read 

and write disks (IO) is increased, the number of page missing interrupts (in) is increased,  the number of context switches (CS) is increased, the number of processes waiting for IO  (b) is increased, and a lot of CPU time is spent waiting for IO (WA) 

Iostat — used to report CPU statistics 

Iostat is used to report CPU statistics and input / output statistics of the whole system, adapter, 

10 

TTY device, disk and CD-ROM. by default, iostat displays the same CPU usage information as vmstat. Use the following command to display extended device statistics:: 

The first line shows the average value since the system started, and then shows the average value of  increment, one line for each device.Common Linux disk IO index abbreviation habits: RQ is request, 

R is read, W is write, Qu is queue, SZ is size, a is coverage, TM is time, SVC is service. Rrqm / s and wrqm / s: combined read and write requests per second. “Combined” means that the  operating system takes out multiple logical requests from the queue and merges them into one request  to the actual disk. R / s and w / s: the number of read and write requests sent to the device per second. RSEC / s and wsec / s: the number of sectors read and written per second.Avgrq – SZ: the number of  sectors requested. 

Avgqu – SZ: the number of requests waiting in the device queue. 

Await: time spent on each IO request. 

Svctm: actual request (service) time. 

%Util: the percentage of time spent with at least one active request. 

Dstat — system monitoring tool 

Dstat shows the CPU usage, disk IO, network contract and page change. The output is color and readable. Compared with vmstat and iostat, the input is more detailed and intuitive. In use, you can directly enter the command, of course, you can also use specific parameters. 

As follows: dstat – cdlmnpsy 

Iotop — Linux Process real time monitoring tool 

The iotop command is a special command to display the IO of the hard disk. The interface style is  similar to the top command. It can show which process is responsible for the IO load. Top is a top class tool for monitoring disk I / O usage. It has a UI similar to top, including PID, user, I / O, process and other information. 

Can be used in a non interactive way: 

iotop – bod Interval to view the I / O of each process. 

11 

You can use pidstat, pidstat – d instat 

Pidstat — monitoring system resources. Pidstat is mainly used to monitor the utilization of system  resources by all or specified processes, such as CPU,  

memory, device IO, task switching, threads, etc. 

usage method: 

pidstat –d interval 

#Count CPU usage information 

pidstat –u interval 

#Statistics memory information 

Pidstat –r interval 

top 

Top commandThe summary area of shows five aspects of system performance information Load: time, number of login users, average system load; 

Process: run, sleep, stop, zombie; 

CPU: user mode, kernel state, nice, idle, waiting for IO, interrupt, etc; 

Memory: total amount, used, idle (system angle), buffer, cache; 

Swap partition: total, used, idle 

The task area displays by default: process ID, valid user, process priority, nice value, virtual memory,  physical memory and shared memory used by the process, process status, CPU usage, memory usage, Cumulative CPU time, and process command line information. 

htop 

Htop is an interactive process viewer in Linux system, a text mode application (in the console or X termineeds ncurses. 

Htop allows users to operate interactively, supports color theme, scrolls horizontally or vertically to broprocess listand supports mouse operation.Compared with top, htop has the following advantages: You or vertically through the process list to see all the processes and the complete command line. On startupthan top. You don’t need to enter a process number to kill a process. 

Htop supports mouse operation 

mpstat

12 

Mpstat is the abbreviation of multiprocessor statistics, is a real-time system monitoring tool. It reports some statistical information about CPU, which is stored in / proc / STAT file. In the multi CPUs  system, it can not only view the average status information of all CPUs, but also view the information of specific CPUs. Common usage: 

mpstat –P ALL interval times 

netstat 

NetstatIt is used to display the statistical data related to IP, TCP, UDP and ICMP protocols. It is  used to check the network connection of each port of the machine. 

Common usage: 

netstat – npl # You can check whether the port you want to open is already open. netstat – rn # Print routing table information. 

netstat – in # Provide the interface information of the system, print the MTU of each  interface, the number of input packets, input errors, the number of output packets, output errors Conflicts and the length of the current output queue. 

strace 

Track the system calls and received signals generated in the process of program execution to help  Analyze the abnormal situation encountered in the process of program or command execution. For example: to see which configuration file mysqld loads on Linux, you can run the following command: 

strace –e stat64 mysqld –print –defaults > /dev/null 

uptime 

It can print the total running time of the system and the average load of the system,Uptime command The last three output figures mean the average load of the system in 1 minute, 5 minutes and 15 minuteslsof 

lsof (list open files)Is a list of the current system to open the file tool. adoptlsofThe tool can view this list to detect and debug the system 

#View file system blocking  

lsof /boot 

#Check which process is using the port number 

13 

lsof -i : 3306 

#View which files users open  

lsof –u username 

#View which files the process opens  

lsof –p 4838 

#View remote open network links  

lsof –i @192.168.34.128 

perf 

Perf is a system performance optimization tool of Linux kernel. The advantage lies in the close  Combination with Linux kernel. It can be first applied to the new feature added to kernel, which can be used to view hotspot functions and the ratio of cache miss, so as to help developers optimize program  Performance. 

Common performance testing tools 

Proficient and proficient in the second part of the performance analysis command tools, the  introduction of several performance testing tools 

perf_events 

A performance diagnostic tool released and maintained with Linux kernel code, maintained  and developed by the kernel community. Perf can be used not only for application  performance statistics, but also for kernel code performance statistics and analysis. 

eBPF tools 

A performance tracking tool using BCC, ebpf map can use custom ebpf program, which is  widely used in kernel tuning, and can also read user level asynchronous code. The important  thing is that this external data can be managed in user space. The K-V format map data body  is created, added and deleted by calling BPF system call in user space.

14 

Perf-tools: 

A software based on perf_ Event (perf) and ftrace. Perf tools has less dependent libraries and  is easy to use. Support Linux 3.2 and above kernel version. 

Bcc (BPF Compiler Collection) 

A perf performance analysis tool using ebpf. A toolkit for creating efficient kernel tracers and  manipulators, including several useful tools and examples. Using the extended BPF  (Berkeley packet filter), officially known as ebpf, a new feature was first added to Linux 3.15.  Multipurpose needs BCC above Linux 4.1. 

Ktap 

A new dynamic performance tracking tool for Linux scripts. Allows users to track Linux  kernel dynamics. Ktap is designed to be interoperable, allowing users to adjust operational  insights, troubleshoot and extend kernel and applications. It is similar to Linux and Solaris  DTrace systemtap. 

Flame Graphs 

Is a use of perf, system, tap, ktap visualization graphics software, allowing the most frequent  code path to quickly and accurately identify, can be the use of  github.com/brendangregg/flamegraph in the development of source code program  generation. 

Procman System Manager 

The current version of Red Hat provides the Procman System Manager for displaying system  information and managing system processes, accessible from System Tools | System  Monitor. There are two panels, one for processes and one for system information. The  System Monitor panel displays graphs for CPU, Memory, and Swap memory usage. Your  disk devices are also listed, showing the amount of disk space used and how much is free.  The Process Listing panel lists your processes, letting you sort or search for processes. You  can use field buttons to sort by name, process ID, user, memory, and even percentage of CPU  time used. The View pop-up menu lets you select all processes, just your own, or active  processes. You can easily stop any process by selecting it and then clicking the End Process 

15 

button. Right-clicking an item displays actions you can take on the process such as stopping  or hiding it. The Memory Maps display, selected from the View menu, shows information on  virtual memory, inodes, and flags. 

GNOME System Manager (GTop) 

With the GNOME System Manager (GTop), you can sort the processes according to their  fields by clicking the field's button at the top of the process list. If you right-click an entry, a  pop-up menu displays actions you can perform on that entry. System statistic summary  graphs are displayed at the top of the window, showing the CPU load, memory use, and  disk use. You can add more graphs or change their display features, such as the colors used.  The GTop window displays three tabbed panels for detailed reports showing processes,  memory use, and file system use. You can add more, showing customized reports such as  only the user processes. Process lists can be further refined to show user, system, or all 

16 

processes. To configure GTop, select the Settings | Preferences to display a menu with  tabbed panels for specifying the update frequency for different statistics, determining the  summaries you want displayed, and what process fields to show. You can find the GNOME  System Manager in the Utilities menu. 

KDE Process Manager (kpm) 

The K Desktop provides the KDE Process Manager (kpm) for viewing and managing your  processes. You can sort the processes according to their fields by clicking the field's button at  the top of the process list. If you select a process, you can then choose to perform several  different actions on it, such as ending it (killing the process) or suspending it (putting it to  sleep). Right-clicking a process entry displays a pop-up menu with the different actions you  can take. You can further refine your process list by choosing to view only your own  processes, system processes, or all processes. 

KDE Task Manager and Performance Monitor (KSysguard) Red Hat also provides the KDE Task Manager and Performance Monitor, KSysguard,  accessible from the Extras System Tools menu as KDE System Guard. This tool allows you to  monitor the performance of your own system as well as remote systems. KSysguard can  provide simple values or detailed tables for various parameters. A System Load panel  provides graphical information about CPU and memory usage, and a Process Table lists  current processes using a tree format to show dependencies. You can design your own  monitoring panels with worksheets, showing different types of values you want to display  and the form you want to display them in, like a bar graph or digital meter. The Sensor  Browser pane is an expandable tree of sensors for information like CPU System Load or  Memory's Used Memory. There is a top entry for each host you are connected to, including  your own localhost. To design your own monitor, create a worksheet and drag and drop a  sensor onto it. 

Introduction to Users and Groups 

While users can be either people (meaning accounts tied to physical users) or accounts that  exist for specific applications to use, groups are logical expressions of organization, tying 

17 

users together for a common purpose. Users within a group share the same permissions to  read, write, or execute files owned by that group. 

Each user is associated with a unique numerical identification number called a user ID (UID).  Likewise, each group is associated with a group ID (GID). A user who creates a file is also the  owner and group owner of that file. The file is assigned separate read, write, and execute  permissions for the owner, the group, and everyone else. The file owner can be changed only  by root, and access permissions can be changed by both the root user and file owner. 

Managing Users 

you can use command line tools for managing users and groups that are listed  in Table below, “Command line utilities for managing users and groups”. 

Utilities 

Description

Id 

Displays user and group IDs.

useradd, usermod, userdel 

Standard utilities for adding, modifying, and deleting user  accounts.

groupadd, groupmod, groupdel 

Standard utilities for adding, modifying, and deleting  groups.

Gpasswd 

Utility primarily used for modification of group password  in the /etc/gshadow file which is used by  the newgrp command.

pwck, grpck 

Utilities that can be used for verification of the password,  group, and associated shadow files.

pwconv, pwunconv 

Utilities that can be used for the conversion of passwords  to shadow passwords, or back from shadow passwords to  standard passwords.

grpconv, grpunconv 

Similar to the previous, these utilities can be used for  conversion of shadowed information for group accounts.



Adding a New User 

To add a new user to the system, type the following at a shell prompt as root: useradd options username

18 

…where options are command-line options as described in Table 4.2, “Common useradd  command-line options”. 

By default, the useradd command creates a locked user account. To unlock the account, run  the following command as root to assign a password: 

passwd username 

Following Table contain Common useradd command-line options 

Option 

Description

-c 'comment

comment can be replaced with any string. This option is generally used to  specify the full name of a user.

- 

d home_directory

Home directory to be used instead of default /home/username/.

-e date 

Date for the account to be disabled in the format YYYY-MM-DD.

-f days 

Number of days after the password expires until the account is disabled.  If 0 is specified, the account is disabled immediately after the password  expires. If -1 is specified, the account is not disabled after the password  expires.

-g group_name 

Group name or group number for the user’s default (primary) group. The  group must exist prior to being specified here.

-G group_list 

List of additional (supplementary, other than default) group names or  group numbers, separated by commas, of which the user is a member. The  groups must exist prior to being specified here.

-m 

Create the home directory if it does not exist.

-M 

Do not create the home directory.

-N 

Do not create a user private group for the user.

-p password 

The password encrypted with crypt.

-r 

Create a system account with a UID less than 1000 and without a home  directory.

-s 

User’s login shell, which defaults to /bin/bash.

-u uid 

User ID for the user, which must be unique and greater than 999.



Adding a New Group 

To add a new group to the system, type the following at a shell prompt as root:

19 

groupadd options group_name 

Common groupadd command-line options 

Option 

Description

-f, --force 

When used with -g gid and gid already exists, groupadd will choose  another unique gid for the group.

-g gid 

Group ID for the group, which must be unique and greater than 999.

-K, --key key=value 

Override /etc/login.defs defaults.

-o, --non-unique 

Allows creating groups with duplicate GID.

-p, -- 

password password

Use this encrypted password for the new group.

-r 

Create a system group with a GID less than 1000.



Adding an Existing User to an Existing Group 

Use the usermod utility to add an already existing user to an already existing group. 

Various options of usermod have different impact on user’s primary group and on his or her  supplementary groups. 

To override user’s primary group, run the following command as root

~]# usermod -g group_name user_name 

To override user’s supplementary groups, run the following command as root: ~]# usermod -G group_name1,group_name2,... user_name 

Note that in this case all previous supplementary groups of the user are replaced by the new  group or several new groups. 

To add one or more groups to user’s supplementary groups, run one of the following  commands as root

~]# usermod -aG group_name1,group_name2,... user_name 

~]# usermod --append -G group_name1,group_name2,... user_name

20 

Creating Group Directories 

System administrators usually like to create a group for each major project and assign people  to the group when they need to access that project’s files. With this traditional scheme, file  management is difficult; when someone creates a file, it is associated with the primary group  to which they belong. When a single person works on multiple projects, it becomes difficult  to associate the right files with the right group. However, with the UPG scheme, groups are  automatically assigned to files created within a directory with the setgid bit set. The setgid bit  makes managing group projects that share a common directory very simple because any files  a user creates within the directory are owned by the group that owns the directory. 

For example, a group of people need to work on files in the /opt/myproject/ directory.  Some people are trusted to modify the contents of this directory, but not everyone. 

1. As root, create the /opt/myproject/ directory by typing the following at a shell  prompt: 

mkdir /opt/myproject 

2. Add the myproject group to the system: 

groupadd myproject 

3. Associate the contents of the /opt/myproject/ directory with the myproject group: chown root:myproject /opt/myproject 

4. Allow users in the group to create files within the directory and set the setgid bit: chemod 2775 /opt/myproject 

At this point, all members of the myproject group can create and edit files in  the /opt/myproject/ directory without the administrator having to change file  permissions every time users write new files. To verify that the permissions have been  set correctly, run the following command: 

~]# ls -ld /opt/myproject 

drwxrwsr-x. 3 root myproject 4096 Mar 3 18:31 /opt/myproject 

5. Add users to the myproject group: 

user mod -aG myproject username

21 

Merging groups- group management tools  

  

 One of the many benefits of having password database files that have a well-defined  format in straight text is that it is easy for anyone to write custom management tools. Indeed,  many site administrators have already done this to integrate their tools along with the rest of  their organization’s infrastructure. They can, for example, start the process of creating a new  user from the same form that lets them update the corporate phone and e-mail directory,  LDAP servers, web pages, and so on. Of course, not everyone wants to write custom tools,  which is why Linux comes with several existing tools that do the job for you. In this section,  we discuss user management tools that can be launched from the command-line interface, as  well as graphical user interface (GUI) tools. Of course, learning how to use both is the  preferred route, since they both have advantages 

Command-Line User Management 

You can choose from among several command-line tools to perform the same actions  performed by the GUI tools. Some of the most popular command-line tools are useradd,  userdel, usermod, groupadd, groupdel, and groupmod. The compelling advantage of using  command-line tools for user management, besides speed, is the fact that the tools can usually  be incorporated into other automated functions 

useradd 

As the name implies, useradd allows you to add a single user to the system. Unlike the GUI  tools, this tool has no interactive prompts. Instead, all parameters must be specified on the  command line 

Here’s the syntax for using this too 

Usage: useradd [options] LOGIN Options:  

-b, --base-dir BASE_DIR  

-c, --comment COMMENT  

-d, --home-dir HOME_DIR 

-D, --defaults 

-e, --expiredate EXPIRE_DATE 

-f, --inactive INACTIVE  

-g, --gid GROUP  

-G, --groups GROUPS 

-k, --skel SKEL_DIR 

-K, --key KEY=VALUE 

-l, --no-log-init 

-m, --create-home  

-M, --no-create-home  

-N, --no-user-group  

-o, --non-unique  

-p, --password PASSWORD 

-r, --system 

-s, --shell SHELL

22 

-u, --uid UID  

-U, --user-group 

Take note that most of the options are optional. The useradd tool assumes preconfigured  defaults in its usage. The only non-optional parameter is the LOGIN parameter or the  desired username. Also, don’t be intimidated by this long list of options! They are all quite  easy to use and some of them are described in Table 5-1 

Option Description -c, --comment 🡪 Allows you to set the user’s  name in the GECOS field. As with any command-line parameter, if the value includes a  space, you will need to add quotes around the text. For example, to set the user’s name to  Ying Yang, you would have to specify -c "Ying Yang". 

-d, --home-dir 🡪 By default, the user’s home  directory is /home/user_name. When a new user is created, the user’s home directory is  created along with the user account, so if you want to change the default to another place,  you can specify the new location with this parameter 

-e, --expiredate 🡪 It is possible for an account to  expire after a certain date. By default, accounts never expire. To specify a date, use the  YYYY-MM-DD format. For example, -e 2019-10-28 means the account will expire on October  28, 2019 

-f, --inactive 🡪 This option specifies the  number of days after a password expires that the account is still usable. A value of 0 (zero)  indicates that the account is disabled immediately. A value of -1 will never allow the account  to be disabled, even if the password has expired. (For example, -f 3 will allow an account to  exist for three days after a password has expired.) The default value is -1  

-g, --gid 🡪 Using this option, you can  specify the user’s default group in the password file. You can use a number or name of the  group; however, if you use a name of a group, the group must exist in the /etc/group file. 

-G, --groups 🡪 This option allows you to  specify additional groups to which the new user will belong. If you use the -G option, you  must specify at least one additional group. You can, however, specify additional groups by  separating the elements in the list with commas. For example, to add a user to the project  and admin groups, you would specify -G project,admin 

-m, --create -home [-k skel-dir ] 🡪 By default, the system  automatically creates the user’s home directory. This option is the explicit command to create  the user’s home directory. Part of creating the directory is copying default configuration files  into it. These files come from the /etc/skel directory by default. You can change this by 

23 

using the secondary option -k skel-dir. (You must specify -m in order to use -k.) For example,  to specify the /etc/adminskel directory, you would use -m -k /etc/adminskel 

-M 🡪 If you used the -m option, you  cannot use -M, and vice versa. This option tells the command not to create the user’s home  directory 

-N 🡪 Some Linux distros automatically  create a new group with the same name as the new user’s login as part of the process of  adding a user. You can disable this behavior by using this option on such distros 

-s, shell 🡪 A user’s login shell is the first  program that runs when a user logs into a system. This is usually a command line  environment, unless you are logging in from the X Window System login screen. By default,  this is the Bourne Again Shell (/bin/bash), though some folks like to use other shells, such as  the Turbo C Shell (/bin/tcsh). 

-u, --uid 🡪 By default, the program will  automatically find the next available UID and use it. If, for some reason, you need to force a  new user’s UID to be a particular value, you can use this option. Remember that UIDs must  be unique for all users  

LOGIN or username 🡪 finally, the only parameter that isn’t  optional! You must specify the new user’s login name 

usermod 

 The usermod command allows you to modify an existing user in the system. It works in  much the same way as useradd. Its usage is summarized here

Usage: usermod [options] LOGIN 

Options:  

-c, --comment COMMENT new value of the GECOS field 

-d, --home HOME_DIR new home directory for the user account  

-e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE -f, --inactive INACTIVE set password inactive after expiration  

-g, --gid GROUP force use GROUP as new primary group  

-G, --groups GROUPS new list of supplementary GROUPS 

-a, --append append the user to supplemental GROUPS 

-l, --login NEW_LOGIN new value of the login name  

-L, --lock lock the user account 

-m, --move-home move contents of the home directory 

-o, --non-unique allow using duplicate (non-unique) UID 

-p, --password PASSWORD use encrypted password for the new password -s, --shell SHELL new login shell for the user account 

-u, --uid UID new UID for the user account 

24 

-U, --unlock unlock the user account 

Every option you specify when using this command results in that particular parameter  being modified for the user. All but one of the parameters listed here are identical to the  parameters documented for the useradd command. The one exception is -l. The -l option  allows you to change the user’s login name. This and the -u option are the only options that  require special care. Before changing the user’s login or UID, you must make sure the user is  not logged into the system or running any processes. Changing this information if the user is  logged in or running processes will cause unpredictable results 

userdel 

 The userdel command does the exact opposite of useradd—it removes existing users. This  straightforward command has only two commonly used optional parameters and one  required parameter: 

Usage: userdel [options] LOGIN 

Options:  

-f, --force force removal of files, even if not owned by user  

-r, --remove remove home directory and mail spool  

groupadd 

The group-related commands are similar to the user commands; however, instead of  working on individual users, they work on groups listed in the /etc/group file. Note that  changing group information does not cause user information to be automatically changed.  For example, if you remove a group whose GID is 100 and a user’s default group is specified  as 100, the user’s default group would not be updated to reflect the fact that the group no  longer exists. The groupadd command adds groups to the /etc/group file. The command line options for this program are as follows: 

Usage: groupadd [options] GROUP 

groupdel 

Even more straightforward than userdel, the groupdel command removes existing groups  specified in the /etc/group file. The only usage information needed for this command is Usage: groupdel group 

where group is the name of the group to remove

groupmod 

The groupmod command allows you to modify the parameters of an existing group. The  syntax and options for this command are shown here 

Usage: groupmod [options] GROUP 

Options: 

-g, --gid GID change the group ID to GID  

-n, --new-name NEW_GROUP change the name to NEW_GROUP 

-o, --non-unique allow to use a duplicate (non-unique) GID  

-p, --password PASSWORD change the password to this (encrypted) PASSWORD 

The -g option allows you to change the GID of the group, and the -n option allows you to specify a new name  of a group. In addition, of course, you need to specify the name of the existing group as the last parameter

25 

 Option Description 

-g gid 🡪 Specifies the GID for the new group as  gid. This value must be unique, unless the -o option is used. By default, this value is  automatically chosen by finding the first available value greater than or equal to 1000 

-r, --system 🡪 By default, Fedora, RHEL, and  CentOS distros search for the first GID that is higher than 999. The -r option tells groupadd  that the group being added is a system group and should have the first available GID under  999. 

-f, --force 🡪 This is the force flag. This will  cause groupadd to exit without an error when the group about to be added already exists on  the system. If that is the case, the group won’t be altered (or added again). It is a Fedora- and  RHEL-specific option 

GROUP 🡪 This option is required. It  specifies the name of the group you want to add to be group. 

File Permissions 

All the three owners (user owner, group, others) in the Linux system have three types of  permissions defined. Nine characters denotes the three types of permissions. 

1) Read (r) : The read permission allows you to open and read the content of a file. But  you can't do any editing or modification in the file. 

2) Write (w) : The write permission allows you to edit, remove or rename a file. For  instance, if a file is present in a directory, and write permission is set on the file but  not on the directory, then you can edit the content of the file but can't remove, or  rename it. 

3) Execute (x): In Unix type system, you can't run or execute a program unless execute  permission is set.But in Windows, there is no such permission available. 

Permissions are listed below: 

permission on a file on a directory 


r (read) 

read file content (cat) 

w (write) 

change file content (vi) 

x (execute) 

execute the file 



read directory content (ls) create file in directory (touch) enter the directory (cd)

26 

Permission set 

Look at the above snapshot, there are ten characters (-rw-rw-r--) before the user owner. We'll  describe these ten characters here. 

File permissions for (-rw-rw-r--) 

position characters ownership 


2-4 

rw- 

5-7 

rw- 

8-10 

r-- 



denotes file type permission for user permission for group permission for other 

When you are the User owner, then the user owner permission applies to you. Other  permissions are not relevant to you. 

When you are the Group then the group permission applies to you. Other permissions are  not relevant to you. 

When you are the Other, then the other permission applies to you. User and group  permissions are not relevant to you. 

Permission Example 

Now we'll show some examples how permissions can be seen for a file or directory. Look at the above snapshot, different directories and files have different permissions.

27 

First letter (-) or d represents the files and directories respectively. 

Now, from remaining nine letters, first triplet represents the permission for user  owner. Second triplet represents the permission for group owner. Third triplet represents  the permission for other . 

Managing password-policy& shadow password 

At one time, encrypted passwords were stored in the world-readable /etc/passwd file. This  was thought to be reasonably secure until dictionary attacks on encrypted passwords became  common. At that point, the encrypted passwords were moved to a separate /etc/shadow file  which is readable only by root. This new file also allowed password aging and expiration  features to be implemented….Like /etc/passwd, each user has a line in the /etc/shadow file.  A sample line from /etc/ shadow with its nine colon-separated fields is shown below. 

Username of the account this password belongs to. 

The encrypted password of the user. The format of encrypted passwords is discussed later in  this section. 

The day on which the password was last changed. This is set in days since 1970-01-01 and is  calculated in the UTC time zone. 

The minimum number of days that have to elapse since the last password change before the  user can change it again. 

The maximum number of days that can pass without a password change before the  password expires. An empty field means it does not expire based on time since the last  change. 

Warning period. The user will be warned about an expiring password when they login for  this number of days before the deadline. 

Inactivity period. Once the password has expired, it will still be accepted for login for this  many days. After this period has elapsed, the account will be locked. 

The day on which the password expires. This is set in days since 1970-01-01 and is calculated  in the UTC time zone. An empty field means it does not expire on a particular date. The last field is usually empty and is reserved for future use. 

Format of an Encrypted password 

The encrypted password field stores three pieces of information: the hashing algorithm used,  the salt, and the encrypted hash. Each piece of information is delimited by the $ sign. 

The hashing algorithm used for this password. The number 6 indicates it is a SHA-512 hash,  which is the default in Red Hat Enterprise Linux 8. A 1 would indicate MD5, a 5 SHA-256. The salt used to encrypt the password. This is originally chosen at random. The encrypted hash of the user’s password. The salt and the unencrypted password are  combined and encrypted to generate the encrypted hash of the password. The use of salt prevents two users with the same password from having identical entries in  the / etc/shadow file. For example, even if user01 and user02 both use mypass as their  passwords, their encrypted passwords in /etc/shadow will be different if their salts are  different.

28 

Password verification  

When a user tries to log in, the system looks up the entry for the user in /etc/shadow,  combines the salt for the user with the unencrypted password that was typed in, and  encrypts them using the hashing algorithm specified. If the result matches the encrypted  hash, the user typed in the right password. If the result does not match the encrypted hash,  the user typed in the wrong password and the login attempt fails. This method allows the  system to determine if the user typed in the correct password without storing that password  in a form usable for logging in. 

Configuring password aging  

The following diagram relates the relevant password aging parameters, which can be  adjusted using the chage command to implement a password aging policy. 

[user01@host ~]$ sudo chage -m 0 -M 90 -W 7 -I 14 user03 

- The preceding chage command uses the -m, -M, -W, and -I options to set the minimum age,  maximum age, warning period, and inactivity period of the user’s password, respectively. - The ‘chage -d 0 user03’ command forces the user03 user to update its password on the next  login. - The ‘chage -l user03’ command displays the password aging details of user03. - The  chage -E 2019-08-05 user03’ command causes the user03 user’s account to expire on 2019-08- 05 (in YYYY-MM-DD format). 

[user01@host ~]$ date -d "+45 days" -u 

Thu May 23 17:01:20 UTC 2019

29 

Edit the password aging configuration items in the /etc/login.defs file to set the default  password aging policies. The PASS_MAX_DAYS sets the default maximum age of the  password. The PASS_MIN_DAYS sets the default minimum age of the password. The  PASS_WARN_AGE sets the default warning period of the password. Any change in the  default password aging policies will be effective for new users only. The existing users will  continue to use the old password aging settings rather than the new ones. 

Restricting Access 

You can use the chage command to set account expiration dates. When that date is reached,  the user cannot log in to the system interactively. The usermod command can lock an  account with the -L option. 

[user01@host ~]$ sudo usermod -L user03 

[user01@host ~]$ su - user03 

Password: mypass 

su: Authentication failure 

usermod If a user leaves the company, the administrator may lock and expire an account  with a single command. The date must be given as the number of days since 1970-01-01, or in  the YYYY-MM-DD format. 

[user01@host ~]$ sudo usermod -L -e 2019-10-05 user03 

The preceding usermod command uses the -e option to set the account expiry date for the  given user account. The -L option locks the user’s password. Locking the account prevents  the user from authenticating with a password to the system. It is the recommended method  of preventing access to an account by an employee who has left the company. If the  employee returns, the account can later be unlocked with usermod -U. If the account was  also expired, be sure to also change the expiration date. 

Managing Disk Quotas 

CentOS disk quotas can be enabled both; alerting the system administrator and denying  further disk-storage-access to a user before disk capacity is exceeded. When a disk is full,  depending on what resides on the disk, an entire system can come to a screeching halt until  recovered. 

Enabling Quota Management in CentOS Linux is basically a 4 step process − Step 1 − Enable quota management for groups and users in /etc/fstab. Step 2 − Remount the filesystem. 

Step 3 − Create Quota database and generate disk usage table. 

Step 4 − Assign quota policies.

30 

Enable Quota Management in /etc/fstab 

First, we want to backup our /etc/fstab filen − 

[root@centosLocal centos]# cp -r /etc/fstab ./ 

We now have a copy of our known working /etc/fstab in the current working directory. # 

# /etc/fstab 

# Created by anaconda on Sat Dec 17 02:44:51 2016 

# Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # 

/dev/mapper/cl-root / xfs defaults 0 0 

UUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0 

/dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0 

/dev/mapper/cl-swap swap swap defaults 0 0 

We made the following changes in the options section of /etc/fstab for the volume or Label to  where quotas are to be applied for users and groups. 

usrquota 

grpquota 

As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps  involved. /home is on the same disk as /. Further investigation shows / is set for noquota,  which is a kernel level mounting option. We must re-configure our kernel boot options. root@localhost rdc]# mount | grep ' / ' 

/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota) 

[root@localhost rdc]# 

Reconfiguring Kernel Boot Options for XFS File Systems 

This step is only necessary under two conditions − 

When the disk/partition we are enabling quotas on, is using the xfs file system When the kernel is passing noquota parameter to /etc/fstab at boot time Step 1 − Make a backup of /etc/default/grub. 

cp /etc/default/grub ~/ 

Step 2 − Modify /etc/default/grub

Here is the default file. 

GRUB_TIMEOUT=5 

GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)" 

GRUB_DEFAULT=saved 

GRUB_DISABLE_SUBMENU=true 

GRUB_TERMINAL_OUTPUT="console" 

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb  quiet" 

GRUB_DISABLE_RECOVERY="true" 

We want to modify the following line −

31 

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb  quiet" 

to 

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv =cl/swap rhgb quiet rootflags=usrquota,grpquota" 

Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our  system will fail to boot if any errors were made in the configuration. Please, try this part of  the tutorial on a non-production system. 

Step 3 − Backup your working grub.cfg 

cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak 

Make a new grub.cfg 

[root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg 

Generating grub configuration file ... 

Found linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64 

Found initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img 

Found linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd Found initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img done 

[root@localhost rdc]# 

Reboot 

[root@localhost rdc]#reboot 

If all modifications were precise, we should not have the availability to add quotas to  the xfs file system. 

[rdc@localhost ~]$ mount | grep ' / ' 

/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota) 

[rdc@localhost ~]$ 

We have passed the usrquota and grpquota parameters via grub. 

Now, again edit /etc/fstab to include / since /homeon the same physical disk. /dev/mapper/cl-root/xfs 

defaults,usrquota,grpquota 0 0 

Now let's enable the quota databases. 

[root@localhost rdc]# quotacheck -acfvugM 

Make sure Quotas are enabled. 

[root@localhost rdc]# quotaon -ap 

group quota on / (/dev/mapper/cl-root) is on 

user quota on / (/dev/mapper/cl-root) is on 

group quota on /home (/dev/mapper/cl-home) is on 

user quota on /home (/dev/mapper/cl-home) is on 

[root@localhost rdc]# 

Remount the File System 

If the partition or disk is separate from the actively booted partition, we can remount without  rebooting. If the quota was configured on a disk/partition booted in the root directory /, we 

32 

may need to reboot the operating system. Forcing the remount and applying changes, the  need to remount the filesystem may vary. 

[rdc@localhost ~]$ df 

Filesystem 1K-blocks Used Available Use% Mounted on 

/dev/mapper/cl-root 22447404 4081860 18365544 19% / 

devtmpfs 903448 0 903448 0% /dev 

tmpfs 919308 100 919208 1% /dev/shm 

tmpfs 919308 9180 910128 1% /run 

tmpfs 919308 0 919308 0% /sys/fs/cgroup 

/dev/sda2 1268736 176612 1092124 14% /boot 

/dev/mapper/cl-var 4872192 158024 4714168 4% /var 

/dev/mapper/cl-home 18475008 37284 18437724 1% /home 

tmpfs 183864 8 183856 1% /run/user/1000 

[rdc@localhost ~]$ 

As we can see, LVM volumes are in use. So it's simple to just reboot. This will  remount /home and load the /etc/fstab configuration changes into active configuration. Create Quota Database Files 

CentOS is now capable of working with disk quotas on /home. To enable full quota supprt,  we must run the quotacheck command. 

quotacheck will create two files − 

aquota.user 

aquota.group 

These are used to store quota information for the quota enabled disks/partitions. Following are the common quotacheck switches. 


Switch 

-u 

-g 

-c 

-v 



Action 

Checks for user quotas 

Checks for group quotas 

Quotas should be enabled for each file system with enables quotas Displays verbose output 

Add Quota Limits Per User 

For this, we will use the edquota command, followed by the username − [root@localhost rdc]# edquota centos 

Disk quotas for user centos (uid 1000): 

Filesystem blocks soft hard inodes soft hard 

/dev/mapper/cl-root 12 0 0 13 0 0 

/dev/mapper/cl-home 4084 0 0 140 0 0 

Let's look at each column. 

Filesystem − It is the filesystem quotas for the user applied to blocks − How many blocks the user is currently using on each filesystem

33 

soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time  period 

hard − Set blocks for a hard limit. Hard limit is total allowable quota 

inodes − How many inodes the user is currently using 

soft − Soft inode limit 

hard − Hard inode limit 

To check our current quota as a user − 

[centos@localhost ~]$ quota 

Disk quotas for user centos (uid 1000): 

Filesystem blocks quota limit grace files quota limit grace 

/dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$ Following is an error given to a user when the hard quota limit has exceeded. [centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/ 

cp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE 

1611.iso.part’: Disk quota exceeded 

[centos@localhost Downloads]$ 

As we can see, we are closely within this user's disk quota. Let's set a soft limit warning. This  way, the user will have advance notice before quota limits expire. From experience, you will  get end-user complaints when they come into work and need to spend 45 minutes clearing  files to actually get to work. 

As an Administrator, we can check quota usage with the repquota command. [root@localhost Downloads]# repquota /home 

Block limits File limits 

User used soft hard grace used soft hard grace 

---------------------------------------------------------------------------------------- 

root -- 0 0 0 3 0 0 

centos -+ 6189824 56123456 61234568 541 520 540 6days 

[root@localhost Downloads]# 

As we can see, the user centos has exceeded their hard block quota and can no longer use  any more disk space on /home

-+denotes a hard quota has been exceeded on the filesystem. 

When planning quotas, it is necessary to do a little math. What an Administrator needs to  know is:How many users are on the system? How much free space to allocate amongst  users/groups? How many bytes make up a block on the file system? 

Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a  "safe" buffer of free-space on the file system that will remain in worst case scenario: all  quotas are simultaneously exceeded. This is especially on a partition that is used by the  system for writing logs. 

Configuration and managing print services

34 

Linux, different commands are used to print a file or output. Printing from a Linux terminal  is a straightforward process. The lp and lpr commands are used to print from the terminal.  And, the lpg command is used to display queued print jobs

Printing the double-sided document or in portrait mode is a bit complicated process. And  there may be many other operations that we want to perform, such as printing multiple copies or  canceling a print job, which can be difficult to perform. 

Linux lp and lpr command 

CUPS (Common Unix Printing System) provides the system commands for printing files.  Additionally, it supports several standard options to control the print operation. Let's see  how to print files. 

How to print files in Linux 

To print files from Linux 

terminal, execute the lp and lpr command. It will print the file from the default printer.  Execute it as follows: 

1) lp < file name>  

2) lpr <file name>  

Choosing a Printer 

If our system has connected with more than one printer, you can choose one of them to print  the particular file. These printers can be connected with different methods such as parallel,  serial, USB 

port, networking. 

To display a list of the connected printers, execute the command as follows: 

lpstat -p -d  

The above command will display a list of available printers. The '-p' option is used to display  a list of the printers, and the '=d' option specifies the default printer. 

To print a file with a specific printer, execute the lp command with the '-d' option or lpr  command with the '-P' option. Consider the following commands: 

lp -d <printer name> <file name>  

lpr -P <printer name> <file name>  

In the above commands, both commands will perform the same operation. For example, to print a file 'Notes.pdf' by the printer name 'HPM375', execute the command  as follows:

35 

lpr -P HPM375 Notes.pdf  

Setting the Default Printer 

We can set a particular printer as a default printer from the connected printers. To set a  printer as the default printer, execute the lpoptions command with the '-d' option as follows: 

1) lpoptions -d < printer name> 

Printing Multiple Copies 

The lp and lpr both commands support to print multiple copies of a file. To specify the  number of copies, use the '-n' option with lp command as follows: 

lp -n number <file name>  

Use the '-#' option with lpr command for the same task as follows: 

lpr -#number <filename>  

Generally, the printed copies are not collated. To collate the copies, use the "-o collate=true"  option. Consider the following commands: 

lp -n number -o collate=true <filename>  

lpr -#number -o collate=true <filename> 

Canceling a Print Task 

We can cancel a print task by using the cancel and lprm commands. To cancel a queued job,  execute the commands as follows: 

cancel job-id 

36 

 lprm job-id  

The Job-id can be seen by executing the following commands: 

lpq 

lpstat 

Moving a Print Task 

We can forward a queued job to a different printer by using the lpmove command. To move  a print task to a new printer or class, execute the command as follows: 

lpmove job-id destination  

The job-id is the process id of the task that can be seen by lp or lpstat commands.  The destination is the printer, to which we want to forward the print task. The most common error that can be seen during the move operation is "command not  found" error. Since, the lpmove command is located in the system command directory, and  may not be in our current path. To overcome this problem, specify the full to the path. 

Selecting the Media Size, Type and Source 

To set the media size, type, and source, use the "-o media=xyz" option. Some common media  customization examples are as follows: 

lp -o media=Letter <filename>  

lp -o media=Letter,MultiPurpose <filename>  

lpr -o media=Letter,Transparency <filename>  

lpr -o media=Letter,MultiPurpose,Transparency <filename>  

The media options are completely dependent on the type of printer. But some standard  printers support the following options: 

1)Letter: It is used for the US Letter (8.5x11 inches, or 216x279mm). 

2)Legal: It is used for the US Legal (8.5x14 inches, or 216x356mm). 

3)A4: It is used for ISO A4 (8.27x11.69 inches, or 210x297mm). 

4)COM10: It is used for US #10 Envelope (9.5x4.125 inches, or 241x105mm). 5)DL: It is used for ISO DL Envelope (8.66x4.33 inches, or 220x110mm). 6)Transparency: It is used for transparency media type or source. 

7)Upper: It is used to specify the upper paper tray. 

8)Lower: It is used to specify the lower paper tray. 

9)MultiPurpose: It is used to specify a multi-purpose paper tray. 

10)LargeCapacity: It is used to specify a large capacity paper tray.

37 

The printer's PPD file has a description of all supported options. To list them, execute the  following command: 

lpoptions -p printer -l  

We can customize the page size by using the 'Custom' option. We can specify options in the  following forms: 

lp -o media=Custom.width*length <filename>  

We can specify the width and length in the "in, cm, and mm" unit. 

Printing on Both Sides of the Paper 

To enable two-sided printing, use the "-o sides option" as follows: 

lp -o sides=two-sided-short-edge <filename>  

lp -o sides=two-sided-long-edge <filename>  

The above commands will enable two-sided printing if supported by the printer. The "-short edge" is used for landscape mode, and the "-long-edge" is used for portrait mode. 

Local Printer Configuration  

A Printer is an essential part of a computer that allows us to print the intangible data onto a  paper sheet. Generally, people go to cyber cafes for print out works. It is because they do not  have a computer in their homes or are not computer users and are not knowledgeable about  the technical world. If you have to Google such a question, it probably means that you are a  technical person or computer user, owns a printer or has purchased one and wants to learn  how to connect your printer to the computer. If you have a printer

38 

1)Laser Printers: The printers are used to quickly print hundreds of pages (in just a few  minutes). 

Such printers are used for printing legal or professional documents. We can find such  printers at cyber cafes or government sectors. 

2)Inkjet Printers: These printers are used by a common group of people. Such a printer is  capable of printing documents for schools, project pages, photos, online forms, online  purchasing receipts, etc.

People choose Inkje? printers as their personal assistant. 

3)3D Printers: It is a new variety of printer that is used for printing 3D parts or tools, and  replaced parts for broken objects. It is used for taking digital blueprints of the objects.

39 

Such printers are used for architectural purposes, designing purposes, and many more. 3D  printers are also used for printing toys for kids. 

Network Printer Configuration  

It is only natural to share computer resources. People are increasingly preferring to share a  printer across two or more computers at home rather than at work, especially as more  families acquire several computers. c 

Those who use numerous PCs at home or at a business may want to share a printer in terms  of convenience or cost savings. This article discusses how to make a printer accessible to  numerous computers with the help of using a variety of approaches. Before sharing a printer  over the network, decide on the configuration you want to utilize. 

The various arrangements, as well as their benefits and drawbacks, are listed below.

40 

Wireless printer 

In modern times, most printers (especially midrange and high-end ones) can have the  potential to connect directly to a user's network. Because they are the easiest to set up and  detect, these printers have a major edge in terms of convenience of use. Wireless printers are  practically plug-and-play with Windows Vista, since they are identified by a computer's  word processor or Internet browser. The sole disadvantage of this setup is that it necessitates  the creation of a wireless network. 

Skip Ad 

You can install and connect the printer to all of your computer systems once it has been  setup and linked to your wireless network. 

Dedicated print server 

A print server is a hardware device, which is another option to connect a printer to multiple  computers. A print server can be used to connect a tiny device to your network that  delegates and queues print tasks for numerous workstations. Print servers allow you to print  even if the computer connected to your printer is turned off (network printer configuration),  but they are more expensive and take longer to set up.

41 

Printer connected to a computer or server 

Connecting a printer to a host computer is the most common way to share it. Because of its  simplicity and inexpensive cost, this approach is often used. The printer is effectively  "shared" by the host computer, allowing other computers on the network to print through a  LAN (local area network) or an Internet connection. But, in order for other machines to use  the printer, this method requires the host computer to be turned on at all times that is the  main downside of this method. Furthermore, on the host computer, you must have a  network and a printer installed in order to print through another networked computer. 

Step 1 

Use a switch to turn things on and off. A printer switch, which works with both parallel and  USB printers, you can purchase this printer switch. Connect the switch to both computers  and the printer, then set up the printer on each computer as usual. Some older parallel  printer switches need you, which is used to manually flip a switch to assign one computer to  the printer at a time; however, the latest and slightly more expensive switches have the  potential to do it automatically. For this approach to work, your PCs must be close together. 

Step 2 

If you are using Microsoft Windows, you can share your printer. On both computers, go to  Control Panel, then "System," and make sure that file and printer sharing is enabled, as well  as that systems have the same workgroup name. Now, select "Printers and Faxes" from the 

42 

Control Panel on the computer to which the printer is already attached. Select "Properties"  from the drop-down menu when right-clicking on the printer. Choose the "Sharing" option,  then "Share this Printer" and a name for it. Select "Add a Printer" from the "Printers and  Faxes" menu on the other computer. 

The alternatives are "Network Printer" or "Printer linked to another computer." The name of  the printer you shared on the first computer should display when you select Browse for a  Printer. Follow the wizard's instructions to install the printer software on the second  computer, and have the printer's driver CD handy. 

Step 3 

Invest in a network printer. A network connection is now available on many low-cost  printers. All you will need is a router in close proximity to the printer, or a connection to a  router in close proximity to the printer. Set up and switch on the printer. Connect the printer  to the router with a network cable, and then provide the IP address in the printer's settings.  Simply use the "Add a printer" wizard on each computer and input the IP address you  assigned to the printer in the process.

43 

44

What is a Root User? 

Root is the super user account in Unix and Linux. It is a user account for administrative  purposes, and typically has the highest access rights on the system. 

Usually, the root user account is called root. However, in Unix and Linux, any account  with user id 0 is a root account, regardless of the name. It is fairly common for certain  system administrators to have their own root accounts on a system, with their own  passwords. 

Root Access 

Root access means performing something using root privileges. In Linux-based systems, this  means being able to do something using the user id 0, i.e., as root. 

Having root access generally means being able to log into some root account on the server, or  being able to run commands as root on the server, for example by using some privilege  escalation tool such as sudo. 

Root Privileges 

The root account has root privileges. This means it can read and write any files on the  system, perform operations as any user, change system configuration, install and remove  software, and upgrade the operating system and/or firmware. In essence, it can do pretty  much anything on the system. 

It is usually preferable to use dedicated service accounts for running applications and for  managing various operating system subsystems. Access to the root account should be  limited to the absolute minimum number of people and uses. 

Root Password 

When the device is powered on for the first time, it is ready to be configured. Initially, you  log in as the user root with no password. You must configure a plain-text password for the  root-level user (whose username is root) the first time you modify and commit the  configuration. Configuring a plain-text password is one way to protect access to the root  level by unauthorized users. If you forget the root password for the device, you can use the  password recovery procedure to reset the root password. 

Configure the Root Password

When you power on the router or switch, it is ready to be configured. Initially, you log in as  the user root with no password. The root directory is the entry point to all other folders and  files on that device. As a result, access to the root directory is restricted by default to a  predefined user account known as the root user. The root user (also referred to as superuser)  has unrestricted access and full permissions within the system. The expression “log in as  root” is commonly used when an action requires the user to log in to the device as the root  user. 

After you log in, you should configure the root (superuser) password by including the root authentication statement at the [edit system] hierarchy level and configuring one of the  password options: 

If you configure the plain-text-password option, you are prompted to enter and confirm the  password: 

The default requirements for plain-text passwords are: 

The password must be between 6 and 128 characters long. 

You can include most character classes in a password (uppercase letters, lowercase letters,  numbers, punctuation marks, and other special characters). Control characters are not  recommended. 

Valid passwords must contain at least one uppercase letter or one lowercase letter, or one  character class. 

sudo command in Linux with 

sudo (Super User DO) command in Linux is generally used as a prefix of some command  that only superuser are allowed to run. If you prefix “sudo” with any command, it will run  that command with elevated privileges or in other words allow a user with proper  permissions to execute a command as another user, such as the superuser. This is the  equivalent of “run as administrator” option in Windows. The option of sudo lets us have  multiple administrators. 

These users who can use the sudo command need to have an entry in the sudoers file  located at “/etc/sudoers”. Remember that to edit or view the sudoers file you have to use 

sudo command. To edit the sudoers file it is recommended to use “visudo” command. By default, sudo requires that users authenticate themselves with a password which is the  user’s password, not the root password itself. 

Syntax: 

sudo -V | -h | -l | -v | -k | -K | -s | [ -H ] [-P ] [-S ] [ -b ] | [ -p prompt ] [ -c class|- ] [ -a auth_type ] [-r role ] [-t type ] [ -u username|#uid ] commandsudo -V | -h | -l | -L | -v | -k | -K | -s | [ -H ] [-P ] [-S ] [ -b ] | [ -p prompt ] [ -c class|- ] [ -a auth_type ] [-r role ] [-t type ] 

[ -u username|#uid ] command 

-V: The -V (version) option causes sudo to print the version number and exit. If the  invoking user is already root, the -V option will print out a list of the defaults sudo was  compiled with. 

-l: The -l (list) option will print out the commands allowed (and forbidden) the user on the  current host. 

-h or –help: The -h (help) option causes sudo to print a usage message and exit. -v: If, given the -v (validate) option, sudo will update the user’s timestamp, prompting for  the user’s password if necessary. This extends the sudo timeout for another 5 minutes (or  as given in sudoers) but does not run a command. This does not give any output. -k: The -k (kill) option to sudo invalidates the user’s timestamp.So, the next time sudo is  run a password will be required. This option does not require a password and was added  to allow a user to revoke sudo permissions from a .logout file. 

-K: Similar to the -k option, the -K (sure kill) option is used to remove the user’s timestamp  entirely. Likewise, this option does not require a password. 

-b: The -b (background) option tells sudo to run the given command in the background.  Note that if you use the -b option you cannot use shell job control to manipulate the  process. 

-p:The -p (prompt) option allows you to override the default password prompt and use a  custom one. The following percent (‘%’) escapes are supported: 

%u is expanded to the invoking user’s login name;

%U is expanded to the login name of the user the command will be run as (which defaults  to root); 

%h is expanded to the local hostname without the domain name; 

%H is expanded to the local hostname including the domain name (only if the machine’s  hostname is fully qualified or the “fqdn” sudoers option is set); 

%% (two consecutive % characters) are collapsed into a single % character. -n: Use -n option as shown below, which will execute the command without prompting for  the password. This is very helpful when we want to run some of the sudo commands as  background jobs (or in a shell script), where we don’t want sudo to ask for the password. - n option stands for non-interactive. 

-u: The -u (user) option causes sudo to run the specified command as a user other than  root. To specify a uid instead of a username, use #uid. 

-s: The -s (shell) option runs the shell specified by the SHELL environment variable if it is  set or the shell as specified in the file passwd. 

-H: The -H (HOME) option sets the HOME environment variable to the home directory of  the target user (root by default) as specified in passwd. By default, sudo does not modify  HOME. 

-S: The -S (stdin) option causes sudo to read the password from standard input instead of  the terminal device. 

-a: The -a (authentication type) option causes sudo to use the specified authentication type  when validating the user, as allowed by /etc/login.conf. The system administrator may  specify a list of sudo-specific authentication methods by adding an “auth-sudo” entry in  /etc/login.conf. 

–: The — flag indicates that sudo should stop processing command line arguments. It is  most useful in conjunction with the -s flag. 

Run Levels in Linux 

A run level is a state of init and the whole system that defines what system services are  operating. Run levels are identified by numbers. Some system administrators use run levels 

to define which subsystems are working, e.g., whether X is running, whether the network  is operational, and so on. 

Whenever a LINUX system boots, firstly the init process is started which is actually  responsible for running other start scripts which mainly involves initialization of you  hardware, bringing up the network, starting the graphical interface. 

Now, the init first finds the default runlevel of the system so that it could run the start  scripts corresponding to the default run level. 

A runlevel can simply be thought of as the state your system enters like if a system is in a  single-user mode it will have a runlevel 1 while if the system is in a multi-user mode it will  have a runlevel 5

A runlevel in other words can be defined as a preset single digit integer for defining the  operating state of your LINUX or UNIX-based operating system. Each runlevel designates  a different system configuration and allows access to different combination of processes. The important thing to note here is that there are differences in the runlevels according to  the operating system. The standard LINUX kernel supports these seven different runlevels  : 

0 – System halt i.e the system can be safely powered off with no activity. 1 – Single user mode. 

2 – Multiple user mode with no NFS(network file system). 

3 – Multiple user mode under the command line interface and not under the graphical user  interface. 

4 – User-definable. 

5 – Multiple user mode under GUI (graphical user interface) and this is the standard  runlevel for most of the LINUX based systems. 

6 – Reboot which is used to restart the system. 

By default most of the LINUX based system boots to runlevel 3 or runlevel 5. In addition to the standard runlevels, users can modify the preset runlevels or even create  new ones according to the requirement. Runlevels 2 and 4 are used for user defined  

runlevels and runlevel 0 and 6 are used for halting and rebooting the system. Changing runlevel

init is the program responsible for altering the run level which can be called  using telinit command. 

For example, to change a runlevel from 3 to runlevel 5 which will actually allow the GUI to  be started in multi-user mode the telinit command can be used as : 

/*using telinit to change 

runlevel from 3 to 5*/ 

telinit 5 

The changing of runlevels is a task for the super user and not the normal user that’s why it  is necessary to be logged in as super user for the successful execution of the above telinit  command or you can use sudo command as : 

// using sudo to execute telinit 

sudo telinit 5 

The default runlevel for a system is specified in /etc/initab file which will have an entry id : 5 : initdefault if the default runlevel is set to 5 or will have an entry id : 3 : initdefault if the  default runlevel is set to 3. 

Need for changing the runlevel 

There can be a situation when you may find trouble in logging in in case you don’t  remember the password or because of the corrupted /etc/passwd file (have all the user  names and passwords), in this case the problem can be solved by booting into a single user  mode i.e runlevel 1. 

You can easily halt the system by changing the runlevel to 0 by using telinit 0. How To Check The Runlevel In Linux 

Check the Runlevel In Linux (SysV init) 

Here is the list of runlevels in Linux distributions,which were distributed with SysV init as  default service manager. 

0 - Halt 

1 - Single-user text mode 

2 - Not used (user-definable)

3 - Full multi-user text mode 

4 - Not used (user-definable) 

5 - Full multi-user graphical mode (with an X-based login screen) 

6 - Reboot 

Now, let us see how to find the runlevels. 

To find out the system runlevel, open your Terminal and run the following command: $ runlevel 

Sample output: 

N 3 

In the above output, the letter 'N' indicates that the runlevel has not been changed since the  system was booted. And, 3 is the current runlevel i.e the system is in CLI mode. In newer versions of init, you can find the current and previous runlevel details using the  environment variables called RUNLEVEL and PREVLEVEL

Say for example, to find out the current runlevel, you need to run: 

$ echo $RUNLEVEL 

To find the previous runlevel: 

$ echo $PREVLEVEL 

If you'd like to change the RunLevel to something else, edit /etc/inittab file: $ sudo vi /etc/inittab 

Find and edit entry initdefault to the runlevel of your choice. Say for example, to set the  runlevel to multi-user graphical mode (runlevel 5), modify it as shown below. id:5:initdefault: 

Save and close the file. Reboot your system to login to your new runlevel. For more details about runlevels, refer man pages. 

$ man runlevel 

2. Check the Runlevel In Linux (Systemd) 

In recent versions of Linux systems (starting from RHEL 7, Ubuntu 16.04 LTS), the concept  of runlevels has been replaced with systemd targets. 

Here is the list of Systemd targets in Linux distributions,which were distributed  with Systemd as default service manager.

runlevel0.target, poweroff.target - Halt 

runlevel1.target, rescue.target - Single-user text mode 

runlevel2.target, multi-user.target - Not used (user-definable) 

runlevel3.target, multi-user.target - Full multi-user text mode 

runlevel4.target, multi-user.target - Not used (user-definable) 

runlevel5.target,graphical.target - Full multi-user graphical mode (with an X-based login  screen) 

runlevel6.target,reboot.target - Reboot 

In Linux systems that are using Systemd as default service manager, you can find the  current target using command: 

$ systemctl get-default 

Sample output: 

graphical.target 

As you see in the above output, my current runlevel (target in other words) is 5, which is  graphical mode. 

To view all currently loaded targets, run: 

$ systemctl list-units --type target 

The above command will show only the active targets. 

To view all loaded targets (active and inactive), run: 

$ systemctl list-units --type target --all 

If you'd like to change the RunLevel to something else, for example runlevel3.target, set it  as shown below: 

$ sudo systemctl set-default runlevel3.target 

To change to a different target unit in the current session only, run the following command: $ sudo systemctl isolate runlevel3.target 

For more details, refer Systemd man pages. 

$ man systemd 

Check Linux Runlevel Using 'who' command 

As one of the reader suggested in the comment section below, we can also find the runlevel  using who command like below:

$ Who -r 

Sample output: 

 run-level 5 2021-06-09 10:21 

PERFORMANCE ANALYSIS TOOLS AND PROCESSES 

Linux treats each task performed on your system as a process, which is assigned a number  and a name. You can examine these processes and even stop them. Red Hat provides  several tools for examining processes as well as your system performance. Easy monitoring  is provided by several GUI tools, like Red Hat's Procman System Monitor. 

ps Command 

From the command line, you can use the ps command to list processes. With the - aux option, you can list all processes. Piping the output to a grep command with a pattern  enables you to search for a particular process. A pipe funnels the output of a preceding  command as input to a following command. The following command lists all X Window  System processes: 

ps -aux | grep 'X' 

A number of utilities on your system provide detailed information on your processes, as  well as other system information such as CPU and disk use . Although these tools were  designed to be used on a shell command line, displaying output in text lines, several now  have KDE and GNOME versions that provide a GUI interface for displaying results and  managing processes. 

Vmstat — virtual memory statistics 

Vmstat (virtual memory statistics) is a common tool to monitor the memory in Linux.  It can monitor the virtual memory, process and CPU of the operating system. General usage of vmstat:  vmstat interval times, that is, sampling every interval second, a total of sampling times. If times is  Omitted, data will be collected until the user stops manually. For example:

You can use Ctrl + C to stop vmstat collecting data. 

The first line shows the average value of the system since it was started. 

The second line shows what is happening now.The next line shows what happens every 5 seconds. The meaning of each column is in the header. 

The procs: R column shows how many processes are waiting for the CPU, and the B column shows how many processes are sleeping without interruption (waiting for IO). 

Memory: the swap D column shows how many blocks have been swapped out of the disk (page  swapping), the remaining columns show how many blocks are free (Unused),  

how many blocks are being used as buffers, and how many are being used as operating system  Caches. 

Swap: Show swap activity: how many blocks are being swapped in (from disk) and out  (to disk) per second. 

IO: shows how many blocks are read (BI) and written (Bo) from the block device, usually  reflecting the hard disk I / O. 

System: displays the number of interrupts (in) and context switches (CS) per second. CPU: displays the percentage of all CPU time spent on various operations, including  executing user code (non kernel), executing system code (kernel), idle and waiting for Io. Performance of insufficient memory: Free With the rapid decrease of memory, it is useless to  recycle buffers and cachers. A lot of swpd is used, page swap is frequent, the number of read 

and write disks (IO) is increased, the number of page missing interrupts (in) is increased,  the number of context switches (CS) is increased, the number of processes waiting for IO  (b) is increased, and a lot of CPU time is spent waiting for IO (WA) 

Iostat — used to report CPU statistics 

Iostat is used to report CPU statistics and input / output statistics of the whole system, adapter, 

10 

TTY device, disk and CD-ROM. by default, iostat displays the same CPU usage information as vmstat. Use the following command to display extended device statistics:: 

The first line shows the average value since the system started, and then shows the average value of  increment, one line for each device.Common Linux disk IO index abbreviation habits: RQ is request, 

R is read, W is write, Qu is queue, SZ is size, a is coverage, TM is time, SVC is service. Rrqm / s and wrqm / s: combined read and write requests per second. “Combined” means that the  operating system takes out multiple logical requests from the queue and merges them into one request  to the actual disk. R / s and w / s: the number of read and write requests sent to the device per second. RSEC / s and wsec / s: the number of sectors read and written per second.Avgrq – SZ: the number of  sectors requested. 

Avgqu – SZ: the number of requests waiting in the device queue. 

Await: time spent on each IO request. 

Svctm: actual request (service) time. 

%Util: the percentage of time spent with at least one active request. 

Dstat — system monitoring tool 

Dstat shows the CPU usage, disk IO, network contract and page change. The output is color and readable. Compared with vmstat and iostat, the input is more detailed and intuitive. In use, you can directly enter the command, of course, you can also use specific parameters. 

As follows: dstat – cdlmnpsy 

Iotop — Linux Process real time monitoring tool 

The iotop command is a special command to display the IO of the hard disk. The interface style is  similar to the top command. It can show which process is responsible for the IO load. Top is a top class tool for monitoring disk I / O usage. It has a UI similar to top, including PID, user, I / O, process and other information. 

Can be used in a non interactive way: 

iotop – bod Interval to view the I / O of each process. 

11 

You can use pidstat, pidstat – d instat 

Pidstat — monitoring system resources. Pidstat is mainly used to monitor the utilization of system  resources by all or specified processes, such as CPU,  

memory, device IO, task switching, threads, etc. 

usage method: 

pidstat –d interval 

#Count CPU usage information 

pidstat –u interval 

#Statistics memory information 

Pidstat –r interval 

top 

Top commandThe summary area of shows five aspects of system performance information Load: time, number of login users, average system load; 

Process: run, sleep, stop, zombie; 

CPU: user mode, kernel state, nice, idle, waiting for IO, interrupt, etc; 

Memory: total amount, used, idle (system angle), buffer, cache; 

Swap partition: total, used, idle 

The task area displays by default: process ID, valid user, process priority, nice value, virtual memory,  physical memory and shared memory used by the process, process status, CPU usage, memory usage, Cumulative CPU time, and process command line information. 

htop 

Htop is an interactive process viewer in Linux system, a text mode application (in the console or X termineeds ncurses. 

Htop allows users to operate interactively, supports color theme, scrolls horizontally or vertically to broprocess listand supports mouse operation.Compared with top, htop has the following advantages: You or vertically through the process list to see all the processes and the complete command line. On startupthan top. You don’t need to enter a process number to kill a process. 

Htop supports mouse operation 

mpstat

12 

Mpstat is the abbreviation of multiprocessor statistics, is a real-time system monitoring tool. It reports some statistical information about CPU, which is stored in / proc / STAT file. In the multi CPUs  system, it can not only view the average status information of all CPUs, but also view the information of specific CPUs. Common usage: 

mpstat –P ALL interval times 

netstat 

NetstatIt is used to display the statistical data related to IP, TCP, UDP and ICMP protocols. It is  used to check the network connection of each port of the machine. 

Common usage: 

netstat – npl # You can check whether the port you want to open is already open. netstat – rn # Print routing table information. 

netstat – in # Provide the interface information of the system, print the MTU of each  interface, the number of input packets, input errors, the number of output packets, output errors Conflicts and the length of the current output queue. 

strace 

Track the system calls and received signals generated in the process of program execution to help  Analyze the abnormal situation encountered in the process of program or command execution. For example: to see which configuration file mysqld loads on Linux, you can run the following command: 

strace –e stat64 mysqld –print –defaults > /dev/null 

uptime 

It can print the total running time of the system and the average load of the system,Uptime command The last three output figures mean the average load of the system in 1 minute, 5 minutes and 15 minuteslsof 

lsof (list open files)Is a list of the current system to open the file tool. adoptlsofThe tool can view this list to detect and debug the system 

#View file system blocking  

lsof /boot 

#Check which process is using the port number 

13 

lsof -i : 3306 

#View which files users open  

lsof –u username 

#View which files the process opens  

lsof –p 4838 

#View remote open network links  

lsof –i @192.168.34.128 

perf 

Perf is a system performance optimization tool of Linux kernel. The advantage lies in the close  Combination with Linux kernel. It can be first applied to the new feature added to kernel, which can be used to view hotspot functions and the ratio of cache miss, so as to help developers optimize program  Performance. 

Common performance testing tools 

Proficient and proficient in the second part of the performance analysis command tools, the  introduction of several performance testing tools 

perf_events 

A performance diagnostic tool released and maintained with Linux kernel code, maintained  and developed by the kernel community. Perf can be used not only for application  performance statistics, but also for kernel code performance statistics and analysis. 

eBPF tools 

A performance tracking tool using BCC, ebpf map can use custom ebpf program, which is  widely used in kernel tuning, and can also read user level asynchronous code. The important  thing is that this external data can be managed in user space. The K-V format map data body  is created, added and deleted by calling BPF system call in user space.

14 

Perf-tools: 

A software based on perf_ Event (perf) and ftrace. Perf tools has less dependent libraries and  is easy to use. Support Linux 3.2 and above kernel version. 

Bcc (BPF Compiler Collection) 

A perf performance analysis tool using ebpf. A toolkit for creating efficient kernel tracers and  manipulators, including several useful tools and examples. Using the extended BPF  (Berkeley packet filter), officially known as ebpf, a new feature was first added to Linux 3.15.  Multipurpose needs BCC above Linux 4.1. 

Ktap 

A new dynamic performance tracking tool for Linux scripts. Allows users to track Linux  kernel dynamics. Ktap is designed to be interoperable, allowing users to adjust operational  insights, troubleshoot and extend kernel and applications. It is similar to Linux and Solaris  DTrace systemtap. 

Flame Graphs 

Is a use of perf, system, tap, ktap visualization graphics software, allowing the most frequent  code path to quickly and accurately identify, can be the use of  github.com/brendangregg/flamegraph in the development of source code program  generation. 

Procman System Manager 

The current version of Red Hat provides the Procman System Manager for displaying system  information and managing system processes, accessible from System Tools | System  Monitor. There are two panels, one for processes and one for system information. The  System Monitor panel displays graphs for CPU, Memory, and Swap memory usage. Your  disk devices are also listed, showing the amount of disk space used and how much is free.  The Process Listing panel lists your processes, letting you sort or search for processes. You  can use field buttons to sort by name, process ID, user, memory, and even percentage of CPU  time used. The View pop-up menu lets you select all processes, just your own, or active  processes. You can easily stop any process by selecting it and then clicking the End Process 

15 

button. Right-clicking an item displays actions you can take on the process such as stopping  or hiding it. The Memory Maps display, selected from the View menu, shows information on  virtual memory, inodes, and flags. 

GNOME System Manager (GTop) 

With the GNOME System Manager (GTop), you can sort the processes according to their  fields by clicking the field's button at the top of the process list. If you right-click an entry, a  pop-up menu displays actions you can perform on that entry. System statistic summary  graphs are displayed at the top of the window, showing the CPU load, memory use, and  disk use. You can add more graphs or change their display features, such as the colors used.  The GTop window displays three tabbed panels for detailed reports showing processes,  memory use, and file system use. You can add more, showing customized reports such as  only the user processes. Process lists can be further refined to show user, system, or all 

16 

processes. To configure GTop, select the Settings | Preferences to display a menu with  tabbed panels for specifying the update frequency for different statistics, determining the  summaries you want displayed, and what process fields to show. You can find the GNOME  System Manager in the Utilities menu. 

KDE Process Manager (kpm) 

The K Desktop provides the KDE Process Manager (kpm) for viewing and managing your  processes. You can sort the processes according to their fields by clicking the field's button at  the top of the process list. If you select a process, you can then choose to perform several  different actions on it, such as ending it (killing the process) or suspending it (putting it to  sleep). Right-clicking a process entry displays a pop-up menu with the different actions you  can take. You can further refine your process list by choosing to view only your own  processes, system processes, or all processes. 

KDE Task Manager and Performance Monitor (KSysguard) Red Hat also provides the KDE Task Manager and Performance Monitor, KSysguard,  accessible from the Extras System Tools menu as KDE System Guard. This tool allows you to  monitor the performance of your own system as well as remote systems. KSysguard can  provide simple values or detailed tables for various parameters. A System Load panel  provides graphical information about CPU and memory usage, and a Process Table lists  current processes using a tree format to show dependencies. You can design your own  monitoring panels with worksheets, showing different types of values you want to display  and the form you want to display them in, like a bar graph or digital meter. The Sensor  Browser pane is an expandable tree of sensors for information like CPU System Load or  Memory's Used Memory. There is a top entry for each host you are connected to, including  your own localhost. To design your own monitor, create a worksheet and drag and drop a  sensor onto it. 

Introduction to Users and Groups 

While users can be either people (meaning accounts tied to physical users) or accounts that  exist for specific applications to use, groups are logical expressions of organization, tying 

17 

users together for a common purpose. Users within a group share the same permissions to  read, write, or execute files owned by that group. 

Each user is associated with a unique numerical identification number called a user ID (UID).  Likewise, each group is associated with a group ID (GID). A user who creates a file is also the  owner and group owner of that file. The file is assigned separate read, write, and execute  permissions for the owner, the group, and everyone else. The file owner can be changed only  by root, and access permissions can be changed by both the root user and file owner. 

Managing Users 

you can use command line tools for managing users and groups that are listed  in Table below, “Command line utilities for managing users and groups”. 

Utilities 

Description

Id 

Displays user and group IDs.

useradd, usermod, userdel 

Standard utilities for adding, modifying, and deleting user  accounts.

groupadd, groupmod, groupdel 

Standard utilities for adding, modifying, and deleting  groups.

Gpasswd 

Utility primarily used for modification of group password  in the /etc/gshadow file which is used by  the newgrp command.

pwck, grpck 

Utilities that can be used for verification of the password,  group, and associated shadow files.

pwconv, pwunconv 

Utilities that can be used for the conversion of passwords  to shadow passwords, or back from shadow passwords to  standard passwords.

grpconv, grpunconv 

Similar to the previous, these utilities can be used for  conversion of shadowed information for group accounts.



Adding a New User 

To add a new user to the system, type the following at a shell prompt as root: useradd options username

18 

…where options are command-line options as described in Table 4.2, “Common useradd  command-line options”. 

By default, the useradd command creates a locked user account. To unlock the account, run  the following command as root to assign a password: 

passwd username 

Following Table contain Common useradd command-line options 

Option 

Description

-c 'comment

comment can be replaced with any string. This option is generally used to  specify the full name of a user.

- 

d home_directory

Home directory to be used instead of default /home/username/.

-e date 

Date for the account to be disabled in the format YYYY-MM-DD.

-f days 

Number of days after the password expires until the account is disabled.  If 0 is specified, the account is disabled immediately after the password  expires. If -1 is specified, the account is not disabled after the password  expires.

-g group_name 

Group name or group number for the user’s default (primary) group. The  group must exist prior to being specified here.

-G group_list 

List of additional (supplementary, other than default) group names or  group numbers, separated by commas, of which the user is a member. The  groups must exist prior to being specified here.

-m 

Create the home directory if it does not exist.

-M 

Do not create the home directory.

-N 

Do not create a user private group for the user.

-p password 

The password encrypted with crypt.

-r 

Create a system account with a UID less than 1000 and without a home  directory.

-s 

User’s login shell, which defaults to /bin/bash.

-u uid 

User ID for the user, which must be unique and greater than 999.



Adding a New Group 

To add a new group to the system, type the following at a shell prompt as root:

19 

groupadd options group_name 

Common groupadd command-line options 

Option 

Description

-f, --force 

When used with -g gid and gid already exists, groupadd will choose  another unique gid for the group.

-g gid 

Group ID for the group, which must be unique and greater than 999.

-K, --key key=value 

Override /etc/login.defs defaults.

-o, --non-unique 

Allows creating groups with duplicate GID.

-p, -- 

password password

Use this encrypted password for the new group.

-r 

Create a system group with a GID less than 1000.



Adding an Existing User to an Existing Group 

Use the usermod utility to add an already existing user to an already existing group. 

Various options of usermod have different impact on user’s primary group and on his or her  supplementary groups. 

To override user’s primary group, run the following command as root

~]# usermod -g group_name user_name 

To override user’s supplementary groups, run the following command as root: ~]# usermod -G group_name1,group_name2,... user_name 

Note that in this case all previous supplementary groups of the user are replaced by the new  group or several new groups. 

To add one or more groups to user’s supplementary groups, run one of the following  commands as root

~]# usermod -aG group_name1,group_name2,... user_name 

~]# usermod --append -G group_name1,group_name2,... user_name

20 

Creating Group Directories 

System administrators usually like to create a group for each major project and assign people  to the group when they need to access that project’s files. With this traditional scheme, file  management is difficult; when someone creates a file, it is associated with the primary group  to which they belong. When a single person works on multiple projects, it becomes difficult  to associate the right files with the right group. However, with the UPG scheme, groups are  automatically assigned to files created within a directory with the setgid bit set. The setgid bit  makes managing group projects that share a common directory very simple because any files  a user creates within the directory are owned by the group that owns the directory. 

For example, a group of people need to work on files in the /opt/myproject/ directory.  Some people are trusted to modify the contents of this directory, but not everyone. 

1. As root, create the /opt/myproject/ directory by typing the following at a shell  prompt: 

mkdir /opt/myproject 

2. Add the myproject group to the system: 

groupadd myproject 

3. Associate the contents of the /opt/myproject/ directory with the myproject group: chown root:myproject /opt/myproject 

4. Allow users in the group to create files within the directory and set the setgid bit: chemod 2775 /opt/myproject 

At this point, all members of the myproject group can create and edit files in  the /opt/myproject/ directory without the administrator having to change file  permissions every time users write new files. To verify that the permissions have been  set correctly, run the following command: 

~]# ls -ld /opt/myproject 

drwxrwsr-x. 3 root myproject 4096 Mar 3 18:31 /opt/myproject 

5. Add users to the myproject group: 

user mod -aG myproject username

21 

Merging groups- group management tools  

  

 One of the many benefits of having password database files that have a well-defined  format in straight text is that it is easy for anyone to write custom management tools. Indeed,  many site administrators have already done this to integrate their tools along with the rest of  their organization’s infrastructure. They can, for example, start the process of creating a new  user from the same form that lets them update the corporate phone and e-mail directory,  LDAP servers, web pages, and so on. Of course, not everyone wants to write custom tools,  which is why Linux comes with several existing tools that do the job for you. In this section,  we discuss user management tools that can be launched from the command-line interface, as  well as graphical user interface (GUI) tools. Of course, learning how to use both is the  preferred route, since they both have advantages 

Command-Line User Management 

You can choose from among several command-line tools to perform the same actions  performed by the GUI tools. Some of the most popular command-line tools are useradd,  userdel, usermod, groupadd, groupdel, and groupmod. The compelling advantage of using  command-line tools for user management, besides speed, is the fact that the tools can usually  be incorporated into other automated functions 

useradd 

As the name implies, useradd allows you to add a single user to the system. Unlike the GUI  tools, this tool has no interactive prompts. Instead, all parameters must be specified on the  command line 

Here’s the syntax for using this too 

Usage: useradd [options] LOGIN Options:  

-b, --base-dir BASE_DIR  

-c, --comment COMMENT  

-d, --home-dir HOME_DIR 

-D, --defaults 

-e, --expiredate EXPIRE_DATE 

-f, --inactive INACTIVE  

-g, --gid GROUP  

-G, --groups GROUPS 

-k, --skel SKEL_DIR 

-K, --key KEY=VALUE 

-l, --no-log-init 

-m, --create-home  

-M, --no-create-home  

-N, --no-user-group  

-o, --non-unique  

-p, --password PASSWORD 

-r, --system 

-s, --shell SHELL

22 

-u, --uid UID  

-U, --user-group 

Take note that most of the options are optional. The useradd tool assumes preconfigured  defaults in its usage. The only non-optional parameter is the LOGIN parameter or the  desired username. Also, don’t be intimidated by this long list of options! They are all quite  easy to use and some of them are described in Table 5-1 

Option Description -c, --comment 🡪 Allows you to set the user’s  name in the GECOS field. As with any command-line parameter, if the value includes a  space, you will need to add quotes around the text. For example, to set the user’s name to  Ying Yang, you would have to specify -c "Ying Yang". 

-d, --home-dir 🡪 By default, the user’s home  directory is /home/user_name. When a new user is created, the user’s home directory is  created along with the user account, so if you want to change the default to another place,  you can specify the new location with this parameter 

-e, --expiredate 🡪 It is possible for an account to  expire after a certain date. By default, accounts never expire. To specify a date, use the  YYYY-MM-DD format. For example, -e 2019-10-28 means the account will expire on October  28, 2019 

-f, --inactive 🡪 This option specifies the  number of days after a password expires that the account is still usable. A value of 0 (zero)  indicates that the account is disabled immediately. A value of -1 will never allow the account  to be disabled, even if the password has expired. (For example, -f 3 will allow an account to  exist for three days after a password has expired.) The default value is -1  

-g, --gid 🡪 Using this option, you can  specify the user’s default group in the password file. You can use a number or name of the  group; however, if you use a name of a group, the group must exist in the /etc/group file. 

-G, --groups 🡪 This option allows you to  specify additional groups to which the new user will belong. If you use the -G option, you  must specify at least one additional group. You can, however, specify additional groups by  separating the elements in the list with commas. For example, to add a user to the project  and admin groups, you would specify -G project,admin 

-m, --create -home [-k skel-dir ] 🡪 By default, the system  automatically creates the user’s home directory. This option is the explicit command to create  the user’s home directory. Part of creating the directory is copying default configuration files  into it. These files come from the /etc/skel directory by default. You can change this by 

23 

using the secondary option -k skel-dir. (You must specify -m in order to use -k.) For example,  to specify the /etc/adminskel directory, you would use -m -k /etc/adminskel 

-M 🡪 If you used the -m option, you  cannot use -M, and vice versa. This option tells the command not to create the user’s home  directory 

-N 🡪 Some Linux distros automatically  create a new group with the same name as the new user’s login as part of the process of  adding a user. You can disable this behavior by using this option on such distros 

-s, shell 🡪 A user’s login shell is the first  program that runs when a user logs into a system. This is usually a command line  environment, unless you are logging in from the X Window System login screen. By default,  this is the Bourne Again Shell (/bin/bash), though some folks like to use other shells, such as  the Turbo C Shell (/bin/tcsh). 

-u, --uid 🡪 By default, the program will  automatically find the next available UID and use it. If, for some reason, you need to force a  new user’s UID to be a particular value, you can use this option. Remember that UIDs must  be unique for all users  

LOGIN or username 🡪 finally, the only parameter that isn’t  optional! You must specify the new user’s login name 

usermod 

 The usermod command allows you to modify an existing user in the system. It works in  much the same way as useradd. Its usage is summarized here

Usage: usermod [options] LOGIN 

Options:  

-c, --comment COMMENT new value of the GECOS field 

-d, --home HOME_DIR new home directory for the user account  

-e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE -f, --inactive INACTIVE set password inactive after expiration  

-g, --gid GROUP force use GROUP as new primary group  

-G, --groups GROUPS new list of supplementary GROUPS 

-a, --append append the user to supplemental GROUPS 

-l, --login NEW_LOGIN new value of the login name  

-L, --lock lock the user account 

-m, --move-home move contents of the home directory 

-o, --non-unique allow using duplicate (non-unique) UID 

-p, --password PASSWORD use encrypted password for the new password -s, --shell SHELL new login shell for the user account 

-u, --uid UID new UID for the user account 

24 

-U, --unlock unlock the user account 

Every option you specify when using this command results in that particular parameter  being modified for the user. All but one of the parameters listed here are identical to the  parameters documented for the useradd command. The one exception is -l. The -l option  allows you to change the user’s login name. This and the -u option are the only options that  require special care. Before changing the user’s login or UID, you must make sure the user is  not logged into the system or running any processes. Changing this information if the user is  logged in or running processes will cause unpredictable results 

userdel 

 The userdel command does the exact opposite of useradd—it removes existing users. This  straightforward command has only two commonly used optional parameters and one  required parameter: 

Usage: userdel [options] LOGIN 

Options:  

-f, --force force removal of files, even if not owned by user  

-r, --remove remove home directory and mail spool  

groupadd 

The group-related commands are similar to the user commands; however, instead of  working on individual users, they work on groups listed in the /etc/group file. Note that  changing group information does not cause user information to be automatically changed.  For example, if you remove a group whose GID is 100 and a user’s default group is specified  as 100, the user’s default group would not be updated to reflect the fact that the group no  longer exists. The groupadd command adds groups to the /etc/group file. The command line options for this program are as follows: 

Usage: groupadd [options] GROUP 

groupdel 

Even more straightforward than userdel, the groupdel command removes existing groups  specified in the /etc/group file. The only usage information needed for this command is Usage: groupdel group 

where group is the name of the group to remove

groupmod 

The groupmod command allows you to modify the parameters of an existing group. The  syntax and options for this command are shown here 

Usage: groupmod [options] GROUP 

Options: 

-g, --gid GID change the group ID to GID  

-n, --new-name NEW_GROUP change the name to NEW_GROUP 

-o, --non-unique allow to use a duplicate (non-unique) GID  

-p, --password PASSWORD change the password to this (encrypted) PASSWORD 

The -g option allows you to change the GID of the group, and the -n option allows you to specify a new name  of a group. In addition, of course, you need to specify the name of the existing group as the last parameter

25 

 Option Description 

-g gid 🡪 Specifies the GID for the new group as  gid. This value must be unique, unless the -o option is used. By default, this value is  automatically chosen by finding the first available value greater than or equal to 1000 

-r, --system 🡪 By default, Fedora, RHEL, and  CentOS distros search for the first GID that is higher than 999. The -r option tells groupadd  that the group being added is a system group and should have the first available GID under  999. 

-f, --force 🡪 This is the force flag. This will  cause groupadd to exit without an error when the group about to be added already exists on  the system. If that is the case, the group won’t be altered (or added again). It is a Fedora- and  RHEL-specific option 

GROUP 🡪 This option is required. It  specifies the name of the group you want to add to be group. 

File Permissions 

All the three owners (user owner, group, others) in the Linux system have three types of  permissions defined. Nine characters denotes the three types of permissions. 

1) Read (r) : The read permission allows you to open and read the content of a file. But  you can't do any editing or modification in the file. 

2) Write (w) : The write permission allows you to edit, remove or rename a file. For  instance, if a file is present in a directory, and write permission is set on the file but  not on the directory, then you can edit the content of the file but can't remove, or  rename it. 

3) Execute (x): In Unix type system, you can't run or execute a program unless execute  permission is set.But in Windows, there is no such permission available. 

Permissions are listed below: 

permission on a file on a directory 


r (read) 

read file content (cat) 

w (write) 

change file content (vi) 

x (execute) 

execute the file 



read directory content (ls) create file in directory (touch) enter the directory (cd)

26 

Permission set 

Look at the above snapshot, there are ten characters (-rw-rw-r--) before the user owner. We'll  describe these ten characters here. 

File permissions for (-rw-rw-r--) 

position characters ownership 


2-4 

rw- 

5-7 

rw- 

8-10 

r-- 



denotes file type permission for user permission for group permission for other 

When you are the User owner, then the user owner permission applies to you. Other  permissions are not relevant to you. 

When you are the Group then the group permission applies to you. Other permissions are  not relevant to you. 

When you are the Other, then the other permission applies to you. User and group  permissions are not relevant to you. 

Permission Example 

Now we'll show some examples how permissions can be seen for a file or directory. Look at the above snapshot, different directories and files have different permissions.

27 

First letter (-) or d represents the files and directories respectively. 

Now, from remaining nine letters, first triplet represents the permission for user  owner. Second triplet represents the permission for group owner. Third triplet represents  the permission for other . 

Managing password-policy& shadow password 

At one time, encrypted passwords were stored in the world-readable /etc/passwd file. This  was thought to be reasonably secure until dictionary attacks on encrypted passwords became  common. At that point, the encrypted passwords were moved to a separate /etc/shadow file  which is readable only by root. This new file also allowed password aging and expiration  features to be implemented….Like /etc/passwd, each user has a line in the /etc/shadow file.  A sample line from /etc/ shadow with its nine colon-separated fields is shown below. 

Username of the account this password belongs to. 

The encrypted password of the user. The format of encrypted passwords is discussed later in  this section. 

The day on which the password was last changed. This is set in days since 1970-01-01 and is  calculated in the UTC time zone. 

The minimum number of days that have to elapse since the last password change before the  user can change it again. 

The maximum number of days that can pass without a password change before the  password expires. An empty field means it does not expire based on time since the last  change. 

Warning period. The user will be warned about an expiring password when they login for  this number of days before the deadline. 

Inactivity period. Once the password has expired, it will still be accepted for login for this  many days. After this period has elapsed, the account will be locked. 

The day on which the password expires. This is set in days since 1970-01-01 and is calculated  in the UTC time zone. An empty field means it does not expire on a particular date. The last field is usually empty and is reserved for future use. 

Format of an Encrypted password 

The encrypted password field stores three pieces of information: the hashing algorithm used,  the salt, and the encrypted hash. Each piece of information is delimited by the $ sign. 

The hashing algorithm used for this password. The number 6 indicates it is a SHA-512 hash,  which is the default in Red Hat Enterprise Linux 8. A 1 would indicate MD5, a 5 SHA-256. The salt used to encrypt the password. This is originally chosen at random. The encrypted hash of the user’s password. The salt and the unencrypted password are  combined and encrypted to generate the encrypted hash of the password. The use of salt prevents two users with the same password from having identical entries in  the / etc/shadow file. For example, even if user01 and user02 both use mypass as their  passwords, their encrypted passwords in /etc/shadow will be different if their salts are  different.

28 

Password verification  

When a user tries to log in, the system looks up the entry for the user in /etc/shadow,  combines the salt for the user with the unencrypted password that was typed in, and  encrypts them using the hashing algorithm specified. If the result matches the encrypted  hash, the user typed in the right password. If the result does not match the encrypted hash,  the user typed in the wrong password and the login attempt fails. This method allows the  system to determine if the user typed in the correct password without storing that password  in a form usable for logging in. 

Configuring password aging  

The following diagram relates the relevant password aging parameters, which can be  adjusted using the chage command to implement a password aging policy. 

[user01@host ~]$ sudo chage -m 0 -M 90 -W 7 -I 14 user03 

- The preceding chage command uses the -m, -M, -W, and -I options to set the minimum age,  maximum age, warning period, and inactivity period of the user’s password, respectively. - The ‘chage -d 0 user03’ command forces the user03 user to update its password on the next  login. - The ‘chage -l user03’ command displays the password aging details of user03. - The  chage -E 2019-08-05 user03’ command causes the user03 user’s account to expire on 2019-08- 05 (in YYYY-MM-DD format). 

[user01@host ~]$ date -d "+45 days" -u 

Thu May 23 17:01:20 UTC 2019

29 

Edit the password aging configuration items in the /etc/login.defs file to set the default  password aging policies. The PASS_MAX_DAYS sets the default maximum age of the  password. The PASS_MIN_DAYS sets the default minimum age of the password. The  PASS_WARN_AGE sets the default warning period of the password. Any change in the  default password aging policies will be effective for new users only. The existing users will  continue to use the old password aging settings rather than the new ones. 

Restricting Access 

You can use the chage command to set account expiration dates. When that date is reached,  the user cannot log in to the system interactively. The usermod command can lock an  account with the -L option. 

[user01@host ~]$ sudo usermod -L user03 

[user01@host ~]$ su - user03 

Password: mypass 

su: Authentication failure 

usermod If a user leaves the company, the administrator may lock and expire an account  with a single command. The date must be given as the number of days since 1970-01-01, or in  the YYYY-MM-DD format. 

[user01@host ~]$ sudo usermod -L -e 2019-10-05 user03 

The preceding usermod command uses the -e option to set the account expiry date for the  given user account. The -L option locks the user’s password. Locking the account prevents  the user from authenticating with a password to the system. It is the recommended method  of preventing access to an account by an employee who has left the company. If the  employee returns, the account can later be unlocked with usermod -U. If the account was  also expired, be sure to also change the expiration date. 

Managing Disk Quotas 

CentOS disk quotas can be enabled both; alerting the system administrator and denying  further disk-storage-access to a user before disk capacity is exceeded. When a disk is full,  depending on what resides on the disk, an entire system can come to a screeching halt until  recovered. 

Enabling Quota Management in CentOS Linux is basically a 4 step process − Step 1 − Enable quota management for groups and users in /etc/fstab. Step 2 − Remount the filesystem. 

Step 3 − Create Quota database and generate disk usage table. 

Step 4 − Assign quota policies.

30 

Enable Quota Management in /etc/fstab 

First, we want to backup our /etc/fstab filen − 

[root@centosLocal centos]# cp -r /etc/fstab ./ 

We now have a copy of our known working /etc/fstab in the current working directory. # 

# /etc/fstab 

# Created by anaconda on Sat Dec 17 02:44:51 2016 

# Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # 

/dev/mapper/cl-root / xfs defaults 0 0 

UUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0 

/dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0 

/dev/mapper/cl-swap swap swap defaults 0 0 

We made the following changes in the options section of /etc/fstab for the volume or Label to  where quotas are to be applied for users and groups. 

usrquota 

grpquota 

As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps  involved. /home is on the same disk as /. Further investigation shows / is set for noquota,  which is a kernel level mounting option. We must re-configure our kernel boot options. root@localhost rdc]# mount | grep ' / ' 

/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota) 

[root@localhost rdc]# 

Reconfiguring Kernel Boot Options for XFS File Systems 

This step is only necessary under two conditions − 

When the disk/partition we are enabling quotas on, is using the xfs file system When the kernel is passing noquota parameter to /etc/fstab at boot time Step 1 − Make a backup of /etc/default/grub. 

cp /etc/default/grub ~/ 

Step 2 − Modify /etc/default/grub

Here is the default file. 

GRUB_TIMEOUT=5 

GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)" 

GRUB_DEFAULT=saved 

GRUB_DISABLE_SUBMENU=true 

GRUB_TERMINAL_OUTPUT="console" 

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb  quiet" 

GRUB_DISABLE_RECOVERY="true" 

We want to modify the following line −

31 

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb  quiet" 

to 

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv =cl/swap rhgb quiet rootflags=usrquota,grpquota" 

Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our  system will fail to boot if any errors were made in the configuration. Please, try this part of  the tutorial on a non-production system. 

Step 3 − Backup your working grub.cfg 

cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak 

Make a new grub.cfg 

[root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg 

Generating grub configuration file ... 

Found linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64 

Found initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img 

Found linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd Found initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img done 

[root@localhost rdc]# 

Reboot 

[root@localhost rdc]#reboot 

If all modifications were precise, we should not have the availability to add quotas to  the xfs file system. 

[rdc@localhost ~]$ mount | grep ' / ' 

/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota) 

[rdc@localhost ~]$ 

We have passed the usrquota and grpquota parameters via grub. 

Now, again edit /etc/fstab to include / since /homeon the same physical disk. /dev/mapper/cl-root/xfs 

defaults,usrquota,grpquota 0 0 

Now let's enable the quota databases. 

[root@localhost rdc]# quotacheck -acfvugM 

Make sure Quotas are enabled. 

[root@localhost rdc]# quotaon -ap 

group quota on / (/dev/mapper/cl-root) is on 

user quota on / (/dev/mapper/cl-root) is on 

group quota on /home (/dev/mapper/cl-home) is on 

user quota on /home (/dev/mapper/cl-home) is on 

[root@localhost rdc]# 

Remount the File System 

If the partition or disk is separate from the actively booted partition, we can remount without  rebooting. If the quota was configured on a disk/partition booted in the root directory /, we 

32 

may need to reboot the operating system. Forcing the remount and applying changes, the  need to remount the filesystem may vary. 

[rdc@localhost ~]$ df 

Filesystem 1K-blocks Used Available Use% Mounted on 

/dev/mapper/cl-root 22447404 4081860 18365544 19% / 

devtmpfs 903448 0 903448 0% /dev 

tmpfs 919308 100 919208 1% /dev/shm 

tmpfs 919308 9180 910128 1% /run 

tmpfs 919308 0 919308 0% /sys/fs/cgroup 

/dev/sda2 1268736 176612 1092124 14% /boot 

/dev/mapper/cl-var 4872192 158024 4714168 4% /var 

/dev/mapper/cl-home 18475008 37284 18437724 1% /home 

tmpfs 183864 8 183856 1% /run/user/1000 

[rdc@localhost ~]$ 

As we can see, LVM volumes are in use. So it's simple to just reboot. This will  remount /home and load the /etc/fstab configuration changes into active configuration. Create Quota Database Files 

CentOS is now capable of working with disk quotas on /home. To enable full quota supprt,  we must run the quotacheck command. 

quotacheck will create two files − 

aquota.user 

aquota.group 

These are used to store quota information for the quota enabled disks/partitions. Following are the common quotacheck switches. 


Switch 

-u 

-g 

-c 

-v 



Action 

Checks for user quotas 

Checks for group quotas 

Quotas should be enabled for each file system with enables quotas Displays verbose output 

Add Quota Limits Per User 

For this, we will use the edquota command, followed by the username − [root@localhost rdc]# edquota centos 

Disk quotas for user centos (uid 1000): 

Filesystem blocks soft hard inodes soft hard 

/dev/mapper/cl-root 12 0 0 13 0 0 

/dev/mapper/cl-home 4084 0 0 140 0 0 

Let's look at each column. 

Filesystem − It is the filesystem quotas for the user applied to blocks − How many blocks the user is currently using on each filesystem

33 

soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time  period 

hard − Set blocks for a hard limit. Hard limit is total allowable quota 

inodes − How many inodes the user is currently using 

soft − Soft inode limit 

hard − Hard inode limit 

To check our current quota as a user − 

[centos@localhost ~]$ quota 

Disk quotas for user centos (uid 1000): 

Filesystem blocks quota limit grace files quota limit grace 

/dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$ Following is an error given to a user when the hard quota limit has exceeded. [centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/ 

cp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE 

1611.iso.part’: Disk quota exceeded 

[centos@localhost Downloads]$ 

As we can see, we are closely within this user's disk quota. Let's set a soft limit warning. This  way, the user will have advance notice before quota limits expire. From experience, you will  get end-user complaints when they come into work and need to spend 45 minutes clearing  files to actually get to work. 

As an Administrator, we can check quota usage with the repquota command. [root@localhost Downloads]# repquota /home 

Block limits File limits 

User used soft hard grace used soft hard grace 

---------------------------------------------------------------------------------------- 

root -- 0 0 0 3 0 0 

centos -+ 6189824 56123456 61234568 541 520 540 6days 

[root@localhost Downloads]# 

As we can see, the user centos has exceeded their hard block quota and can no longer use  any more disk space on /home

-+denotes a hard quota has been exceeded on the filesystem. 

When planning quotas, it is necessary to do a little math. What an Administrator needs to  know is:How many users are on the system? How much free space to allocate amongst  users/groups? How many bytes make up a block on the file system? 

Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a  "safe" buffer of free-space on the file system that will remain in worst case scenario: all  quotas are simultaneously exceeded. This is especially on a partition that is used by the  system for writing logs. 

Configuration and managing print services

34 

Linux, different commands are used to print a file or output. Printing from a Linux terminal  is a straightforward process. The lp and lpr commands are used to print from the terminal.  And, the lpg command is used to display queued print jobs

Printing the double-sided document or in portrait mode is a bit complicated process. And  there may be many other operations that we want to perform, such as printing multiple copies or  canceling a print job, which can be difficult to perform. 

Linux lp and lpr command 

CUPS (Common Unix Printing System) provides the system commands for printing files.  Additionally, it supports several standard options to control the print operation. Let's see  how to print files. 

How to print files in Linux 

To print files from Linux 

terminal, execute the lp and lpr command. It will print the file from the default printer.  Execute it as follows: 

1) lp < file name>  

2) lpr <file name>  

Choosing a Printer 

If our system has connected with more than one printer, you can choose one of them to print  the particular file. These printers can be connected with different methods such as parallel,  serial, USB 

port, networking. 

To display a list of the connected printers, execute the command as follows: 

lpstat -p -d  

The above command will display a list of available printers. The '-p' option is used to display  a list of the printers, and the '=d' option specifies the default printer. 

To print a file with a specific printer, execute the lp command with the '-d' option or lpr  command with the '-P' option. Consider the following commands: 

lp -d <printer name> <file name>  

lpr -P <printer name> <file name>  

In the above commands, both commands will perform the same operation. For example, to print a file 'Notes.pdf' by the printer name 'HPM375', execute the command  as follows:

35 

lpr -P HPM375 Notes.pdf  

Setting the Default Printer 

We can set a particular printer as a default printer from the connected printers. To set a  printer as the default printer, execute the lpoptions command with the '-d' option as follows: 

1) lpoptions -d < printer name> 

Printing Multiple Copies 

The lp and lpr both commands support to print multiple copies of a file. To specify the  number of copies, use the '-n' option with lp command as follows: 

lp -n number <file name>  

Use the '-#' option with lpr command for the same task as follows: 

lpr -#number <filename>  

Generally, the printed copies are not collated. To collate the copies, use the "-o collate=true"  option. Consider the following commands: 

lp -n number -o collate=true <filename>  

lpr -#number -o collate=true <filename> 

Canceling a Print Task 

We can cancel a print task by using the cancel and lprm commands. To cancel a queued job,  execute the commands as follows: 

cancel job-id 

36 

 lprm job-id  

The Job-id can be seen by executing the following commands: 

lpq 

lpstat 

Moving a Print Task 

We can forward a queued job to a different printer by using the lpmove command. To move  a print task to a new printer or class, execute the command as follows: 

lpmove job-id destination  

The job-id is the process id of the task that can be seen by lp or lpstat commands.  The destination is the printer, to which we want to forward the print task. The most common error that can be seen during the move operation is "command not  found" error. Since, the lpmove command is located in the system command directory, and  may not be in our current path. To overcome this problem, specify the full to the path. 

Selecting the Media Size, Type and Source 

To set the media size, type, and source, use the "-o media=xyz" option. Some common media  customization examples are as follows: 

lp -o media=Letter <filename>  

lp -o media=Letter,MultiPurpose <filename>  

lpr -o media=Letter,Transparency <filename>  

lpr -o media=Letter,MultiPurpose,Transparency <filename>  

The media options are completely dependent on the type of printer. But some standard  printers support the following options: 

1)Letter: It is used for the US Letter (8.5x11 inches, or 216x279mm). 

2)Legal: It is used for the US Legal (8.5x14 inches, or 216x356mm). 

3)A4: It is used for ISO A4 (8.27x11.69 inches, or 210x297mm). 

4)COM10: It is used for US #10 Envelope (9.5x4.125 inches, or 241x105mm). 5)DL: It is used for ISO DL Envelope (8.66x4.33 inches, or 220x110mm). 6)Transparency: It is used for transparency media type or source. 

7)Upper: It is used to specify the upper paper tray. 

8)Lower: It is used to specify the lower paper tray. 

9)MultiPurpose: It is used to specify a multi-purpose paper tray. 

10)LargeCapacity: It is used to specify a large capacity paper tray.

37 

The printer's PPD file has a description of all supported options. To list them, execute the  following command: 

lpoptions -p printer -l  

We can customize the page size by using the 'Custom' option. We can specify options in the  following forms: 

lp -o media=Custom.width*length <filename>  

We can specify the width and length in the "in, cm, and mm" unit. 

Printing on Both Sides of the Paper 

To enable two-sided printing, use the "-o sides option" as follows: 

lp -o sides=two-sided-short-edge <filename>  

lp -o sides=two-sided-long-edge <filename>  

The above commands will enable two-sided printing if supported by the printer. The "-short edge" is used for landscape mode, and the "-long-edge" is used for portrait mode. 

Local Printer Configuration  

A Printer is an essential part of a computer that allows us to print the intangible data onto a  paper sheet. Generally, people go to cyber cafes for print out works. It is because they do not  have a computer in their homes or are not computer users and are not knowledgeable about  the technical world. If you have to Google such a question, it probably means that you are a  technical person or computer user, owns a printer or has purchased one and wants to learn  how to connect your printer to the computer. If you have a printer

38 

1)Laser Printers: The printers are used to quickly print hundreds of pages (in just a few  minutes). 

Such printers are used for printing legal or professional documents. We can find such  printers at cyber cafes or government sectors. 

2)Inkjet Printers: These printers are used by a common group of people. Such a printer is  capable of printing documents for schools, project pages, photos, online forms, online  purchasing receipts, etc.

People choose Inkje? printers as their personal assistant. 

3)3D Printers: It is a new variety of printer that is used for printing 3D parts or tools, and  replaced parts for broken objects. It is used for taking digital blueprints of the objects.

39 

Such printers are used for architectural purposes, designing purposes, and many more. 3D  printers are also used for printing toys for kids. 

Network Printer Configuration  

It is only natural to share computer resources. People are increasingly preferring to share a  printer across two or more computers at home rather than at work, especially as more  families acquire several computers. c 

Those who use numerous PCs at home or at a business may want to share a printer in terms  of convenience or cost savings. This article discusses how to make a printer accessible to  numerous computers with the help of using a variety of approaches. Before sharing a printer  over the network, decide on the configuration you want to utilize. 

The various arrangements, as well as their benefits and drawbacks, are listed below.

40 

Wireless printer 

In modern times, most printers (especially midrange and high-end ones) can have the  potential to connect directly to a user's network. Because they are the easiest to set up and  detect, these printers have a major edge in terms of convenience of use. Wireless printers are  practically plug-and-play with Windows Vista, since they are identified by a computer's  word processor or Internet browser. The sole disadvantage of this setup is that it necessitates  the creation of a wireless network. 

Skip Ad 

You can install and connect the printer to all of your computer systems once it has been  setup and linked to your wireless network. 

Dedicated print server 

A print server is a hardware device, which is another option to connect a printer to multiple  computers. A print server can be used to connect a tiny device to your network that  delegates and queues print tasks for numerous workstations. Print servers allow you to print  even if the computer connected to your printer is turned off (network printer configuration),  but they are more expensive and take longer to set up.

41 

Printer connected to a computer or server 

Connecting a printer to a host computer is the most common way to share it. Because of its  simplicity and inexpensive cost, this approach is often used. The printer is effectively  "shared" by the host computer, allowing other computers on the network to print through a  LAN (local area network) or an Internet connection. But, in order for other machines to use  the printer, this method requires the host computer to be turned on at all times that is the  main downside of this method. Furthermore, on the host computer, you must have a  network and a printer installed in order to print through another networked computer. 

Step 1 

Use a switch to turn things on and off. A printer switch, which works with both parallel and  USB printers, you can purchase this printer switch. Connect the switch to both computers  and the printer, then set up the printer on each computer as usual. Some older parallel  printer switches need you, which is used to manually flip a switch to assign one computer to  the printer at a time; however, the latest and slightly more expensive switches have the  potential to do it automatically. For this approach to work, your PCs must be close together. 

Step 2 

If you are using Microsoft Windows, you can share your printer. On both computers, go to  Control Panel, then "System," and make sure that file and printer sharing is enabled, as well  as that systems have the same workgroup name. Now, select "Printers and Faxes" from the 

42 

Control Panel on the computer to which the printer is already attached. Select "Properties"  from the drop-down menu when right-clicking on the printer. Choose the "Sharing" option,  then "Share this Printer" and a name for it. Select "Add a Printer" from the "Printers and  Faxes" menu on the other computer. 

The alternatives are "Network Printer" or "Printer linked to another computer." The name of  the printer you shared on the first computer should display when you select Browse for a  Printer. Follow the wizard's instructions to install the printer software on the second  computer, and have the printer's driver CD handy. 

Step 3 

Invest in a network printer. A network connection is now available on many low-cost  printers. All you will need is a router in close proximity to the printer, or a connection to a  router in close proximity to the printer. Set up and switch on the printer. Connect the printer  to the router with a network cable, and then provide the IP address in the printer's settings.  Simply use the "Add a printer" wizard on each computer and input the IP address you  assigned to the printer in the process.

43 

44

No comments:

Post a Comment