Sunday 5 July 2020

How to check the most recent system shutdown time?

276. How to check the most recent system shutdown time?

# last -x | grep shutdown | head -1
# last -x shutdown

277. Command to check processor statistics?

# mpstat 
# iostat

278. What are the common standard ports used?

=> 21/20 ftp
= 22 ssh
= 23 telnet
= 25 smtp
= 53 DNS (tcp/udp)
= 68 DHCP
= 69 TFTP
= 80/443 http/https (tcp)
= 88/464 Kerberos (tcp/udp)
= 110 pop3
= 123 NTP(udp)
= 137 nmbd
= 138,139,445 smbd
= 143 IMAP
= 161 SNMP
= 389/636 LDAP/LDAPS (tcp)
= 514 (udp) syslogd
= 2049 NFS

279. How can you make the file untouchable.txt to be immutable (un-alterable) so that it will not be able to be changed or deleted by any user including root?

To achieve this you can use attributes to change the file to be immutable using below command
chattr +i untouchable.txt

280. How can you run a PHP statement from the command line without creating a file?

You can use the PHP interactive input
# php -r ‘echo “Hello Worldrn”;’
281. How to reduce/extend a root lvm?

To Reduce 
– boot into rescue mode without mounting file system (linux rescue nomount).
– activate the lvms if required as explained in previous answer.
– run file system check on respective lvm.
– reduce file system : #resize2fs /dev/vg1/rootlv 10G
– Next, reduce the corresponding lvm : #lvreduce -L 10G /dev/vg1/rootlv (reducing the LV to 10GB)
– Run fsck again.
– Verify the lvm is reflecting the correct size.

To extend 
– no need to boot into rescue, this could be done online.
– unmount the respective file system first (this is not absolutely necessary, size can be extended online, but always recommended to unmount respective file system)
– Extend the lv : #lvextend -L +1G /dev/vg1/rootlv (extending the size to 1GB plus)
– Extend the file system : #resize2fs /dev/vg1/rootlv
– Run fsck if necessary.

282. How to find out backup superblocks for a logical volume?

# dumpe2fs /dev/vg1/rootlv | grep -i “backup superblock”
# mke2fs -n /dev/vg1/rootlv | grep -i -A1 “superblock backup”
283. Find out list of actual devices associated with a logical volume using lvs command?

# lvs -o +segtype,devices
# vgdisplay -v <vgname>
# grep device /etc/lvm/archive/<name>.vg

284. How to scan bus so that all newly added devices/luns would come up?

# echo “- – -” > /sys/class/scsi_host/host<ID>/scan 

285. Command to check all (active/inactive) network interfaces in redhat linux?

# ifconfig -a 
# ip add
# cat /proc/net/dev

286. How do you change the network speed of an interface to 100Mbps with auto-negotiation off and duplex in full mode(example for interface eth0)?

# ethtool -s eth0 speed 100 autoneg off duplex full 
To make this changes persistent need to add the below line to /etc/sysconfig/network-scripts/ifcfg-eth0 file:
ETHTOOL_OPTS=”speed 100 autoneg off duplex full”

287. How do you check the network routing table using commands?

# route -n
# netstat -nr

288. How do you backup and restore iptables (configurations)?

# iptables-save > /tmp/iptables.out
# iptables-restore < /tmp/iptables.out

289. Please explain the checking for Rootkit infections in Linux?

A Rootkit is an advanced form of malware that can yield a range of security issues and in many cases go undetected by average antivirus programs. Hence, advanced anti-spyware tools need to be used for checking Rootkit infections in Linux. One such is the rkhunter.

A few other notable security tools available for checking rootkit infections in Linux are:
LMD (Linux Malware Detect)

290. What is the difference between command ‘ping’ and ‘ping6’?

Both the commands are same and used for the same purpose except that the fact that ping6 is used with ipv6 IP address.

291. You want to search for all the *.tar files in your Home directory and wants to delete all at once. How will you do it?

# find /home/ -name '*.tar' | xargs rm -rf

292. How do Enable / Disable Ethernet Device?

Open and Edit this file #vi /etc/sysconfig/network-scripts/devicename
For enable ONBOOT = yes
For disable ONBOOT =no

292. Check if any user is using the file system?

Check to the what users are currently using the file system:
# fuser -cu /dev/hdc1

293. What are Zombie process in UNIX and how to find them ?

Zombie process is a process whose execution is completed but have not been removed from the process table.
When a program forks and the child finishes before the parent , kernel has some of the child information .
In case parent needs to check for child's exit status - parent calls 'wait()'. Child is said to be a zombie process in the duration child terminating and the parent calling 'wait()'.

# ps aux | grep -w Z

294. How to sort a text file in linux?

The sort command found in linux to arrange the records of a file in a particular order.
By default, the sort command sorts file assuming the contents are ASCII. Using options in sort command, it can also be used to sort numerically.

sorts the contents of a text file, line by line.

standard command line program that prints the lines of its input or concatenation of all files listed in its argument list in sorted order.

It supports sorting alphabetically, in reverse order, by number, by month and can also remove duplicates.

sort by items not at the beginning of the line, ignore case sensitivity and return whether a file is sorted or not. 

By default, the entire input is taken as sort key. Blank space is the default field separator.

295. How will you restrict IP so that the restricted IP’s may not use the FTP Server?

Block suspicious IP by integrating tcp_wrapper. Need to enable the parameter “tcp_wrapper=YES” in the configuration file at ‘/etc/vsftpd.conf’. And then add the suspicious IP in the ‘host.deny’ file at location ‘/etc/host.deny’.

295. Block IP Address, how to?

Open ‘/etc/hosts.deny’ file and add ip addres.
# vi /etc/hosts.deny

296. Q:23 How  to find WWN numbers of HBA cards in Linux Server ?

Method 1
To find the HBA cards installed on your system use :
# lspci -nn | grep -i hba

To check the available HBA ports :
# ls -l /sys/class/fc_host

To find the state of HBA ports (online/offline) :
# more /sys/class/fc_host/host?/port_state

To find the WWN numbers of the above ports :
# more /sys/class/fc_host/host?/port_name

Method 2 : Using systool
To check the available HBA ports :
# systool -c fc_host

To find the WWNs for the HBA ports :
# systool -c fc_host -v | grep port_name

To check the state of the HBA ports (online/offline) :
# systool -c fc_host -v | grep port_state

297. How canyou check BIOS settings from the command line?

# dmidecode | more
# Biosdecode | more
# Hwinfo | more

298. Can we think of systemd over init system?

Systemd is the first process of the Linux system and very well designed process in compare with init.
Systemd is multithreaded and faster than init. Systemd is standard processes to control programs need to be run during Linux boot. It was conceived from the top, not just to fix the bugs, but to be a correct implementation of all the base system services. A systemd, may refer to all packages, utilities and the
libraries around the daemon. It was designed to overcome all the shortcomings of init. It is itself a background process which is designed to start the processes in parallel, and thus reducing the boot time and computational overheading.

 It has a lot of other features as compared to init.
Systemd support multiple useful commands with unified command-line interfaces
Systemd makes the boot process much simpler
Systemd support backward compatibility
Systemd supports SELinux integration
Systemd is an incredibly fast service

299. What are MAJOR and MINOR numbers of special files?

Major and minor numbers are associated with the device special files in the /dev directory and are used by the operating system to determine the actual driver and device to be accessed by the user-level request for the special device file.

Special files for char drivers are identified by a “c” in the first column of the output of ls –l and the two numbers (separated by a comma) in the device file entries before the date of last modification are the major device number and minor device number for the particular device.
For example,
Cd /dev
Ls –l

300. What is the ctrl+D error?

ctrl+D error is one of the common errors occur when the root user tries to make any Permanent entry in fstab file & by mistake changes the path location of mounted file systems in os, it gives error while rebooting the system and fails to load.

fstab is a system configuration file on the Linux operating system that contains information about major filesystems. This file is located in /etc directory and can be viewed like “cat /etc/fstab”.

We have set steps to recovery system from ctrl+D error.
1. Boot system using bootable CV/DVD of Linux of the current version installed
2. Read ctrl+D error for the exact issue
3. Connect using Root User and it will connect you in single-user mode
4. Access /etc/fstab file and make required changes 
5. Try normal system reboot

                                                                                           MENU         PREVIOUS

How do you make/grant complete access on files?

251. How do you make/grant complete access (rwx) on files created for a user and deny any level of access to others including group?

Define the umask value for the required user to achive the same. This can be done by editing .bash_profile file.

For example, if we need to define this for a user “testuser” then we need to edit this file “/home/testuser/.bash_profile” and define umask as given below (assuming that the default home directory location is not changed):
umask 0077
Save and exit the file.
Next time this user logs in, files/directories would get exclusive permissions only for this user as masked by umask parameter.
For root user the umask is defined in “/etc/init.d/functions” file. Otherwise, in /etc/profile (login shell) or /etc/bashrc (non-login shell) file.

252. What does the umask value of 0022 indicates for a root user?

Before understanding this, one must understand the numerical values being used to represent permission bits in Unix environment. It is as shown below:
r – “read” permission – numerical equivalent value “4”
w – “write” permission – numerical equivalent value “2”
x – “execute” permission – numerical equivalent value “1”
s – “special” permission bit – numerical equivalent “4” for SUID (SetUserID), “2” for SGID(SetGroupID “1” for Sticky-bit.
u – “user”
g – “group”
o – “others”

Set/Unset Permissions: Using chmod command. Say for example you wish to set only “read & write (rw)” permission for owner, no permissions for group and others then this could be done like below:
$chmod 600 <filename> OR $chmod u+rw,go-rwx <filename>

Now, lets check what does 0022 umask value indicates:
0 – Indicates special character bit, not masked.
0 – Indicates mask nothing, all permission bits are set for “Owner”.
2 – Indicates mask 2 for “Group” (for files it is “x4x” meaning both read & write bits are set likewise for directories it is “x5x” meaning both read & execute bits are set)
2 – Indicates mask 2 for others ( as explained above)
Saying so, when a root user creates a file/directory this umask bit would be used to set the effective permissions. For a file it would be (666-022=644), rw-,r–,r– (read&write,read,read) respectively for user, group and others (ugo). However, when a directory is created it would be (777-022=755) rwx,r-x,r-x for ugo. Same way the default umask value for other users is 0002.

253. How do you find out all the packages installed on a RHEL system(server)?

# rpm -qa
# yum list installed
# repoquery -a --installed
# yumdb search from_repo base

# yum install yum-utils will create /var/log/yum.log file with date and time of all packages installed.

254. Different ways that can be used to verify that a package got installed successfully via yum:?

– Immediately after running yum command, check exit status, if it shows “0” (numeral) then command executed successfully.
# echo $?

– Run rpm -qa and test.
# rpm -qa | grep <pkg_name>

– Verify with rpm command:
# rpm --version <pkg_name>

– Check the yum log to see the successful log entry about the same package.
# grep <pkg_name> /var/log/yum.log

useful commands to verify that a package got installed successfully,
# yum list installed | grep <pkg_name>
# yum info <pkg_name>
# yum info <pkg_name> | grep Repo | awk '{ print $3 }'
# yum list installed <pkg_name> >/dev/null ; echo $?

255. How to view the installed date of a package?

# rpm -q <pkg_name> -last
# rpm -q --last <pkg_name>
# rpm -qi <pkg_name> | grep "Install Date"

Check in /var/log/yum.log file (provided the package is installed by yum-utils)
# grep <pkg_name> /var/log/yum.log

256. If for some reasons, a binary file gets corrupted or missing from the system, then how could this be recovered with minimal downtime?

1. Try to copy the missing binary (executable) file from a similar working system using scp command.
2. Try to extract this file from respective package and move it to the system.

For example if the binary command file /sbin/ifconfig is missing or corrupted, hence, unable to run this command. So, we’d need to extract this from package and install it.

– Identify which package this command belongs to.

– On a working system, run the command ‘rpm -qf /sbin/ifconfig’. This would tell which package has installed this executable file:
# rpm -qf /sbin/ifconfig

– Mount an iso which holds this package and then run “rpm2cpio” command with “cpio” to extract required file.

– Check if the required file is available in the package before extracting it.
# rpm2cpio /media/Packages/net-tools-1.60-110.el6_2.x86_64.rpm |cpio –extract –list –verbose “*ifconfig”
-rwxr-xr-x 1 root root 69440 Apr 26 2012 ./sbin/ifconfig
1542 blocks

– Now, we know that this binary is available with this package, so we’d need to extract this file. Create a directory where to extract.
# rpm2cpio /media/Packages/net-tools-1.60-110.el6_2.x86_64.rpm |cpio –extract –make-directories –verbose “*ifconfig”
1542 blocks

– The binary would be found under “sbin” directory within current directory.
# tree
└── sbin
└── ifconfig
1 directory, 1 file

– Later, move this binary file to /sbin folder and make sure proper permissions are set as required.

257. How to run file system check on a logical volume in rescue mode?

– Boot into rescue mode (“linux rescue nomount”)
– Don’t mount any file systems, so “Skip” mounting.
– First make the logical volumes available by running these commands:
– lvm pvscan
– lvm vgscan
– lvm lvscan
– lvm lvchange -ay
– Next, run the file system check on the respective lvm.
– #e2fsck -fy /dev/vgname/lvname

258.  How to verify if a filesystem state is marked as clean?

# dumpe2fs -h /dev/sda1 | grep -i state
dumpe2fs 1.41.12 (17-May-2010)
Filesystem state: clean

# tune2fs -l /dev/sda1 | grep -i state
Filesystem state: clean

259.  Different fields in /etc/fstab.

DeviceName MountPoint FilesystemType MountOptions DumpFrequency FsckCheckOrder

260. How do you skip the initial fsck(file system check) on a file system while booting up?

Edit /etc/fstab and make the last column of the respective file system as 0 (number). This would skip the file system check process.

261. How to list all the files with SUID (Set User ID) bit set under the top level root directory and ignore any errors/warnings in the process, and list the output in long list format?

# find / -type f -perm -4000 2>/dev/null | xargs ls -l

262. How to list all the files/folders with SUID/SGID/Sticky Bit (Set Group ID) bit set under the top level root directory and ignore any errors/warnings in the process, and list the output in long list format?

# find / -type f -perm /7000 2>/dev/null | xargs ls -l

263. How to search for all files with extension “*.log” in the current working directory and find out total disk space consumed and skip such files under any sub-directories?

There are situations wherein an admin would required to find out total disk space consumed by those files such as “*.log” or “*.dat” etc., so one could use this command:
# find . -maxdepth 1 -name '*.log' | xargs ls -l | awk '{ TOTAL += $5} END { print TOTAL }'

# find . -maxdepth 1 -name '*.log' -type f -exec du -bc {} + | grep total | cut -f1

If there are smaller files then running the ‘find’ command or ‘du’ command would work, however, if there are bigger files then one may come across error “argument is too long”, so need to use “xargs” to parse output to avoid such errors.

# find . -maxdepth 1 -name '*.dat' | xargs ls -l | awk '{ TOTAL += $5} END { print TOTAL }'

264. I’ve installed the latest kernel on the system successfully, however, my server still boots from the old kernel. How do you make the system to boot from the newly installed kernel?

– Verify if the new kernel packages are installed successfully.
– Verify if the kernel stanza is added in grub.conf file.
– Make the new kernel as the default kernel to boot in grub.conf file. Either move the kernel stanza to be the first or change “default” entry according to the kernel stanza to boot.

265. Explain briefly the Grub in Linux Server?

Boot Loader is a package that loads operating system to memory during boot. Windows comes up with its own boot loader whereas Linux gives you to select boot loader as per your environment and requirement.

GNU GRUB or GRUB (Grand Unified Bootloader) is a type of boot loader package that supports multiple operating systems. It allows feasibility of selecting the required OS during boot. GNU GRUB gives the option to select the operating system to load during boot. GNU GRUB is an advanced level of legacy GRUB.
Unlimited number of boot entries supported
Dynamically configurable, run-time changes can be made during boot
Easy to install or execute from any device
It can be helpful in loading the operating system from the network or decompressing during boot
It also supports Windows and DOS
Only CLI (Command Line Interface) is available
Installation and configuration steps have a slight difference on the basis of OS distribution used

266. How to reinstall GRUB loader from rescue mode under GRUB loader corruption?

when there is a GRUB loader corruption,
1. The GRUB menu is not shown when booting the server
2. Check the header of the booting diskIf the GRUB loader is corrupted
# file -s /dev/sda
the key point is that the first output is missing ‘code offset 0x48‘, which is a indicator of GRUB Stage 1 code.

Reinstalling GRUB loader,
Boot the server into rescue mode, and mount the filesystem automatically
The / partition would be mounted under /mnt/sysimage automatically. If not, mount it manually
Mount the /boot partition 
Re-install the GRUB loader
Reboot the server 

267. Explain nfs hard and soft mount?

Hard Mount : After restarting the server keep on search nfs mount partition until found the device, if the device not found server not will not boot,.
Soft mount: if device not found it will skip

268. How do you disable the “NetworkManager” service on runlevel 5?

# chkconfig –level 5 NetworkManager off
# chkconfig –list NetworkManager
NetworkManager 0:off 1:off 2:on 3:on 4:on 5:off 6:off
In RHEL7.x, NetworkManager is the standard and default daemon for managing network.

269. Which is the parameter that you would add to grub.conf while configuring kdump?

crashkernel=128M (for 128MB crash memory) (crashkernel=0M-2G:128M,2G-6G:256M,6G-8G:512M,8G-:768M)

270. How to find out the system hardware details such as “manufacture, product name” etc,.?

Using “dmidecode”
# dmidecode --type system |egrep -i "Manufacturer|Product Name|Serial Number|Family"
# dmidecode --type system |grep "System Information" -A 8

– To find out BIOS details :
# dmidecode --type bios |grep "BIOS Information" -A 6

Valid type keywords are:

271. Which commands are normally recommended to edit "/etc/passwd", "/etc/shadow", "/etc/group" and "/etc/gshadow" files?

vipw → To edit the user password file (/etc/passwd)
vigr  → To edit the user group file(/etc/group)
vipw -s → To edit shadow password file (/etc/shadow)
vigr -s → To edit shadow group file (/etc/gshadow)

These commands would normally lock the respective file while editing to avoid corruption. It is not a recommended practice to edit shadow file manually. 

272. How to run ‘free’ command to print output of 2 instances with 2 seconds interval and store that output in a file (skipping any errors/warnings), and run this in background?

# free -s 2 -c 2 1> /tmp/free.out 2> /dev/null &
# cat /tmp/free.out

273.  How to find out when was the last time a service got restarted?

To find when the service last started you can use:
# systemctl show <service_name>
# systemctl status sshd | grep "Started"
# systemctl show sshd | grep ActiveEnterTimestamp
# journalctl --unit=sshd | grep Started

274. how to check service session details for sshd?

# journalctl | grep sshd

275. Which command is used to count the number of characters in a file and expain wc command?

# wc -m <file_name>

The wc (word count) command is used to find out the count of number of characters in a file. The wc command can also be used to find out the newline count , byte and character count in files Specified by file arguments.

The syntax of the wc command is of the form,
wc [options] filename

The following are the options and usage provided by the command,
wc -l : prints the number of lines in a file.
wc -w : prints the number of words in a file.
wc -c : prints the number of bytes in a file.
wc -m : prints the number of count of characters in a file.
wc -L : prints only the length of the longest line in a file.

                                                                                           MENU         PREVIOUS | NEXT

Explain the usage of curl command in Linux?

226. Explain the usage of curl command in Linux ?

In Linux, Curl command is a tool to transfer data from or to a server. In Linux, curl command is used to test an application's endpoint or connectivity to an upstream service endpoint. It is used to determine if the application can reach another service, like a database, or to check if the service is up and running . This  command doesn’t require any user interaction.

$ curl -I -s application:5000

This example with an exception shows that the application can't reach server. Options used In the above command,
-I option -> shows the header information
-s option -> silences the response body.

Curl command with -O option is  used to download the file :
Usage :
curl -O #Save the file as myfile.tar.gz

227. Explain how to enable curl on Ubuntu LAMP stack?

To enable curl on Ubuntu, first, install libcurl, once done use following command /etc/init .d /apache2 restart or service apache2 restart.

228. How to get a list of currently running processes and resource utilization in Linux?

Top is the command used to get the list of running processes and resource utilization (RAM or CPU usage). It gives  all the information about each process running on the host :
Process ID (PID)
Owner of the process(USER)
Priority of process(PR)
Percentage of CPU (%CPU)
Percentage of memory
Total CPU time spends on the process.
Command used to start a process.

Most commonly used options with the top  command are below –
top -u -> Process by a user.
top – i -> exclude idle tasks
top -p -> Show a particular process

229. What is the process in a Linux context?

A process is a running program. Processes can be started from the GUI or the command line. Processes can also start other processes. Whenever a process runs, Linux keeps track of it through a process ID (PID). After booting, the first process is an initialization process called init. It is given a PID of 1. From that point on, each new process gets the next available PID.

A process can only be created by another process. We refer to the creating process as the parent and the created process as the child. The parent process spawns one or more child processes. The spawning of a process can be accomplished in one of several ways. Each requires a system call (function call) to the Linux kernel. These function calls are fork(), vfork(), clone(), wait(), and exec().

230. What are Regular Expressions(regex)? What is the meaning of *,+,? In regular expression?

A regular expression (regex) is a string that expresses a pattern used to match against other strings. The pattern will either match some portion of another string or not. There is a list of predefined metacharacters used in a regex.
1. * Used to match the preceding character if it appears 0 or more times
2. +Used to match the preceding character if it appears 1 or more times
3. ? Used to match the preceding character if it appears 0 or 1 time

231. Explain list of daemon responsible for event tracking in Linux system & signals given to the syslogd?

syslogd daemon process facilitates the event tracking in a Linux system and logs useful information or future analysis. syslogd provides two system utilities, one for logging and other for the kernel messages. syslogd mainly reacts to the set of signals given by users.

Some of the signals given to syslogd:

SIGHUP: This signal instructs syslogd to perform a re-initialization step. All open files are then closed, the configuration file (default is /etc/syslog.conf) will be reread and the syslog facility will be started again.

SIGTERM: syslogd will die.

SIGINT, SIGQUIT: If debugging is enabled these are then ignored, otherwise syslogd will die.

SIGUSR1: Switch the debugging on/off. This option can only be used if the syslogd is started with the - d debug option.

SIGCHLD: Wait for Childs if some were born, because of the waiting messages.

232. How do you make a file copied to a new user account automatically upon user account creation?

Store the file in /etc/skel directory.

233. Explain about /etc/skel directory?

The /etc/skel directory contains files and directories that are automatically copied over to a new user's home directory when such user is created by the useradd program.

/etc/skel allows a system administrator to create a default home directory for all new users on a computer or network and thus to make certain that all users begin with the same settings or environment.

Several user configuration files are placed in /etc/skel by default when the operating system is installed. Typically they might include .bash_profile, .bashrc, .bash_logout, dircolors, .inputrc and .vimrc. The dots preceding the names of these files indicate that they are hidden files, i.e., files that are not normally visible in order to avoid visual clutter and help reduce the chances of accidental damage.

234. How do you make a new user to reset his password upon his first login?

# chage -l <username>

235. Which files stores the user min UID, max UID, password expiration settings, password encryption method being used etc.,?


236. Create users home directory in /home1 directory instead of default /home directory. This gets applicable to any new users who gets created i.e the home directory of that user should be /home1/<UserName>/ ?

Edit /etc/default/useradd
Change the line : HOME=/home1
Save the changes and exit. After this any new users home directory would be under /home1

To check the useradd defaults using the command,
# useradd -D
# cat /etc/default/useradd

After this you can add users with the command “useradd <UserName>”. This would create the users home directory with the name of the user under the specified HOME directory as defined in /etc/default/useradd.

237. What are the possible causes when an user failed to login into a Linux system (physical/remote console); despite providing proper credentials?

Here are the possible reasons why an user fails to login into console:

1. Account Locked.
When user tries to login via GUI receive an error “authentication failure” after entering password and it goes back to the user list prompt.
In CLI mode, after entering user password, it would fail with an error “incorrect password”. However, if user tries “su” from root account, access would get granted.

2. Account Expired.
When account expired, an error notifying about the same would be shown up.

3. Shell Disabled
After entering password in GUI, system shows a progress, however, could come back the login prompt. When this user attempts login via CLI, would receive an error “This account is currently not available”. For example, do disable shell of an user “test” : #usermod -s /sbin/nologin test (this only locks only terminal login, however, GUI login would work)

4. Only Non-root Users Failed To Login.
If all non-root users are unable to login via GUI/CLI, however, root could login then this could be because of the file “/etc/nologin” presence on the system.

5. Only Non-root Users Failed To Login in CLI.
If all non-root users are unable to login via CLI, however, can login via GUI then it would be because of /tmp space limitations. Need to check if /tmp is configured and mounted separately and check free space under /tmp.

6. User login failed from GUI or from text console, however, could do su.
If an user fails to login from GUI/Console, however, could login from other user accounts by running ‘su’ then it could be due to pam restrictions. One could use “pam_access” module to restrict login. Need to add :
account required pam
to files : /etc/pam.d/login & /etc/pam.d/gdm-*
After this add ” – : <UserName> : ALL ” to /etc/security/access.conf file. For example to limit user “test”, we could add below line to access.conf file;
– : test : ALL
{{ there would an error “permission denied” in GUI when user is restricted to login via pam}}

7. Only root user login failed from console, however, works in GUI.
This could be because of no terminals available or defined in /etc/securetty file.
If an user failed to login remotely via ssh then the reasons could be different. Here are the reasons:

8. User Restricted.
If “AllowUsers” parameter is configured in /etc/ssh/sshd_config then need to add required user to this list to get access.

9. Max Logins Set.
If “maxlogins” parameter is set in /etc/security/limits.conf then user would be allowed up to the parameter set and further connections would be denied. There could be “maxsyslogins” configured as well to limit concurrent access to a system.

238. What does ‘ivh’ represents in rpm -ivh <PackageName> command?

i – install
v – verbose mode
h – hash mode where it would print ## characters as the installation progresses

239. What is the difference between rpm -F <PackageName> and rpm -U <PackageName>?

rpm -F = Basically freshens a package which in turn upgrades an existing package, otherwise doesn’t install it if an earlier version not found.
rpm -U = Upgrades an existing package if exists otherwise install it.

240. How to find to which package the “ls” commands belongs to (to find out package responsible for this command)?

# rpm -qf /bin/ls #this would tell about the package to which this command (binary file) belongs to if installed by that package.

241. How to check what file systems are mounted and their read/write status?

# cat /etc/mtab
# cat /proc/mounts
# mount

# df -Th #this would not tell the read/write status

242. How do you remount a file system read only on the fly?

# mount -o remount,ro <Mountpoint>
To make a file system gets mounted read only during boot, need to edit fstab.

243. Command used to convert ext2 file system into ext3.

# tune2fs -j <device or file system name>

244. How to set “rw” permissions on file for a user and disable for other users except root user (exclusive permissions)?

Use “setfacl -m u:<UserName>:<PermissionBits> <File/FolderPath>
# setfacl -m u:<UserName>:rw /testfile
To read use “getfacl” command: #getfacl /testfile

245. How to find out the shadow password encryption method being used in Linux? How could this be changed (example : from md5 to sha512)?

Check in /etc/login.defs
grep -i crypt /etc/login.defs
# Use SHA512 to encrypt password.

Check using “authconfig” command,
# authconfig --test | grep hashing
password hashing algorithm is sha512

Check the password beginning character in the second field of /etc/shadow file:
If it begins with = $6 > indicates sha512
$5 > sha256
$1 > md5

To Change Password Encryption Method to sha512:
# authconfig –passalgo=sha512 –update 

246. How to manually add user without using “useradd/adduser” or “system-config-user” utilities?

Create required directory under /home (default home directory for all local users) and set permissions.
# mkdir /home/manualusr
# chmod 700 /home/manualusr
ls -ld /home/manualusr
drwx------. 2 root root 6 Jun 28 06:57 /home/manualusr

Edit /etc/passwd file to manually set required parameters for the new user “manualusr”:
# vipw (this command would block multiple edits of /etc/passwd file)
manualusr:x:2000:2000:local user:/home/manualusr:/bin/bash
 use the command 'vipw -s' to modify /etc/shadow 
# grep manualusr /etc/passwd
manualusr:x:1002:1002:local user:/home/manualusr:/bin/bash
 use the command 'vigr -s' to modify /etc/gshadow 

Create required group by editing /etc/group file using command ‘vigr’:

Next step is to create the local profile files for the new user by copying from /etc/skel.
# cp -arv /etc/skel/. /home/manualusr/

Change permissions of all the files under /home/manualusr to be owned by new user:
#chown -R manualusr:manualusr /home/manualusr

Try logging in as new manualusr and test.

For user mail requirement, need to create a proper file under /var/spool/mail (default mail box location) with username and permissions:
# cd /var/spool/mail
# touch manualusr
# chown manualusr:mail manualusr
# chmod 660 manualusr

247. Which command to be used to check the shell being used?

# echo $SHELL
# echo $0

2) How to check if the syslog service is running?
# /etc/init.d/rsyslog status OR service rsyslog status 

# systemctl status rsyslog.service (in RHEL7.x).

248. By default log files are set to get rotated on weekly basis, how to make this gets rotated on monthly basis?

Edit /etc/logrotate.conf and change below lines
# rotate log files monthly

Save changes and if you want to rotate the log files immediately then run the command:
# logrotate -f /etc/logrotate.conf

249. What does /var/log/wtmp and /var/log/btmp files indicates and what do they store?

These files are used to store user login/logout details since from the date of creation.
The user login, logout, terminal type etc are stored in /var/log/wtmp and this is not a user-readable file, so “last” command reads data from this file (or the file designated by the -f flag).

All un-successful(bad) login attempts are recorded in /var/log/btmp which could be displayed using the command “lastb”. All these login/logout events would also get recorded in /var/log/secure file (this file usually stores all authentication/authorization events).

Like-wise, there is /var/log/lastlog which records most previous successful login event of users. In earlier RHEL versions (RHEL 5.x) there used to be a file /var/log/faillog to hold failed login events which had become obsolete since RHEL6.1 and is no longer available.

250. How to find out the configuration files installed by a package (take into consideration of the “coreutils” package)?

# rpm -qc coreutils

To list out only the document files installed by coreutils package:-
# rpm -qd coreutils

To list out all the files installed by this package:-
# rpm -ql coreutils
# rpm -q --filesbypkg coreutils

To list out dependencies :-
# rpm -qR coreutils

To list out packages which require this package:-
# rpm -q --whatrequires coreutils

To find out more information of this package:-
#rpm -qi coreutils

To find out any scripts executed by this package:-
#rpm -q -scripts coreutils

                                                                                           MENU         PREVIOUS | NEXT

How to create user and group in Linux?

201. How to create user and group in Linux?

To create the user and also create the user's home directory to match the username,
# useradd -m <username>

Issue the command to set password,
# passwd <username>

To create a group
# groupadd <groupname>

To add our new user
# usermod -a -G <groupname> <username>

To know which users are already a member of a group
# grep <groupname> /etc/group

202. Mention the ways to debug the kernel code?

We can debug a kernel code simply with the command printks. Else we can also use KDB and kernel probes. Other methods are:

UML (User Mode Linux) – It is the best method for debugging but it does not support device drivers.

KGDB (Kernel GNU Debugger)

kdump tools which are used to dump kernel cores.

203. How would you swap the stdout and stderr of a command?

$ command 3>&2 2>&1 1>&3
To swap stdout and stderr of a command, a third file descriptor is being created (in this case 3), which is assigned to the same target that stderr is pointed to (referenced by &2). Then stderr is pointed to the same target stdout is pointed to (&1). Finally, stdout is pointed back to where the newly created file descriptor is pointed (which is the same target stderr originally pointed to.)

204. How would you write a shell script that prints all the additional arguments passed to it in reverse order?

for (( i = ${#}; i > 0; i-- )); do
        echo ${!i}
The arguments are available as $<n>, where n is the position of the argument. For example, $0 would give the name of the script, $1 would give the first additional argument, $2 the second, and so on. The total number of additional arguments is found in $#.
A loop that starts at $# and ends at 1 can be used to print each additional argument in reverse order.

205. What is the correct path for the grub’s configuration file?

The configuration file (/boot/grub/grub.conf OR /etc/grub2/grub.conf), which is used to create the list of operating systems to boot in GRUB's menu interface, essentially allows the user to select a pre-set group of commands to execute.

206. How to add binary to $PATH variable?

$ export PATH=$PATH:/path/to/the/binary/file

207. Why setup password less ssh login?

To improve system security even further, most of the organizations turned to use key based authentications instead of Password-based authentication. We can enforce the key-based authentication by disabling the standard password authentication, which involves a public key private key pair. The public key is added in the server configuration file while the private key is kept confidential on the client-side.

208. What is Key-based authentication? Explain.

One of the ways to achieve the security is to use Key-based authentication. To use this type of authentication, we have to disable the password-based authentication. So, there is a procedure to set up this authentication which is as follows:

We have to get the SSH key pair using below command:
$ ssh-keygen -t rsa
It will generate the public/private rsa key pair.

Enter file where you want to save this generated key (/home/username/.ssh/id_rsa):
It will prompt you for the same location, i.e. ~/.ssh/id_rsa for the key pair. Press enter if you want to confirm the same location. Else, if you want to provide any other location, enter that and confirm the same.

Now copy ~/.ssh/ into the ~/.ssh/authorized_keys that will be located where you have to connect.
Now, we have to provide the permissions to the file as per below command:
$ chmod 600 ~/.ssh/authorized_keys

Now try to sshthe machine you want to connect, and you will see that you are able to login to the machine without a password.

If you are confirmed that key-based authentication is working fine, disable the password-based authentication.
Go to the path /etc/ ssh/sshd_config
set the following property as no.
PasswordAuthentication no

209. Explain the logical steps to increase the size of LVM partition?

Some logical steps need to be followed to increase the size of LVM partition. 

These are as follows:

Run the command as per given format:
lvextend -L +500M /dev/<Name of the LVM Partition>
Here, we are extending the size of LVM partition by 500MB.

resize2fs /dev/<Name of the LVM Partition>
You can check the size of partition using ‘df -h’ command

210. Which utility is to create a partition from the raw disk?

To create the partition from the raw disk, you have to use fdisk utility. Below are the steps to create a partition from the raw disk:

Step 1: Run the below command:
fdisk  /dev/hd* (IDE) or /dev/sd* (SCSI)

Step 2: Type n to create a new partition

Step 3: Now partition has been created, and we have to write the changes to the partition table, so type w command to write the changes.

211. If a volume group already exists and we need to extend the volume group to some extent. How will you achieve this?

Linux provide the facility to increase the size of a volume group even if it already exists. For this, we need to run a command.

First of all, we have to create a physical volume (/dev/sda1)
Size of the physical volume should be the size you want the size of the logical volume.

Now, run the below command:
vgextend VG1 /dev/sda1

Here VG1 is the name of the volume group.

212. How we can enable ACL?

ACL is an acronym for Access Control List which is used to provide flexible permission mechanism for the file systems. We can enable ACL by following methods:
Type the code in the shell: /etc/fstab with a label=/home/ext3 acl

Now we have to remount this file system with the ACL partition: mount –t ext3 –o acl /dev/sda3/home

213. What are the possible methods to deploy a module inside a kernel?

To check the modules that are already installed inside the kernel, you have to run this code: lsmod. When the module has been built, now it is the stage to load it in the kernel. You can load it by the command “Insmod” or “Modprobe”.

Syntax: Insmod[filename][module-options] //module-options are command line arguments to kernel objects.

Insmod always accepts only one filename at a time.'

Modprobe offers more features than Insmod like it can decide which module is to be loaded and is aware of the module dependencies.

214. Mention the case when we use “user virtual address” instead of “kernel virtual address”?

When we run a program in userspace then we use “user virtual address” as we do not have any access to kernel virtual memory address. Normally when we are running our program in kernel mode then we use kernel address but in case we have to run our program in kernel mode and that program needs an interaction with a userspace then we will use “user virtual address” and be careful to first translate it to user virtual address.

215. How would you write a shell script and ensure that only one instance of the script may run for every user? Strong atomicity is not required.

In Bash:
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "Already running!"
    exit 1
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${LOCKFILE}

Start by determining a name for the lock file. In this case, the lock file is generated by suffixing a common name with the username of the current user.

Then, check if the lock file exists and if the PID contained within the lock file is running. If it is, exit with a message.

Create a trap to remove the lock file on a clean exit, or unclean exits (any exit with the signal INT or TERM).

Finally, if the script has not exited yet, create the lock file, and store the PID of the current process ($$) in it.

216. What are terminal multiplexers? What are some of their key features? What are some of the more popular ones currently available?

Terminal multiplexers enable several terminals to be created and controlled from a single screen or from a single remote session. The terminals and sessions can be detached and left running, even with the user logging off.

Two of the more common ones available today are GNU Screen and tmux.

Screen enables you to connect to multiple remote servers without needing to open multiple terminal shells. Work can be preserved and a session detached, for example, to wait for the output of a long-running command. On subsequent reconnection, users can reattach to existing sessions or run new sessions. Sessions can also be shared among different users, which may be useful in audit or training scenarios.

Both Screen and tmux support split-screen functionality (to be more precise, tmux supports this and Screen supports it via a plugin). This allows, for example, runningtail on a service’s log file in one part of the screen, and editing the configuration of that service, and restarting it if necessary, in another.

217. What is a Linux null (or Blackhole) route? How can it be used to mitigate unwanted incoming connections?

A Linux null (or Blackhole) route is a type of routing table entry which, upon matching a packet, discards it without forwarding the packet any further or sending any ICMP.

Using this technique, it is possible to block an IP (or range of IP addresses) by running a simple command. For example, blocking can simply be done with the following command:
# ip route add blackhole 

218. How to add a null route?

In our example we are receiving unwanted SSH login attempts from
# netstat -na | grep :22
 tcp 0 0* LISTEN

To add the null route we will use the ip command
# ip route add blackhole

To verify the route is in place will will use ip route show
# ip route show
 default via dev eth0 metric 100

After a little while the established ssh connections will time out and all subsequent connections from the blocked ip will receive the following.
 baduser@attacker:~$ ssh
 ssh: connect to host port 22: No route to host

219. How to remove a null route?

After the attack has subsided or in case you add the wrong ip you may want to remove the blackhole route. To do so we will use the ip command again.
# ip route del
# ip route show
 default via dev eth0 metric 100

220. what are the contents of /usr/local?

/usr/local comprises files installed locally. This is an important directory in the environment where files have to keep in a network. Typically, files locally-installed go to /usr/local/lib, /usr/local/bin, etc.). Another application of directory is its usage for software packages, or software not shipped formally with the distribution.

221. Name some major Stateless Linux Server’s features?

Some of the major features of Stateless Linux Server are as follow:
1. It stores every system’s prototype.
2. It stores the home directories.
3. It stores the snapshot was taken. 
4. It uses LDAP that holds information concerning which snapshot run on which system. 

222. How to Calculate Load Average in Linux?

The load average is calculated through the decimal number in Linux, starting from 0.00. The load average suggests the number of programs waiting for their turn to be run on the system.  The status would be one-minute average, five-minute average, and fifteen minutes average.
223. how to color the Git console?

To color the Git console, you can use the command git config—global color.ui auto. In the command, the color.ui variable sets the default value for a variable such as color.diff and color.grep.

224. What is the steps if the remote server is not connecting?

Ping remote server IP. (to check  alive or not)
Make sure remote server sshd service enabled
If everything is ok, login remote server ILO, open the remote console and check the status

225. Tell me the difference between ext3 and ext2 file systems?

Some of the major differences between the ext3 and ext2 file systems are as follow:

The ext3 file system is a higher form of the ext2 file system.

After an unexpected system crash or power failure (a system shutdown), ext2 file system should be analyzed for constancy through the e2fsck program. It is a time-taking procedure and through this process, information on the volumes is inaccessible.

ext3 supports journaling, it is one of the major differences among both ext2 and ext3.

The journaling offered by the ext3 file system indicates that this type of file system check is not essential to perform after an unclean system shutdown. A consistency check only occurs in rare hardware failure while using ext3, for example, hard drive failures. after an unclean system shutdown, the recovering time of an ext3 file system not based on the file system size or the number of files. But it is based on the journal size used to preserve constancy. The default size of the journal takes a couple of seconds to recover, based on the hardware speed.

                                                                                           MENU         PREVIOUS | NEXT

What is RPM?

176. What is RPM and How to check dependencies of RPM Package on before Installing ?

RPM is a Package Manager for popular distribution such as Red Hat, Suse and many others. It is a powerful command line package management system for installing uninstalling, verifying, querying, and updating Linux computer software packages.

rpm -qpR {.rpm-file}
rpm -qR {package-name}

-qpR above is equivalent to --query --package --requires.

177. How can we increase disk read performance in single commands?

To see the current read performance,

$ blockdev –getra /dev/sdb

$ time dd if=/tmp/disk.iso of=/dev/null bs=256k
2549+1 records in
2549+1 records out
copied, 6,84256 seconds, 97,7 MB/s
real 0m6.845s
user 0m0.004s
sys 0m0.865s

After test,
$ blockdev –setra 1024 /dev/sdb

$ time dd if=/tmp/disk.iso of=/dev/null bs=256k
2435+1 records in
2435+1 records out
copied, 0,364251 seconds, 1,8 GB/s
real 0m0.370s
user 0m0.001s
sys 0m0.370s

178. How do i check which NFS version ?

$ rpcinfo -p localhost | grep -i nfs
$ rpm -qa | grep nfs
$ rpm -qi nfs nfs-utils

179. What is the command for extract RPM?

$ rpm2cpio

$ rpm2cpio php-5.1.4-1.esp1.x86_64.rpm | cpio -idmv

i: Restore archive
d: Create leading directories where needed
m: Retain previous file modification times when creating files
v: Verbose i.e. display progress

Verify that you have extracted an RPM file in the current directory:
$ ls

180. Assume the / partition got read only error, what steps has to be take.

$ remount –o rw,remount

181. Please let us know how to stop the ssh service from a particular node?

$ /etc/hosts.deny a sshd: ALL except Node IP

182. How to check whether the ssh is running or not on the remote host?

# nmap   -p  22    <IP address of the remote host>    (to see the ssh is running or not on remote system)

183. Step out if you are facing too many file system while login via ssh?

# lsof |wc -l #(list of open files)

# sysctl -a | grep file-max # check system capacity

# ulimit -n

Try ulimit -n -H which will show the "hard" limit for open files (-n), for example 4096. Then raise the limit to that value eg: ulimit -n 4096 before invoking your SSH tunnel.

Increase the limit by going through limits.conf file which is available in the location /etc/security/limits.conf. Now add the below content in the file "limits.conf".

soft nofile value
hard nofile value

184. What is linux library file extension?

On Linux, dynamic libraries typically have a .so (shared object) extension. One advantage of dynamic libraries is that many programs can share one copy, which saves space.

185. What is relevance of $?

It reflects the status of previous command,

1. If 0 – Success
2. If Non-Zero – Not Success

186. Which Terminal you are working in?

Find it using ‘tty’ command or who command

187. Command ifconfig is not found in my system, how to get my ip address

# ip a

188. What is ErrorDocument?

The Apache web server provides a default set of generic error pages for 404, 500, and other common Apache errors. The ErrorDocuments directive lets you specify what happens when a client asks for a nonexistent document. Specifies a file that the server sends when an error of a specific type occurs. You can also provide a text message for an error. 

Here are some examples:

ErrorDocument 403 “Sorry, you cannot access this directory”
ErrorDocument 403 /error/noindex.html
ErrorDocument 404 /cgi-bin/
ErrorDocument 401 /new_subscriber.htm

400: Bad Request
401: Unauthorized
402: Payment Required
403: Forbidden
404: Not Found
405: Method Not Allowed
406: Not Acceptable
407: Proxy Authentication Required
408: Request Timeout
409: Conflict
410: Gone
411: Length Required
412: Precondition Failed
413: Request Entity Too Large
414: Request-URI Too Long
415: Unsupported Media Type
416: Requested Range Not Satisfiable
417: Expectation Failed
500: Internal Server Error
501: Not Implemented
502: Bad Gateway
503: Service Unavailable
504: Gateway Timeout
505: HTTP Version Not Supported

189. Find SGID Files with 644 Permissions?

# find / -perm 2644

190. Specify number of maximum open files in a single login based on the amount of system RAM?

# echo “1599383” > /proc/sys/fs/file-max

This can also be done by using sysctl
sysctl command is used to change Kernel Parameters at run-time
# sysctl -w fs.file-max=1599383

Kernel Parameters can also be changed by making changes in the below file:

Append the below line in the /etc/sysctl.conf file
fs.file-max = 1599383

After making the above change run the below command for changes to reflect, loads the sysctl settings
# sysctl -p

191. Increase the local port range, by default the port range is small?

# echo “1024 65535″ > /proc/sys/net/ipv4/ip_local_port_range This can also be done using sysctl command

# sysctl -w net.ipv4.ip_local_port_range=”1024 65535”

Append the below line in the /etc/sysctl.conf file
net.ipv4.ip_local_port_range = 1024 61000

After making the above change run the below command for changes to reflect, loads the sysctl settings
# sysctl –p

192. How can an administrator know whether a user account is locked or not?

To check if the user account is locked or not just run this command in the shell:
passwd –S <username>

# passwd --status <username>

Check for the flag *LK* in the below command output which indicates that the account is locked.

Or search for the grep username in the location /etc/shadow file and it will show a symbol ‘!’ prefix to the encrypted field in the password box.

To just unlock the password type this command:
# passwd –u <username>

If there is a double exclamation mark then run this command two times:
# usermod –U <username>

193. How to lock user account or disable user account in Linux? How to check and enable?

Locking or disable user account is done for the security purpose so that unauthorized users cannot login. There are several ways in which user account can be locked or disabled. Some of them are below. 

1.Lock or disable the password using passwd command.
# usermod -L <username>
# passwd -l <username>

To check
# passwd --status <username>

To enable
# passwd –u <username>

2.To completely disable user accounts you can user the command chage -E0. For example :
# chage -E0 <username>

To check
# chage -l <username>

To enable
# chage -E YYYY-MM-DD <username>

3.Changing the shell using nologin command ( /sbin/nologin ).
so that the user do not get any login shell when he tries to login into the system.

# usermod -s /sbin/nologin <username>
check for the 7th and last field in /etc/passwd for the change of shell to /sbin/nologin.

To check
grep ^<username> /etc/passwd

To enable
# usermod -s /bin/bash <username>

194. When we execute ‘usermod‘ command in terminal, what are the files used and affected.

/etc/passwd – User account information.
/etc/shadow – Secure account information.
/etc/group – Group account information.
/etc/gshadow – Secure group account information.
/etc/login.defs – Shadow password suite configuration..

195. How to change user home directory?

check the current home directory of a user using the following command,
# grep <username> /etc/passwd

change home directory from /home/<username> to /var/www/,
# usermod -d /var/www/ <username>

196. How to set user account expiry date?

check the current account expiry status using,
# chage -l <username>

To set user account expiry date,
# usermod -e YYYY-MM-DD <username>

197. How to change password expiry to specific date?

check the current account expiry status using,
# chage -l <username>

To change password expiry to 120 days,
#  chage -M 120 <username>

To Change the password to never expire,
# chage -m 0 -M 99999 -I -1 -E -1 <username>

This will set the following,

Password expires                                        : never
Password inactive                                       : never
Account expires                                         : never
Minimum number of days between password change          : 0
Maximum number of days between password change          : 99999

198. How to change user primary group?

To check the current group for the user,
# id <username>

To set or change a user primary group,
# usermod -g <new_gid> <username>

199. How to add a new group to existing group?

#  usermod -G <gid> <username>

200. How will you figure out the author of each file?

#  ls --author -l

                                                                                           MENU         PREVIOUS | NEXT

Where does Linux store the commands executed recently?

151. Where does Linux store the commands executed recently?

The history list are stored in ~/.bash_history file.

Note that if you don't use bash, it won't be in ~/.bash_history, but ~/.<shell name>_history. 
For example, for zsh, log is in ~/.zsh_history.

152. show all of the last commands that have been recently used?

$ history

153. how to set the history limit and check the current settings?

$ export HISTSIZE=2000

Apply changes,
$ source ~/.bashrc

To check the current settings,
$ echo $HISTSIZE
$ grep HISTSIZE /etc/profile /etc/bash.bashrc ~/.profile ~/.bash_profile ~/.bash_login
154. How to add date and time to bash history?

Set HISTTIMEFORMAT to print the time stamps associated with each history entry.

Append the following line to ~/.bashrc file:
export HISTTIMEFORMAT="%h %d %H:%M:%S "

Now, when you type history, it will show something like:
113  Jun 08 16:31:06 sudo ifconfig

155. Ways to Re-run Last Executed Commands in Linux?

i. Use the Up arrow keys to retrieve a previous command. Pressing it constantly takes you through multiple commands in history.

ii. To re-execute a specific command from the history of commands,
!number #find the number using history command.
for example,
# !988

iii. Also re-execute previously used command with '!' character followed by a few of the first characters of that particular command as shown.
for example,
# !find
find / -name profile

156. What is the command to start a job that will keep on running even after closing the session?

nohup commad used to avoid a command to be terminated when you close the terminal or get disconnected.

157. How to backup or archive files in Linux using tar command?

To back up a directory, simply run the tar command  below
$ tar -cvf tarball_name.tar /path/to/directory

For example, to create an archive in tar.gz format of a file sales.txt  in /data/reports/ path execute:
$ tar -cvf sales.tar.gz  /data/reports/sales.txt

You can also archive a whole directory as shown:
$ tar -cvf repors.tar.gz  /data/reports/

158. Why you use export command?

Export command marks and exports environment variables.

159. What are the environmental variables?

They are dynamic values that affect the process of programs on a computer. They exist in every operating system and their types may vary. They can be created, edited, saved and deleted and they also give the information about the system behaviour.

160. How to find the interface IP address?

You can easily find the IP interface by running the command ifconfig interface_name or using ip command.

For example
ifconfig –a
ip addr show

161. Choose 5 Linux commands, what are your choices?

   •    rsync command

The rsync command can be used to synchronize two directories or directory trees whether they are on the same computer or on different computers but it can do so much more than that. rsync creates or updates the target directory to be identical to the source directory.
rsync -aH sourcedir targetdir
The -a option is for archive mode which preserves permissions, ownerships and symbolic (soft) links. The -H is used to preserve hard links. Note that either the source or target directories can be on a remote host.

   •    sed command

Sed command is used when you need to select specific lines of a file. Sed is short for stream editor, is one way to do this. You want to combine multiple files that all had headers or to do a bulk find and replace a file.
Insert a blank line above every line which matches "regex"
$ sed '/regex/{x;p;x;}'
Change "scarlet" or "ruby" or "puce" to "red"
$ sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g'

   •    awk command

Awk is a programming language that allows easy manipulation of structured data and the generation of formatted reports. It searches one or more files to see if they contain lines that match with the specified patterns and then perform associated actions
Print Specific Field
$ awk -F':' '{ print $1 }' /etc/group
$ date | awk '{print $2 " " $6}'

   •    lsof command

lsof is a command line utility which is used to list the information about the files that are opened by various processes. In unix, everything is a file: pipes, sockets, directories, devices, etc. So by using lsof, you can get the information about any opened files.

List processes which opened a specific file
# lsof /var/log/syslog

Lists all open files belonging to processes owned by the user
# lsof -u username

Kill all process that belongs to a particular user
# kill -9 `lsof -t -u username

List all network connections
# lsof -i

List all network files in use by a specific process
# lsof -i -a -c ssh

List processes which are listening on a particular port
# lsof -i :25

   •    grep command

Grep is a command used to search text or for a given file for lines containing a match to the given strings or words. By default, grep displays the matching lines.

Print network connection used by firefox
# netstat -pltnu | grep firefox

Print the line which contains "root" on /etc/passwd file
# cat /etc/passwd | grep root

162. How to remove blank lines from a file - sample.txt in a single command line ?

sed '/^$/d' sample.txt
Here “^” symbol represents the starting point of a line and “$” represents the end of the line. Whereas “^$” represents the empty lines, d stands for delete.

163. How to get version from multiple Linux servers using bash script?

serverlist='server_list.txt' #serverlist
servers=`cat $serverlist` #write in variable all server list
result='result.txt' #path to file with result
echo -e "Servername \t\t kernel version"> $result
for server in $servers
kernel=`ssh root@${server} "uname -r"`
echo -e "$server \t\t $kernel" >> $result

164. Explain Grep command and Regular Expressions?

“GREP” abbreviates as a “Global Regulation Expression Point”. Grep command is an expression used for filtering results or output. It is used for searching a text file for commonly used expressions. 

For instance, to list a directory and only search for files with the word 'cron', run the command:
For example,
ls | grep cron
grep “smith” passwd shadow
netstat -an | grep 8083
cat /etc/passwd | grep smith

165. What do you mean by an ext3 file system?

Ext3 file system is an upgraded version of ext2 and it also supports journaling. When an unclean shutdown is performed ext2 file system performs a check on the machine for errors which is a long process but it is not so in case of the ext3 file system.

In case of a hardware failure, an ext3 consistency check will occur without any pause. The time of the recovery of the file system is independent of the number of files. The time is dependent on the size of the journal which only takes a second which depends on the speed of the hardware.

166. How would you count every occurrence of the term “water” in all the files appearing under the current directory, and its subdirectories, recursively?

$ grep -orI water . | wc -l

To list every occurrence of the term “water” on a separate line, one must run grep -o water <path>. Adding the r flag to the command makes the search recursively process every file under the given path, and the I flag ensures that matches in binary files are ignored. In addition, the w flag can be included to match the exact term only, and ignore superstrings such as “watering”, and to make the search case-insensitive, the i flag can be added as well:

$ grep -iworI water . | wc -l
The number of lines yielded by this grep command is the number of occurrences of the desired term, which can then be counted by piping it into the wc -l command.

167. What is the issue behind getting an error “filesystem is full” while there is space available when you check it through “df” command? How will you rectify this problem?

When all the inodes are consumed then even though you have free space, you will get the error that filesystem is full. So, to check whether there is space available, we have to use the command df –i.  Sometimes, it may happen file system or storage unit contains the substantial number of small files, and each of the files takes 128 bytes of the inode structure then inode structure fills up, and we will not be able to copy any more file to the disk. So, to rectify the problem, you need to free the space in inode storage, and you will be able to save more files.

168. How can we create a local Yum repository in the location /media with the use of mounted Linux ISO image?

To create the local yum repository you have to create the files ending with extension .repo in the location /etc/yum.repos.d
Syntax: [root@localhost yum.repos.d]# cat local.repo

169. Mention the methods to check whether using Yum, the package is installed successfully or not?

There are several methods to check whether the package is installed or not. 

Method 1 –If the command is executed successfully then after running the yum command it will show ‘0’ on checking the exit status.

Method 2-You can run the rpm and –qa test.

Method 3–In the yum log, check if any entry is installed in the directory.

170. What is the advantage of executing the running processes in the background? How can you do that?

The most significant advantage of executing the running process in the background is that you can do any other task simultaneously while other processes are running in the background. So, more processes can be completed in the background while you are working on different processes. It can be achieved by adding a special character ‘&’ at the end of the command.

171. Why is “finger service” always kept disabled when not in use?

Finger Service acts as both the Web and FTP server. It is also known as Finger User Information Protocol which contains the information of the user that can be viewed by the clients. It allows a remote user to see the information about the admin such as login shell, login name and other confidential details. That is why; the finger service should be kept disabled when it’s not in use.
If it is not disabled, you have to modify and comment out the file “/etc/inetd.conf”.

172. How can we make a router with the help of Linux Computer?

You may generally come across this type of questions in Linux interview. Linux machine has the ability to turn it into a router with the help of IP Masquerade. You may have seen the servers found in commercial firewalls. IP Masquerade does the same function to one-to-many Network Address Translation servers. If the internal computers do not have the IP address then in this case, IP Masquerade can connect to the other internal computers which are connected to Linux box to access the internet.

Just follow these steps to enable IP Masquerade Linux:

Connect your PC to LAN.

This PC can be used as a default gateway for other systems for TCP/IP networking. You can use the same DNS on all other systems.

Go in the Kernel and enable IP forwarding. You can also enable IP forwarding using the command: /etc/rc.d/rc.local file on rebooting the system.

The last step is to run this command which sets up the rules to masquerade: /sbin/iptables

173. What is command grouping?

We can redirect a command from a file or to a file. It is usually done with the help of braces or parenthesis. When the command is grouped then redirection is done to the whole group.
The command is executed by the current shell when we use the braces () and in case we have to execute a command by a subshell then we use parenthesis {}.

174. Write the command to view an existing tar archive and how to extract it?

The command for viewing tar archive that is already existing: $ tar tvf archive_name.tar
The command to extract an existing tar archive: $ tar xvf archive_name.tar
The command for the creation of new tar archive: $ tar cvf archive_name.tar dirname/

174. Write the steps to make a USB bootable device.

Followings are the steps to make a USB bootable device –

write efidisk.img from RHEL 6 DVD images/ subdirectory
to USB dd if=efidisk.img of=/dev/usb (name of the usb device)

disable ping to avoid network /ICMP flood

set the following in/etc/sysctl.conf : net.ipv4.icmp_echo_ignore_all =1

Then “sysctl -p”

175. Mention the steps to create the partition form a raw disk?

In case we want to create a new partition form a raw disk, you have to use a tool known as “fdisk utility”. The steps to create a raw disk are as follows:

In case of IDE we use >>> fdisk/dev/hd and in case of SCSI we use >>> fdisk/dev/sd

Then type n for creating a new partition.

After the partition is created type ‘w’.

                                                                                           MENU         PREVIOUS | NEXT

How do you set Linux file/directory permissions?

126. How do you set Linux file/directory permissions?

To set file permissions, use the chmod command followed by the octal value or symbolic value then the file name or directory name.

For example to assign a file permissions value of 664 run
chmod 664 filename

To assign directory permissions, use the -R option to assign permissions recursively.
chmod -R 664 directory_name.

127. How to set ownership for files/directories?

To set file owner use the chown command. 
For example, 
chown user:user filename.

For a directory use the -R option to assign permissions recursively. 
For example,
chown -R user:user directory_name

128. What is swappiness in Linux?

The swappiness parameter controls the tendency of the kernel to move processes out of physical memory and onto the swap disk. Because disks are much slower than RAM, this can lead to slower response times for system and applications if processes are too aggressively moved out of memory.

Swappiness can be set to values between 0 and 100.

vm.swappiness = 0   # Swap is disabled. In earlier versions, this meant that the kernel would swap only to avoid an out of memory condition, but in later versions this is achieved by setting to 1.

vm.swappiness = 1   # Kernel version 3.5 and over, as well as kernel version 2.6.32-303 and over: Minimum amount of swapping without disabling it entirely.

vm.swappiness = 10  # This value is sometimes recommended to improve performance when sufficient memory exists in a system, this value *10* could be considered for the performance being expected. 

vm.swappiness = 60  # The default value.

vm.swappiness = 100 # The kernel will swap aggressively.

129. How to configure the swappiness parameter to improve overall performance?

The Linux kernel provides a tweakable setting that controls swappiness,
$ cat /proc/sys/vm/swappiness

For example, open /etc/sysctl.conf as root. Then, change or add this line to the file:
vm.swappiness = 10

for changing the swappiness value temporarily try this command:
$ echo 50 > /proc/sys/vm/swappiness

130. How can you append one file to another in Linux?

To append one file to another in Linux you can use command cat file2 >> file 1. The operator >> appends the output of the named file or creates the file if it is not created. While another command cat file 1 file 2 > file 3 appends two or more files to one.

131. What is NFS and Benefits of NFS?

Full form of NFS is Network File System. NFS is used for sharing of the files and folders between Linux/Unix systems by Sun Microsystems in late 1980. NFS helps you in mounting your local file systems or drive over a network and remote \ client hosts can use it as it mounted locally on their system. With the help of the NFS, we can set up file sharing between the cross-operating system, Unix to Linux system and vice versa. If you want to use Linux system mount on windows, you need to use SAMBA\CIFS in place of NFS.

Benefits of NFS:-

You can access remote files as local
NFS uses client/server architecture for file sharing
NFS support file sharing cross-operating systems
NFS helps in building centralized storage solutions
Users can access their data irrespective of physical location
No manual refresh needed for new files
NFS can be secured with Firewalls and Kerberos

132. Which command will list the current time source?

The ntpd program is an operating system daemon which sets and maintains the system time of day in synchronism with Internet standard time servers.
# ntpd -q

133. Name some of the text editors that are available in Linux ?

Some of the common text editors that are available in Linux are vi/vim, nano, subl, gedit, atom, emacs. Vi is the default editor that you have in Linux machines.

134. How to check on the status of our RAID device?

# mdadm –query –detail /dev/md0
# cat /proc/mdstat

135. Find Files Without 777 Permissions?

# find / -type f ! -perm 777

136. What is the command to find all the files and directories having 777 permissions ?

find –perm option is used to find files based on permissions
Here "." or period denotes the current directory
$ find . -perm 777

137. How to find the difference in two configuration files?

You can use the diff command for this: 
$ diff abc.conf xyz.conf

138. What are the modes used in VI editor?

There are 3 types of modes in vi Editor:
Regular mode or command mode
Insertion mode or edit mode
Replacement mode or Ex mode

139. How to check os version in Linux command line ?

Type any one of the following command to find os name and version in Linux:
$ cat /etc/os-release
$ lsb_release -a 
$ hostnamectl
$ uname -r

140. How to find the kernel/OS version in Linux?

Run the command,
$ uname –a

141. How to get +100 MB files in file system?

$ find / -type  f -size +100M

142. What is the use of scp command in linux ?

SCP command stands for secure copy. It is used to copy/download data from one machine to another machine.

143. What is a jump server ?

A jump server is a virtual machine that is used to manage other systems. It is sometimes called a “pivot server” for this reason: once you are logged in, you can “pivot” to the other servers. It is usually security hardened and treated as the single entryway to a server group from within your security zone, or inside the overall network. A jump server is a “bridge” between two trusted networks. The two security zones are dissimilar but both are controlled.

144. What is a bastion host ?

A bastion host is also treated with special security considerations and connects to a secure zone (also known as jump server), but it sits outside of your network security zone. The bastion host is intended to provide access to a private network from external networks such as the public internet. Email servers, web servers, security honeypots, DNS servers, FTP servers, VPNs, firewalls, and security appliances are sometimes considered bastion hosts.

145. How to reverse lookup for IP address?

$ dig -x IP-Address

146. Getting rid of “-bash: dig: command not found” ?

install bind-utils package. It contains a collection of utilities (such as dig command and other) for querying DNS name servers to find out information about internet hosts. These tools will provide you with the IP addresses for given host names, as well as other information about registered domains and network addresses.

Use the yum command to install dig on CentoS 7:
$ sudo yum install bind-utils

147. Explain dig command output?

The dig command output has the following sections:

HEADER: This displays the dig command version number, the global options used by the dig command, and few additional header information.

QUESTION SECTION: This displays the question it asked the DNS. i.e This is your input. Since we said ‘dig’, and the default type dig command uses is A record, it indicates in this section that we asked for the A record of the website.

ANSWER SECTION: This displays the answer it receives from the DNS. i.e This is your output. This displays the A record of

AUTHORITY SECTION: This displays the DNS name server that has the authority to respond to this query. Basically this displays available name servers of

ADDITIONAL SECTION: This displays the ip address of the name servers listed in the AUTHORITY SECTION.

STATUS SECTION: Stats section at the bottom displays few dig command statistics including how much time it took to execute this query.

148. How do I use dig command?

The syntax is:

dig Hostname
dig DomaiNameHere
dig @DNS-server-name Hostname
dig @DNS-server-name IPAddress
dig @DNS-server-name Hostname|IPAddress type

149. Sometimes NSCD die itself and DNS resolving doesn't occur properly. How can we avoid NSCD for DNS and is there any disadvantage to bypass it?

NSCD means Name Service Cache Daemon which provides a cache for the most common name service requests. When resolving a user, group, service the process will first try to connect to the NSCD socket (something like /var/run/nscd/socket2).

If NSCD died, then the connection will fail and NSCD won't be used for same and that should not be a problem.

If NSCD in a hung state, then the connection may hang or succeed. If this succeeds then the client will send the request. Now, we can configure NSCD to disable caching for any type of the database (for instance by having enable-cache hosts no in the /etc/nscd.conf for hosts database).

However, if NSCD is in a hung state, it may not be able to even give that simply won't do the answer, so that won't necessarily help. NSCD is a caching daemon, it's meant to improve the performance. Disabling it would potentially make those lookups slower. However, that's only true for some kind of databases. For the instance, if user/service/group databases are only in small files (/etc/passwd, /etc/group, /etc/services), then using NSCD for those will probably bring little benefit if any. NSCD will be very useful for the host's database.

150. What are aliases and how to create them with examples ?

Aliases are abbreviated shortcuts used to represent a command or a group of commands executed with or without custom options.
alias command instructs the shell to replace one string with another string while executing the commands.

#Alias for log directory
alias logs="cd /user/application/logs"

These aliases can be put in the ~/.bash_aliases file.

To have the aliased command on any existing terminal, user needs to source ~/.bashrc from the terminal :
source ~/.bashrc

                                                                                           MENU         PREVIOUS | NEXT