Sunday, 5 July 2020

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.

Example:
$ curl -I -s application:5000
HTTP/1.0 500 INTERNAL SERVER ERROR

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 http://webname.com/myfile.tar.gz #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.,?

/etc/login.defs

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
OR
# 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 _access.so
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.
ENCRYPT_METHOD SHA512

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’:
#vigr
manualusr:x:1002:

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
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}
done
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/id_rsa.pub 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:
LOCKFILE=/tmp/lock-`whoami`
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "Already running!"
    exit 1
fi
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 192.168.0.1 can simply be done with the following command:
# ip route add blackhole 192.168.0.1/32 

218. How to add a null route?

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

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

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

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 192.168.0.197
 ssh: connect to host 192.168.0.197 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 192.168.0.195
# ip route show
 default via 192.168.0.1 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
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