Sunday, 5 July 2020

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
256

$ 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

example,
$ 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/bad_link.pl
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:
/etc/sysctl.conf

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
echo $HISTSIZE
3000

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
/etc/lvm/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.
nohup COMMAND [ARGS]

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?

#!/bin/bash
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
do
kernel=`ssh root@${server} "uname -r"`
echo -e "$server \t\t $kernel" >> $result
done

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
[local]
name=RHEL6.5
baseurl=file:///media
enabled=1
gpgcheck=1
gpgkey=file:///media/RPM-GPG-KEY-redhat-release

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
60  

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 redhat.com’, and the default type dig command uses is A record, it indicates in this section that we asked for the A record of the redhat.com website.

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

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

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

How many characters can a file name have?


101. How many characters can a file name have?

The maximum amount of characters that a file name in Linux may have is 255.

102. What is the similarity and difference between cron and anacron? Which one would you prefer to use?

Cron and Anacron are used to schedule the tasks in cron jobs. Both of these are the daemons that are used to schedule the execution of commands or tasks as per the information provided by the user.

Differences between cron and anacron:

• cron works on the system that are running continuously that means it is designed for the system that is running24*7. While anacron is used for the systems that are not running continuously.

• jobs can run every minute, but anacron jobs can be run only once a day.
• Any normal user can do the scheduling of cron jobs, but the scheduling of anacron jobs can be done by the superuser only.

• Cron should be used when you need to execute the job at a specific time as per the given time in cron, but anacron should be used in when there is no any restriction for the timing and can be executed at any time.

• If we think about which one is ideal for servers or desktops, then cron should be used for servers while anacron should be used for desktops or laptops.

103. What are the default port numbers used for SMTP, FTP,DNS, DHCP, SSH?

Service      Port

SMTP 25
FTP         20 for data transfer and 21 for Connection established
DNS          53
DHCP 67 (UDP for DHCP server), 68  (UDP for DHCP client)
SSH         22

104. Explain file content commands along with the description.

There are many commands present in Linux which are used to look at the contents of the file.

head: to check the starting of a file.
tail: to check the ending of the file. It is the reverse of head command.
cat: used to view, create, concatenate the files.
rrep: used to find the specific pattern or string in a file.
more: used to display the text in the terminal window in pager form.
less: used to view the text in the backward direction and also provides single line movement.

105. Explain cd command in Linux?

In Linux, when a user needs to change the current directory then “cd” command is input in the shell.
Syntax: $cd

The purpose that can be fulfilled by the current command are –
• Redirect to a new directory from the current directory.
• Change a directory using absolute path and relative path.

The following commands are under the cd:
• cd ~:  Redirect to home directory.
• cd-:  Redirect to previous directory.
• cd/: Redirect to entire system directory.

106. How will you check if the two files are hard-linked to each other?

# ls –i, check the inode numbers are same or not.

107. What is the command that displays the settings for all services and run-levels?

# chkconfig --list # This output shows SysV services only
# systemctl list-unit-files #list systemd services

108. What is the command to list the hidden files in your HOME directory?

# ls -la ~/

108. Explain system calls used for process management?

System call provides additional control over the system. Processes are the most basic unit on Linux System and process management need some system calls in Linux, some of them are:-

System calls Explanation

Fork         Creates a new process
Exec         Execute the program
Wait         Force process to wait
Exit         Exit/terminate the process
Clone Creates Child Process
Exit_Group Exit/terminate all threads in the process
Nice         Change the priority of the running process
Getppid Find parent ID of the process
Vfork Create Child Process and block parent

109. What is page frame?

A page frame is a block of RAM that is used for virtual memory. It has its page frame number. The size of a page frame may vary from system to system, and it is in the power of 2 in bytes. Also, it is the smallest length block of memory in which an operating system maps memory pages.

110. What is the difference between rm and rm –r?

The rm command is used to delete all the files while rm –r command is used to delete all the files in a directory and also in subdirectories.

For Example,

# rm file.txt: It will delete the file with name file.txt
# rm –r directory: It will remove directories and subdirectories and also their contents.

111. How can we edit a file without opening in Linux?

sed command is used to edit a file without opening. sed is the acronym for StreamEditor. The sed command is used to modify or change the contents of a file

For example, 

# cat test.txt
one six three four five

to replace the content of the file and we want to replace "six"  with “two”. So, we will use below command for this.

# sed 's/six/two/' test.txt > out.txt

# cat out.txt
one two three four five
So, "six" is replaced with "two" in the text.

112. What are shared, slave, private, and unbindable mountpoints?

A mount point that is shared may be replicated as many times as needed, and each copy will continue to be the exact same. Other mount points that appear under a shared mount point in some subdirectory will appear in all the other replicated mount points as it is.

A slave mount point is similar to a shared mount point with the small exception that the “sharing” of mount point information happens in one direction. A mount point that is slave will only receive mount and unmount events. Anything that is mounted under this replicated mount point will not move towards the original mount point.

A private mount point is exactly what the name implies: private. Mount points that appear under a private mount point will not be shown elsewhere in the other replicated mount points unless they are explicitly mounted there as well.

An unbindable mount point, which by definition is also private, cannot be replicated elsewhere through the use of the bind flag of the mount system call or command.

113. What are some basic measures that you would take to harden a server’s SSH service?

There are a some very simple steps that can be taken to initially harden the SSH service, such as:

• Forcing the service to use only version 2 of the protocol will introduce both security and feature enhancement.

• Disabling root login, and even password-based logins, will further reinforce the security of the server.

• The whitelist approach can be taken, where only the users that belong to a certain list can login via SSH to the server.

• Disabling password-based login will require you to then allow key based logins, which is secure, but can be taken further by restricting their use from only certain IP addresses.

• Changing the port to something other than 22 significantly decreases random brute force attempts from the internet.

Sometimes the use of having an SSH service on a server may just be transferring files to and from the server (typically using tools like scp). In such a case, it is possible to change the shell of the user to something restrictive, such as rssh.

Finally it is often desirable to know exactly what is going on while you are not logged into the server. The logging verbosity may be increased if needed. Often, it is the logs that allow one to figure out if a key has indeed been stolen and is being abused.

114. What would be a simple way to continuously monitor the log file for a service that is running?

Probably the simplest and most common way to do this would be by using the command:
tail -f $LOGFILE

where $LOGFILE is an environment variable corresponding to the path to the log file to be monitored.
By default, the Linux tail command prints the last 10 lines of a given file to standard output. The -F option causes additional file content to be displayed in realtime as the file continues to grow. This yields a simple mechanism for monitoring services via their log files in close to realtime.

Two other specific command line options of interest in this context are:

• The -s option causes tail to sleep for a specified number of seconds between updates (e.g., tail -F -s 10 will update the displayed file contents roughly every 10 seconds rather than in close to realtime as the file is updated).

• The -n option can be used to specify a number of lines other than 10 to initially display (e.g., tail -n 20 -F will first display the last 20 lines of the file and will then continue updating the output in realtime).

115. How to check the default route and routing table?

To display the default route and routing table, we use the following commands.

$ route -n
 
$ netstat -rn
 
$ ip

116. How to check which ports are listening in my Linux Server?

To check which ports are in listening in Linux Server, 

# netstat --listen
# netstat -l

117. What are the different modes of Network bonding in Linux?

• Mode-0(balance-rr): It is a default mode and based on Round-Robin policy. It offers fault tolerance and load balancing features. It used round-robin fashion to transmit the packets.

• Mode-1(active-backup): It is based on Active Backup policy and only one slave will act in the band and another one will act when the others fail in the band. It also provides fault tolerance.

• Mode-2(balance-xor): It sets a xor mode between the source Mac address and destination Mac address to provide fault tolerance.

• Mode-3(broadcast): It is based on broadcast policy and transmitted everything in the slave interface. It also provides fault tolerance and it can be used only for a particular purpose.

• Mode-4(802.3ad): It is a dynamic aggregation mode, it created aggregation groups which is having the same speed. It uses transmit hashing method to select the slaves for outgoing traffic.

• Mode-5(balance-tlb): The outgoing traffic is according to the current load on the slave, and the incoming traffic is received by the slave. It is called an adaptive transmit load balancing mode. 

• Mode-6(balance-alb): It is an adaptive load balancing mode. It does not require any switch support. 

118. Why we use LINUX? 

We are some many reasons, in that few important reasons are listed out. Following are

• High Stability: It is very stable and does not lead to crashes, it runs fastly as it is when it installed first. 

• Security: It is a dependable server, that offers high security to the user. Using Linux on your system it is easy to avoid virus and malware. The attacker cannot change any changes in the system until the user logged in at as root user.

• Easy to Operate: Linux is easy to operate and we can install easily on to the system because all the variants of the Linux have there owned software repositories. You can update the system periodically with just a few clicks or you can set automatic updation.

• Hardware Compatibility: Linux can use on any hardware, it doesn’t have any hardware restrictions. It uses efficiently all system resources.

• Open Source: The source code is available as it is under Free and Open Source Software(FOSS).
119. Why is Linux considered more secure than other operating systems?

Linux is an open-source operating system, nowadays it is rapidly growing in the technology market. A few reasons why Linux is more secure than other OS.

• The perk of accounts: Linux allows only a few users to access the system. Thus, the virus cannot attack the whole system, it may cause only a few files in the system. 

• Strong Community: Linux users first accomplished the files before they open. So they can save their systems from vulnerabilities. 

• Iptables: Iptables used by the Linux because it checks the security circle of the system. 

• Different Working Environment: Linux system has different working environments like Linux Mint, Debian, Arch and many more, these working environments protect from the virus.

• Recording in Linux: It maintains log history because later it can view the details of the system files easily. 

• Few User: Linux users are less compared to others, due to this security will be more.

120. How can you setup Password Aging?

In Linux, the system administrators use chage command to apply password ageing. This command is used to modify the number of days among resets of a mandatory password. 
The /etc/login.defs file is accountable for managing the configuration in the system. It can be edited for:
• PASS_MIN_DAYS – States the minimum days allowed between password reset.
• PASS_MAX_DAYS – States the maximum days to use a password.
• PASS_WARN_AGE – States the days to give warning before a password expires.

121. Name some troubleshooting and Linux networking commands?

All computers are linked to network externally or internally for the aim of information exchange. Network configuration and troubleshooting are some of the essential elements of network administration. The networking commands allow you to rapidly troubleshoot issues related to the connection with another system; check another host response, etc.

A network administrator upholds network of a system including network troubleshooting and configuration. Some commands with their description are mentioned below:

• Hostname: This command is used to view the machine hostname (IP address and domain) and for hostname setting.

• ifconfig: used to manipulate and display network and route interfaces. It shows the configuration of the network. ‘IP’ is the ifconfig command replacement.

• Traceroute: It is a utility of network troubleshooting, used to find the hops needed for a packet for accessing the destination.

• Dig:  used for DNS name servers query for any job related to the DNS lookup.

• Route: It displays the route table details and operates the IP routing table.

• Ifplugstatus: it tells if the network cable is plugged in or not.

• Ping: this command is used to identify if the remote server is accessible or not.

• netstat: It shows network links, interface statistics, routing tables. ‘ss’ is the netstat command replacement, used to get more data.

• Tracepath: It like a traceroute with a change that it does not need root rights.

• nslookup: This command is used to find query related to DNS.

• mtr: it combines track path and ping into a single command.

122. What is the device tree concept?

Device tree is a data structure which is used to remove the repetitive codes in different boards. They are loaded in the memory with the help of bootloader to a binary file. Here the kernel is used to settle the structure of the device tree on the binary.

123. How can we reduce the size of the kernel?

There are codes which are unnecessary and are not executed, we can find and disable them to make the processing faster in the project. The kernel comes with an editor known as “kernel’s configuration editor” by which we can remove and disable chunks of code that are not required.

There may be the codes for which the hardware is not present in the system and you have to make your system understand about what are your system’s requirements. Below are some guiding principles by which you can find the codes to be removed.

• Hardware Networking Drivers: Several of system-on-chips have Wi-Fi drivers, serial and other hardware that are not used, you can remove those drivers that are built on the kernel.

• File Systems: The system has the only requirement of few file systems but in the kernel you will find many file systems drivers that are not in use e.g. Devices which make use of flash file systems do not require ext2 or ext3 file system so they can be removed. Be cautious that do not remove the file systems that are essential or you may have the use of the systems in the future.

• Debugging and Profiling: All the systems which come under kernel hacking entry could be disabled if not in use.

124. Explain the command and method to change the file permissions in Linux?

chmod command is used to change the permissions of a file. There are three parts to consider to set the file permissions.

• User (or Owner)
• Group
• Other

3 types of file permission that is given to a file.

• r – Reading permission
• w – Writing permission
• x – Execution permission

For example, chmod 751 filename
Then, three number 751 describes permissions given to the user, group and other in the order. Each number is the sum of the values,i.e. 4 for reading, 2 for write, 1 for execute.
Here 751 is the combination of (4+2+1), (4+0+1), (0+0+1).

So, chmod 751 filename will provide read, write and execute permission to the owner; read and execute permission to the group and only execute permission to the others.

125. Where is the target path of a symlink stored? How are permission settings for symlinks handled?

The target path of a symlink is stored in an inode - the data structure used to store file information on disk.

Typically, the permission settings of the symlink itself only control the renaming and removal operations performed on the symlink itself. Any operation that deals with the contents of the file linked to are controlled by the permission settings of the target file.

                                                                                           MENU         PREVIOUS | NEXT

What is the difference between Linux and Unix?


76. What is the difference between Linux and Unix?

Linux Unix

Both paid and free distributions are available. Different paid structures for different levels of Unix.

Linux primarily uses GUI with an optional            Unix uses the command-line interface
command-line interface

Portable and can be executed in                        Not portable.
different hard drives

Developed by a worldwide Linux community. Developed by AT&T developers.

Bug Fix Speed is Faster because            Bug Fix Speed is Slow
Linux is Community driven.

Linux is used at home-based PC's, phones, etc. Unix is used mainly as Internet Server, Workstations, Mainframes.

File System Support: Ext2, Ext3, Ext4,     File System Support: jfs, gpfs, hfs, hfs+, 
Jfs, ReiserFS, Xfs, Btrfs, FAT, FAT32, NTFS.           ufs, xfs, zfs,vxfs.

Examples:Ubuntu, Fedora, Red Hat, Examples:OS X, Solaris, All Linux
Kali Linux, Debian, Archlinux, Android, etc. 

Linux comes with open source Netfilter and   UNIX operating systems comes with its own firewall 
IPTables based firewall tool to protect server         products. 
and desktop from the crackers and hackers. 

Viruses listed: 60-100 Viruses listed: 80-120

77. What are soft links? Describe some of the features of soft links?

Soft Links or Symbolic Link or Symlink are special files which are used as a reference for another directory.

 Some features of softlinks are:

• They have a different INODE number with respect to source files or original files.
• If in case the original file is deleted then a soft link of that file is useless.
• We cannot update a soft link.
• Soft links are used to create links between directories.
• Soft links are independent of file system boundaries.
78. Explain the linux directory commands?

The linux directory commands are :

• pwd: It is a built-in command which stands for ‘print working directory’. It displays the current working location, working path starting with a / and directory of the user. Basically, it displays the full path to the directory you are currently in.

• Is: This command lists out all the files in the directed folder.

• cd: This stands for ‘change directory’. This command is used to change to the directory you want to work from the present directory. 

• mkdir: This command is used to create an entirely new directory.

• rmdir: This command is used to remove a directory from the system.
79. Which is the first process started by the kernel and what is itsprocess id?

‘init’ is the first process in linux which is started by the kernel and its process id is 1.
80. Is it legal to edit Linux Kernel?

Yes , it is absolutely legal to edit Linux Kernel. Kernel is released under General Public License(GPL) , and anyone can edit Linux Kernel to the extent permitted under GPL. Linux Kernel comes under the category of Free and Open Source Software(FOSS).
 
81. Explain /bin, /usr, /sbin, /user/bin and /user/sbin Linux directories?

/bin: Its critical directory used to bring the system online in single-user mode to repair it. This contains executable programs(can say scripts) for this.

/sbin: This directory holds commands needed to boot the system in normal condition but not executed or used by normal users.

/usr: This is one of the largest directories in the Linux system, mostly mounted from a separate partition. Birnies and files all programs are installed reside here.

/usr/bin: This directory contains programs, executables and scripts not used for boot process but used by users to execute. Most of the programs or executable executed by users rather than root

/usr/sbin: Program binaries or executables required for a system administrator is kept under this directory. This program binaries or executables are not required for boot process or normal users.

82. What are filenames that are preceded by a dot?

Generally, all the hidden files are preceded by a dot. These files hold important or setup info as they can be configuration files. Keeping these files as hidden makes them secure from being accidentally deleted.

83. What does Sar provide? Where are Sar logs stored?
SAR is an abbreviation for System Activity Report. This command is used to collect data, report and save the usage of CPU, a Memory unit, input, and output in Linux. 

84. What is the full form of grep?

Grep stands for global regulation expression point. The command-line utility, grep, is used for searching data sets in plain-text for lines that match an expression which is used regularly. 

85. Explain Window Manager in Linux?

Window Manager is client software that controls icons, placement of icons, the appearance of the window after login to the system. This is desktop management software. LINUX is an open-source operating system and it have a long list of WM software available in the market. The system administrator can install and configure it as per user or environment requirements. One thing before using WM software, they will consume additional resources on the system.

The/etc/.xinitrc file is hidden system files allows you to change the window manager while login from any or particular user account. The prefix of “.” In the file, the name shows that it is hidden file and you will not be able to view it with the normal ls command.  WM gives enhance user experience or add-on features.

Some of the popular command for WM or desktop management are:-

• The KDE = startkde
• The Gnome = gnome-session
• The Blackbox = Blackbox
• The FVWM = fvwm
• The Window Maker = wmaker
• The IceWM = icewm

86. What is the FTP Server?

FTP is the simplest file transfer protocol to exchange files to and from a remote computer or network system. Similar to Windows, Linux, and UNIX operating systems they also have built-in command-line prompts that can be used as FTP clients to establish FTP connection. FTP works in Client-Server architecture to communicate and transfer the file during an established FTP session. 

When the Client initiates a connection to the server, it’s called Passive Connection. Whereas when Server initiates a connection to the client, it’s called Active Connection.

In Phase 1, When Connection initiated with the server, User credentials are passed for authentication. This is the control connection phase. In Phase 2, When actual data is transferred between client & server, This is data connection phase.

87. Differences between Softlink and Hardlink?

Hard Links 

  •   Gets created using same I-node number with a different name.
  •   Can only be created within same file system.
  •   Remains even if original file is removed.
  •   Can’t be created for directories.
  •   Created using ln command

Soft Links

  •   Gets created using alias name referring the original file name, but uses different I-node.
  •   Can be created across file systems.
  •   Dies after original file is removed, otherwise exists as a dead link.
  •   Can be used to create links to directories.
  •   Created using ln -s command

88. What is the difference between umask and ulimit?

unmask stands for user file creation mode. When the user creates any file, it has default file permissions. So unmask will specify few restrictions to the newly created file (it controls the file permissions).

umask [-S] [mask]

You can limit user to specific range by editing /etc/security/limits.conf at the same time system wide settings can be updated in /etc/sysctl.conf


89. Your server is using a lot of cached memory. How do you free it up short of rebooting?

Kernels 2.6.16 and newer provide a mechanism to have the kernel drop the page cache and/or inode and dentry caches on command, which can help free up a lot of memory.
To free page cache, dentries and inodes: echo 3 > /proc/sys/vm/drop_caches

90. What is the difference between /dev/random and /dev/urandom for generating random data?

The Random Number Generator gathers noise of environment from the device drivers and other sources into the entropy pool. It also keeps an estimate of the number of bits of the noise in an entropy pool. It is from this entropy pool and will generate random numbers.

/dev/random will only be returning Random bytes from the entropy pool. If the entropy pool is empty, reads to /dev/random will be blocked until the additional environmental noise will be gathered. This is suited to high-quality randomnesses, such as the one-time pad or key generation.

/dev/urandom will return as many random bytes requested. But if the entropy pool is empty, this will generate data using SHA, MD5 or any other available algorithm. It never blocks the operations. Due to which, the values are vulnerable to the theoretical cryptographic attack, though no known methods will exist.

For cryptographic purposes, we should really use the /dev/random because of the nature of data it returns. Possible waiting should be considered as an acceptable tradeoff for the sake of the security, IMO. When we need random data fast, we should use the /dev/urandom of course.

Both /dev/urandom and the /dev/random are using exact same CSPRNG (a cryptographically secure pseudorandom number generator). They can only differ in very few ways that have nothing to do with the “true” randomness and then /dev/urandom is the preferred source of cryptographic randomness on the UNIX-like systems.

91. What is Samba Share?

Samba is an open-source software suite that runs on the Unix/Linux based platforms but it is able to communicate with the Windows clients like a native application. So Samba is able to provide the service by employing the Common Internet File System (CIFS).

At the heart of the CIFS is the Server Message Block (SMB) protocol.  Samba does this by performing the four key things –

• The File & print services
• The Authentication and Authorization
• The Name resolution
• The Service announcement (browsing)

Samba can be run on many different platforms including Linux, Unix, OpenVMS and the operating systems other than the Windows and allows users to interact with a Windows client or server natively. It can basically be described as Standard Windows interoperability suite of the programs for Linux and Unix.

92. What is IRIX Mode in top command?

In Irix Mode, System considers all processors as a whole and CPU usage can vary from 0 to 100 only. IRIX feature was introduced in Solaris and adopted by Linux later.

93. If you have a file with 2000 IP's. How do you ping them all using bash in parallel?

# echo $(cat iplistfile) | xargs -n 1 -P0 ping -w 1 -c 1

94. What command can you use to send unsolicited ARP updates to the neighboring servers caches.

# arping -U -c 1 -I eth0 0.0.0.0 -s IP_ADDRESS

95. Write command to list all the links from a directory?

# ls -lrt | grep "^l"

96. What Linux utility can craft custom packets, like TCP SYN packets and send them to a remote host?

# hping3 -S 192.168.1.1 -p 80 -i u1

97. Create a read-only file in your home directory?

create a file and change its parameter to read-only by using chmod command you can also change your umask to create read only file.

$ touch file
$ chmod 400 file

98. How will you run a process in background? How will you bring that into foreground and how will you kill that process?

For running a process in background use "&" in command line. For bringing it back in foreground use command "fg jobid" and for getting job id you use command jobs, for killing that process find PID and use kill -9 PID command.

99. How to search files in linux?

To search files in Linux, use the locate  or find command.

100. How to remote login to another linux computer?

You can log in to a remote Linux computer using SSH protocol or using the VNC service.

                                                                                           MENU         PREVIOUS | NEXT

How to create and delete a directory in Linux?


51. How to create and delete a directory in Linux?

To create a directory use the mkdir command as shown;
mkdir directory_name

For example to create a directory called 'data' run the command:
# mkdir data

To delete a directory in Linux, use either the rm or rmdir command.
The rmdir command is used for removing empty directories.
The rm command is mostly used with the -R flag for recursively removing directories.

52. How to list and mount devices in Linux?

To list mount points run the command:
# df  -aTh

To find more information about the mount points on your system, execute the command:
# findmnt

Additionally, you can use the cat command below
# cat /proc/self/mounts

Also, you can use the mount command as shown
# mount -l

53. How to schedule a task in Linux? What is crontab and explain the fields in a crontab?

The cron is a deamon that executes commands at specific dates and times in Linux. You can use this to schedule activities, either as one-time events or as recurring tasks. Crontab is the program used to install, deinstall or list the tables used to drive the cron daemon in a server. Each user can have their own crontab, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. 

Here are few of the command line options for crontab.

# crontab -e #Edit your crontab file.
# crontab -l #Show your crontab file.
# crontab -r #Remove your crontab file.

Traditional cron format consists of six fields separated by white spaces:

<Minute> <Hour> <Day_of_the_Month> <Month_of_the_Year> <Day_of_the_Week> <command/program to execute>

The format is explained as follows:

* * * * * *
| | | | | |
| | | | | +-- Year (range: 1900-3000)
| | | | +---- Day of the Week (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month (range: 1-31)
| +---------- Hour (range: 0-23)
+------------ Minute (range: 0-59)

54. What are the basic Vim commands you know?

a) Save
To save a file, press ESC button and press :wq! OR :ZZ

b) Exit
To exit from a file without making changes, run the command :q

c) Jump to a particular line in a file
Press ESC and press j to move down by one line.
To move up by one line press k on the keyboard
Move the cursor to the beginning of a line Press ^
Move the cursor to the end of a line Press $
Move the cursor to the beginning of a file 1G
Move the cursor to the end of a file G
Moves the cursor to the start of line number “n” in the file nG

d) Copy text
Move the cursor to the beginning of the string or text. Next hit v on your keyboard and press cursor forward to highlight text. Once you get to the end of text that you wish to copy, hit y short for yank, to copy the text.
To copy text from current position to the end of the line - y$
To copy the entire line - yy
To copy 4 lines below - 4yy

e) Paste text
To paste text, simply press p on the keyboard

f) Delete text
To delete a line, move to the beginning of a line. Press the ESC button and press dd
To delete a single word, place the cursor in front of the word and hit dw
To delete text from the current word to the end of the line hit d$
To delete 3 lines below run 3dd

55. Explain are different process states in Linux?

When we execute “ps aux”  in Linux terminal console, we can see multiple states of processes running in the system under the STAT column.

R: Process is running with CPU or waiting for CPU (Running or Runnable)

S: Process is waiting for the set event to complete, Like an input from terminal (SLEEP)

D: Process is with uninterruptible sleep stats which cannot be changed or killed \ rollback. The only way to go away is the reboot system.

Z: Process in Zombie status means the process is already killed but process information and data still exist in the process table.

T: Process either completed or terminated by the operating system or user. This is also known as Terminated /  Completed.

56. What are inodes in Linux? How to find the inode associated with a file?

The inode (index node) is a data structure in a Unix-style file system that describes a file-system object such as a file or a directory. When a file is created, it is assigned both a name and an inode number, which is an integer that is unique within the filesystem.

Explanation,
File systems have two parts: the metadata or the “data” about the data and the data. Metadata consist of information about the data. It includes information such as the Access Control List (ACL), the date the file was modified, file owner, file permissions, size of file, device ID, uid of the file, etc. inodes store this metadata information and typically they also store information about where the data is located on the storage media.

In a file system, inodes consist roughly of 1% of the total disk space, whether it is a whole storage unit (hard disk, thumb drive, etc.) or a partition on a storage unit. The inode space is used to track the files stored on the hard disk. The inode entries only points to these structures rather than storing the data. Each entry is 128 bytes in size. Space for inodes is allocated when the operating system or a new file system is installed and when it does its initial structuring. So this way we can see that in a file system, the maximum number of inodes and hence maximum number of files are set. Now, the above concept brings up another interesting fact. 

A file system can run out of space in two ways:

• No space for adding new data is left
• All the inodes are consumed.

To get a listing of an inode number, use ls -i command.

# ls -li or # ls -li file_name 

# find /root -inum inode_number

57. Explain file permission in Linux?

In Linux, there are 3 main types of file permissions: read, write and execute. These permissions can be assigned to either a file or a directory recursively.  Being a multi-user system, you can assign these permissions to the root user, groups or even to other users using the system.

Read: The read permission grant uses the ability to open and read a file.

Write: Write permission allows a user to open and modify or edit the file's contents and save the changes.

Execute: This allows a user to execute or run the file or a program or shell script which is executable.

Decimal Permission Representation

0 No Permission - - -
1 Execute - - x
2 Write - w -
3 Write + Execute - w x
4 Read r - -
5 Read + Execute r - x
6 Read + Write r w –
7 Read + Write + Execute r w x

58. What basics measures could you take to secure an ssh connection? For Linux users, it is frequent to access servers by ssh. But are we sure that the communication established is really good secured?

Linux has secured shell services used to connect a Linux system in a secured manner. SSH is is the most common tool for a system administrator for better system management and security. SSH gives some advance features that need proper knowledge and expertise to use. SSH gives more features to the user.

Steps to secure ssh services as below:-

1. Disable/enable Root User
2. Reset Root user password
3. Disable password-based login and enable key-based logins
4. Change standard ports of the system and assign random ports
5. Restricted network access from the system
6. Use a white list approach to allow only authorized IPs to connect

59. Describe what happens when you run the rm command?

The rm command removes a filename from a directory list, decrements the link count of the corresponding i-node by 1, and, if the link count thereby falls to 0, deallocates the i-node and the data blocks to which it refers.

60. What is a process?

A process is an instance of an executing program. When a program is executed, the kernel loads the code of the program into virtual memory, allocates space for program variables, and sets up kernel bookkeeping data structures to record various information (such as process ID, termination status, user IDs, and group IDs) about the process. From a kernel point of view, processes are the entities among which the kernel must share the various resources of the computer.

61. What are the logically divided parts of a process?

A process is logically divided into the following parts, known as segments:
* Text: the read-only machine-language instructions of the program run by the process.
* Data: initialized/uninitialized global and static variables used by the program;
* Heap: an area from which memory (for variables) can be dynamically allocated at run time. The top end of the heap is called the program break;
* Stack: a piece of memory that grows and shrinks as functions are called and return and that is used to allocate storage for local variables and function call linkage information;

62. How are threads different from processes?

Like processes, threads are a mechanism that permits an application to perform multiple tasks concurrently. A single process can contain multiple threads. All threads are independently executing the same program, and they all share the same global memory, including the initialized data, uninitialized data, and heap segments.

Sharing information between threads is easy and fast. It is just a matter of copying data into shared (global or heap) variables. However, in order to avoid the problems that can occur when multiple threads try to update the same information, we must employ some synchronization techniques.
Thread creation is faster than process creation—typically, ten times faster or better. On Linux, threads are implemented using the clone() system call.

63.  What is a Signal in Linux, and what signal is invoked when you use the kill command? What is the difference between kill and kill -9?

A. A signal is a limited form of inter-process communication used in Unix, Unix-like, and other POSIX-compliant operating systems. It is an asynchronous notification sent to a process or to a specific thread within the same process in order to notify it of an event that occurred. When a signal is sent, the operating system interrupts the target process's normal flow of execution.

The difference between invoking kill with no signal specified (which uses SIGTERM, number 15) and kill -9 is that the latter tries to kill the process without consideration to open files and resources in use.

64. How do you debug a running process or a library that is being called?

# strace -p PID
# ltrace libraryfile

65. How to see a memory map of a process, along with how much memory a process uses?

# pmap -x PID

66. What is Huge Pages in Linux and what use is there for them?

Hugepages is a mechanism that allows the Linux kernel to utilize the multiple page size capabilities of modern hardware architectures. Linux uses pages as the basic unit of memory, where physical memory is partitioned and accessed using the basic page unit. The default page size is 4096 Bytes in the x86 architecture. Hugepages allows large amounts of memory to be utilized with a reduced overhead.

To check: # cat /proc/sys/vm/nr_hugepages.
To set: # echo 5 > /proc/sys/vm/nr_hugepages

67. What symbol represents that ACLs have been set on a file?

+

68. How would you continuously display memory usage every 5 seconds?

# free -s 5

69. How to stop a running process in Linux?

To stop a running process, use the kill command followed by the PID of the process.

to stop a process with PID 3836, run the command
# kill 3836

70. What is the difference between name based virtual hosting and IP based virtual hosting?

Virtual hosts are used to host multiple domains on a single apache instance. You can have one virtual host for each IP your server has, or the same IP but different ports, or the same IP, the same port but different host names. The latter is called "name based vhosts".

On IP-based virtual hosting, we can run more than one web site on the same server machine, but each web site has its own IP address while In Name-based virtual hosting, we host multiple websites on the same IP address. But for this to succeed, you have to put more than one DNS record for your IP address in the DNS database.

71. What is the advantage of Network Bonding?

Network Bonding(also known as NIC Teaming) is a Linux kernel feature that allows aggregating multiple network interfaces into a single virtual link. This is a great way to achieve redundant links, fault tolerance or load balancing networks in the production system. If one of the physical NIC is down or unplugged, it will automatically move traffic to the other NIC card. Similar way the bonding will increase the interface throughput to handle the traffic it is configured in active-active mode.

72. Where is password file located in Linux and how can you improve the security of password file?

User information along with the passwords in Linux is stored in /etc/passwd that is a compatible format. But this file is used to get the user information by several tools. Here, security is at risk. So, we have to make it secured.
To improve the security of the password file, instead of using a compatible format we can use shadow password format. So, in shadow password format, the password will be stored as single “x” character which is not the same file (/etc/passwd). This information is stored in another file instead with a file name /etc/shadow. So, to enhance the security, the file is made word readable and also, this file is readable only by the root user. Thus security risks are overcome to a great extent by using the shadow password format.

73. Explain all the fields in the/etc/passwd file?

/etc/passwd file contains the useful information for all the system users who log in. Many fields in /etc/passwd file such as username, password, user ID, group ID, comment or user ID info, home directory, command /shell, etc. So, this file contains sensitive information regarding all the user accounts. There is a single line per user in this file. Colon (:) separates the fields in /etc/passwd. 

Below is the explanation of the fields.

• Username: First field is the username that contains the username which is 1 to 32 length characters.

• Password: This field does not show the actual password as the password is encrypted. Here, x character shows that password is encrypted that is located in /etc/shadow file.

• User ID (UID): All the users created in Linux is given a user ID whenever the user is created. UID 0 is fixed and reserved for the root user.

• Group ID (GID): This field specifies the name of the group to which the user belongs. The group information is also stored in a file /etc/group.

• User ID Info: Here you can add comments and you can add any extra information related to the users like full name, contact number, etc.

• Home directory: This field provides the path where the user is directed after the login. For example, /home/smith.

• Command/shell: This field provides the path of a command/shell and denotes that user has access to this shell i.e. /bin/bash.

74. What is a Master boot Record and how do you back it up and restore it?

The MBR  is a 512 byte segment on the very first sector of your hard drive composed of three parts: 
•  the boot code which is 446 bytes long, 
•  the partiton table which is 64 bytes long, and 
•  the boot code signature which is 2 bytes long.

To backup: # dd if=/dev/sda of=/tmp/mbr.img_backup bs=512 count=1
To restore: # dd if=/tmp/mbr.img of=/dev/sda bs=512 count=1

75. You are using iSCSI or a virtual machine with attached block device. Due to high IO or network latencies the FS goes in read only mode from time to time. What can you do to increase the write time out on the block device?

To increase the write time out on a block device in real time use the sys fs:
echo 60 > /sys/block/sdk/device/timeout
        
                                                                                           MENU         PREVIOUS | NEXT