Linux Interview Questions and Answers

1.Create user with specified Home directory ..?

 Ans:      useradd -d "Directory Path" username
               Ex: useradd -d /var/aravi aravi

2. Create new user, user should change password by first login..?

 Ans:      useradd <user name>
               Ex: useradd aravi1; chage -d 0 aravi1; passwd aravi1

3. How to ditermine cronjob ran status..?

  Ans:

<After the Cron Script> Add the $? > <Log File>

Find the code below and its status

0  -- No problems.
1  -- An attempt has been made to start cron but there is already a /var/run/cron.pid file. If there really is no other cron daemon running (this does not include invokations of mcron) then you should remove this file before attempting to run cron.
2  -- In parsing a guile configuration file, a job command has been seen but the second argument is neither a procedure, list or string. This argument is the job's action, and needs to be specified in one of these forms.
3  -- In parsing a guile configuration file, a job command has been seen but the first argument is neither a procedure, list or string. This argument is the job's next-time specification, and needs to be specified in one of these forms.
4  -- An attempt to run cron has been made by a user who does not have permission to access the crontabs in /var/cron/tabs. These files should be readable only by root, and the cron daemon must be run as root.
5  -- An attempt to run mcron has been made, but there are no jobs to schedule!
6  -- The system administrator has blocked this user from using crontab with the files /var/cron/allow and /var/cron/deny.
7  -- Crontab has been run with more than one of the arguments -l, -r, -e. These are mutually exclusive options.
8  -- Crontab has been run with the -u option by a user other than root. Only root is allowed to use this option.
9  -- An invalid vixie-style time specification has been supplied.
10 -- An invalid vixie-style job specification has been supplied.
11 -- A bad line has been seen in /etc/crontab.
12 -- The last component of the name of the program was not one of mcron, cron, crond or crontab.
13 -- Either the ~/.cron directory does not exist, or there is a problem reading the files there.
15 -- Crontab has been run without any arguments at all. There is no default behaviour in this case.
16 -- Cron has been run by a user other than root.

4. What is zombie process in Linux ..?

Ans:  Zombie process is a process that has completed execution (via the exit system call) but still has an entry in the process table: it is a process in the "Terminated state".

5. How to find and kill zombie process in Linux ..?

Ans: To find zombie process in Linux use below command

$ ps axo stat,ppid,pid,comm | grep -w Z
$ kill -9 <PID>

6. How to find Linux system calls ..?

Ans: using $ strace command we can find system calls

7. What is the Difference between Hardlink and Softlink in Linux..?

Ans:
Hard Link:
A hardlink isn't a pointer to a file, it's a directory entry (a file) pointing to the same inode. Even if you change the name of the other file, a hardlink still points to the file. If you replace the other file with a new version (by copying it), a hardlink will not point to the new file. You can only have hardlinks within the same filesystem. With hardlinks you don't have concept of the original files and links, all are equal (think of it as a reference to an object). It's a very low level concept.

Soft Link:
A softlink is actually pointing to another path (a file name); it resolves the name of the file each time you access it through the symlink. If you move the file, the symlink will not follow. If you replace the file with another one, keeping the name, the symlink will point to the new file. Symlinks can span filesystems. With symlinks you have very clear distinction between the actual file and symlink, which stores no info beside the path about the file it points to.

8. How can I find all the Soft Links in my system ?

Ans. Use this command for the same “find /etc -type l -exec ls -li {} \;”

9. How can I find all the files having Hard Links in my system ?

Ans. Use this command for the same “find / -links +2 -type f -exec ls -li {} \;”

10. How to find whether a file is a softlink ?

Ans. Simply using this command “ls -l” will tell you whether a file is pointing to some other file or not.

11. How to check whether a file have any softlink pointing to it ?

Ans. Till now, I am not aware of any way to do that. If I will find any, I will surely update my post.

12. How can I find out the source file of a hard link ?

Ans. No, you can’t find out the source file of a hard link. Once hard link is created, there is no way to tell which was the first file created.

13. Can I make a Soft link to a Hard link and Vice Versa ?

Ans. Yes, both soft links and hard links acts as normal files of the file system, so you can do both.

14. What is the use of initrd directory..?

Ans. The Linux initial RAM disk (initrd) is a temporary root file system that is mounted during system boot to support the two-state boot process. The initrd contains various executables and drivers that permit the real root file system to be mounted

15. RHEL version comparison..?

Ans.
 
16. What is MYSQL query cache..?

Ans: The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again.


17. What is Difference between Swap and Pagefile ..?

Ans: SWAPFILES operate by swapping entire processes from system memory into the swapfile. This immediately frees up memory for other applications to use.
      PAGING FILES function by moving "pages: of a program from system memory into the paging file. These pages are 4KB in size. The entire program does not get swapped wholesale into the paging file, when next application is requested this paging file not immediately freedup.

18. How to check the MYSQL running processes ..?

Ans: You can run the MySQL command SHOW PROCESSLIST to see what queries are being processed.

19. How to identify which processes are taking more memory..?

Ans: Enter Command "top"
        Press SHIFT+F
        Press n (* N: %MEM       = Memory usage (RES))
        Press ENTER

                OR

use below command to see top 5 processes

$ ps -eo pmem,pcpu,vsize,pid,cmd | sort -k 1 -nr | head -5

19. TCP vs UDP ..?
Ans :

TCP - 
Transmission Control Protocol.
TCP is a connection-oriented protocol.
Use by other protocols HTTP, HTTPs, FTP, SMTP, Telnet.
The speed for TCP is slower than UDP.
TCP header size is 20 bytes
TCP does error checking
Acknowledgement segments

UDP - 
User Datagram Protocol or Universal Datagram Protocol
UDP is a connectionless protocol.
Use by other protocols DNS, DHCP, TFTP, SNMP, RIP, VOIP.
UDP is faster because there is no error-checking for packets.
UDP Header size is 8 bytes.
UDP does error checking, but no recovery options.
No Acknowledgment


.  what is the difference between bash & ksh..?

 Ans: 

Y Feature can be done using this shell.
N Feature is not present in the shell.
F Feature can only be done by using the shells function mechanism.
L The readline library must be linked into the shell to enable this Feature  
      
Description sh csh ksh bash tcsh zsh rc es
Job control N Y Y Y Y Y N N
Aliases N Y Y Y Y Y N N
Shell functions Y(1) N Y Y N Y Y Y
Sensible Input/Output redirection  Y N Y Y N Y Y Y
Directory stack N Y Y Y Y Y F F
Command history N Y Y Y Y Y L L
Command line editing N N Y Y Y Y L L
Vi Command line editing N N Y Y Y(3) Y L L
Emacs Command line editing N N Y Y Y Y L L
Rebindable Command line editing N N N Y Y Y L L
User name look up N Y Y Y Y Y L L
Login/Logout watching N N N N Y Y F F
Filename completion N Y(1) Y Y Y Y L L
Username completion N Y(2) Y Y Y Y L L
Hostname completion N Y(2) Y Y Y Y L L
History completion N N N Y Y Y L L
Fully programmable Completion N N N N Y Y N N
Mh Mailbox completion N N N N(4) N(6) N(6) N N
Co Processes N N Y N N Y N N
Builtin artithmetic evaluation N Y Y Y Y Y N N
Can follow symbolic links invisibly N N Y Y Y Y N N
Periodic command execution N N N N Y Y N N
Custom Prompt (easily) N N Y Y Y Y Y Y
Sun Keyboard Hack N N N N N Y N N
Spelling Correction N N N N Y Y N N
Process Substitution N N N Y(2) N Y Y Y
Freely Available N N N(5) Y Y Y Y Y
Checks Mailbox N Y Y Y Y Y F F
Tty Sanity Checking N N N N Y Y N N
Can cope with large argument lists Y N Y Y Y Y Y Y
Has non-interactive startup file N Y Y(7) Y(7) Y Y N N
Has non-login startup file N Y Y(7) Y Y Y N N
Can avoid user startup files N Y N Y N Y Y Y
Can specify startup file N N Y Y N N N N
Low level command redefinition N N N N N N N Y
Has anonymous functions N N N N N N Y Y
List Variables N Y Y N Y Y Y Y
Full signal trap handling Y N Y Y N Y Y Y
File no clobber ability N Y Y Y Y Y N F
Local variables N N Y Y N Y Y Y
Lexically scoped variables N N N N N N N Y
Exceptions N N N N N N N Y

Linux Introduction | RHCSA Tutorial | Tech Arkit





     UNIX is the first Operating system in the world, developed by Kem Thompson and Dennis Ritchie in 1969 at Bell Lab by AT&T Company

Distributions: Overview of various Linux distributions (Ubuntu, Fedora, CentOS, Debian, etc.) that build upon the Linux kernel.
  •             IBM    :           AIX
  •             SGI     :           IRIX
  •             Sun     :           Solaris
  • Free software foundation organization, they start a project by name GNU. The main aim of this project is to develop such an operating system that can run on any platform. 
  • In 1991, a student Linuz Torvalds developed a kernel named Linux’s kernel plus GNU application called Linux operating system.
  • Linux is an open source technology.
  • Different companies that provide Linux in Market are Redhat, SuSe, Scientific, Centos, and Knoppix etc.

Features:

Ø  Linux is the fastest Operating system in the world. It runs 2 to 3 times fast than windows OS.
Ø  Linux is the much secured OS because there is no any problem of virus.
Ø  Linux file format is text format and windows file format is binary format.
Ø  Linux is a very reliable OS because the kernel of Linux is very stable as compare to windows kernel not crashed easily.
Ø  Kernel of Linux is very small in size it can be stored in floppy.
Ø  Linux uses the x-Window system which is advanced network windowing system. Using this system we can display output of any workstation monitor attached in the network.

Advantages:

Ø  Virus Proof
Ø  Crash Proof
Ø  Economical
Ø  Multiuser, Multi-Tasking and Multiprocessing capacity

Login Modes:


Two modes:  

1. Text mode (CLI)   - All the commands can be executed   
2. Graphical Mode (GUI)

Open Source

       The idea behind Open Source software is rather simple: when programmers can read, distribute and change code, the code will mature. People can adapt it, fix it, debug it, and they can do it at a speed that dwarfs the performance of software developers at conventional companies. This software will be more flexible and of a better quality than software that has been developed using the conventional channels, because more people have tested it in more different conditions than the closed software developer ever can.

        The Open Source initiative started to make this clear to the commercial world, and very slowly, commercial vendors are starting to see the point. While lots of academics and technical people have already been convinced for 20 years now that this is the way to go, commercial vendors needed applications like the Internet to make them realize they can profit from Open Source. Now Linux has grown past the stage where it was almost exclusively an academic system, useful only to a handful of people with a technical background. Now Linux provides more than the operating system: there is an entire infrastructure supporting the chain of effort of creating an operating system, of making and testing programs for it, of bringing everything to the users, of supplying maintenance, updates and support and customizations, etcetera. Today, Linux is ready to accept the challenge of a fast-changing world.


 Please write your valuable comments...

Reset MySql Server root user password

RESET MYSQL ROOT PASSWORD PROCESS

 You have to have the sudo/root access to the server

Run the below command to reset the password.

Step 1. STOP the mysql daemon service using "service mysqld stop" "sudo /sbin/service mysqld stop"

Step 2.   mysqld_safe --skip--grant-tables

Step 3. mysql -u root

Step 4.  
mysql> UPDATE mysql.user SET Password=PASSWORD('mysql') WHERE User='root';
Query OK, 2 rows affected (0.00 sec)
Rows matched: 3  Changed: 2  Warnings: 0

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

Add one more user

mysql> create user 'aravi'@'localhost' IDENTIFIED BY 'mysql';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'aravi'@'localhost'
    -> WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)

mysql> show grants for 'aravi'@'localhost';
+----------------------------------------------------------------------------------------------------------------+
| Grants for aravi@localhost                                                                                     |
+----------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'aravi'@'localhost' IDENTIFIED BY PASSWORD '68d4f47c49a579c9' WITH GRANT OPTION |
+----------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> quit

Password reset for root user is done. Now restart the mysqld service.

sudo /sbin/service mysqld restart
service mysqld restart

Enjoy.......

Linux Architecture




Kernel: It is a program. Kernel is a Core component of operating system, interacts directly with hardware and provides low level services to upper layer components.
Shell: An interface to kernel, hiding complexity of kernel’s functions from users. Takes commands from user and executes kernel’s functions.
User Interface: In information technology, the user interface (UI) is everything designed into an information device with which a human being may interact. Two types CLI (Command line interface) and GUI (Graphical User Interface).
System Library - System libraries are special functions or programs using which application programs or system utilities accesses Kernel's features. These libraries implements most of the functionality of the operating system and do not requires kernel module's code access rights.
System Utility - System Utility programs are responsible to do specialized, individual level tasks.

Kernel Mode vs User Mode


        Kernel component code executes in a special privileged mode called kernel mode with full access to all resources of the computer. This code represents a single process, executes in single address space and do not require any context switch and hence is very efficient and fast. Kernel runs each processes and provides system services to processes, provides protected access to hardwares to processes.

        Support code which is not required to run in kernel mode is in System Library. User programs and other system programs works in User Mode which has no access to system hardwares and kernel code. User programs/ utilities use System libraries to access Kernel functions to get system's low level tasks.
Basic Features

Following are some of the important features of Linux Operating System.

    Portable - Portability means softwares can works on different types of hardwares in same way.Linux kernel and application programs supports their installation on any kind of hardware platform.

    Open Source - Linux source code is freely available and it is community based development project. Multiple teams works in collaboration to enhance the capability of Linux operating system and it is continuously evolving.

    Multi-User - Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time.

    Multiprogramming - Linux is a multiprogramming system means multiple applications can run at same time.

    Hierarchical File System - Linux provides a standard file structure in which system files/ user files are arranged.

    Shell - Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used to do various types of operations, call application programs etc.

    Security - Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data.


 

Linux System Architecture is consists of following layers

    Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).

    Kernel - Core component of Operating System, interacts directly with hardware, provides low level services to upper layer components.

    Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes commands from user and executes kernel's functions.

    Utilities - Utility programs giving user most of the functionalities of an operating systems.

Windows Vs Linux


Windows Vs Linux

                                Windows
                                      Linux
    • It is a proprietary software everything need to buy
    • It is an open source software everything is free
    • Less Secure
    • More Secure
    • More costly
    • Less Cost compare to windows
    • Chance to get a carpal tunnel syndrome
    • There is no chance to get carpal tunnel syndrome
    • Developed by Microsoft corporation
    • Developed by Linus Torvalds
    • Options need to select
    • You can develop anything as per your requirement
    • Kernel is not editable
    • Kernel is editable

NagiosXI Login Notification

If you want to monitor who is logged in to the NagiosXI web console then schedule this below script in your crontab it will check for User Activities and it will send you a Mail alert.

#!/bin/bash
# Purpose: To get alerts when user is logged in to Nagiosxi console
# Author: Ankam Ravi Kumar
# Date: 13-Feb-2015
# NagiosXI Console Login check Script START
DT=`date +%Y-%m-%d`
psql -U nagiosxi -d nagiosxi -t -A -F"," -c "select * from xi_auditlog;" > /tmp/auditlog.txt
cat /tmp/auditlog.txt |grep $DT > /tmp/today.txt
EPOCTIME=`cat /tmp/today.txt |awk -F, '{print $2}' |tail -1`
ENDTIME=$(date +%s)
STARTIME=$(date +%s -d"$EPOCTIME")
echo $((ENDTIME-STARTIME)) | awk '{print int($1/60)}' > /tmp/value1
count=`cat /tmp/value1`
if [ $count -lt 8 ]
then
        cat /tmp/auditlog.txt |grep $DT |tail -1 > /tmp/mail
        mail -s "NagiosXI Login ALERT: User `cat /tmp/mail | awk -F, '{print $4}'` `cat /tmp/mail | awk -F, '{print $6}'` to `hostname`" aravikumar48@gmail.com < /tmp/mail
fi
rm -rf /tmp/auditlog.txt /tmp/today.txt /tmp/value1 /tmp/mail
#END


FS Monitoring

::::::::::::: Script to Monitor File system :::::::::::::::

No need to configure any mail server just send a mail/messages using sendEmail..

Download sendEmail Program from below link

http://caspian.dotconf.net/menu/Software/SendEmail/

------------------
Installation
------------------

SendEmail is a perl script/program, and only needs to be copied to a directory
in your path to make it accessible.  Most likely the following steps will
be sufficient:

1) Extract the package
    tar -zxvf sendEmail-v1.XX.tar.gz

2) Copy the sendEmail script to /usr/local/bin
    cp -a sendEmail-v1.XX/sendEmail /usr/local/bin

3) Make sure its executable
    chmod +x /usr/local/bin/sendEmail

4) Run it
    sendEmail
      or
    /usr/local/bin/sendEmail

NOTES:
  * Running sendEmail without any arguments will produce a usage summary.
  * SendEmail is written in Perl, so no compilation is needed.
  * On a Unix/Linux OS if your perl binary is not installed at /usr/bin/perl
    you may need to edit the first line of the script accordingly.

#------------------------------------------------------------------
# Script Starts................
#------------------------------------------------------------------
#!/bin/bash
# Purpose: Disk Space Monitoring
# Author: Ravi Kumar
# Script Start
# Variables #
MAILLIST="aravikumar48@gmail.com"
CRITICAL=95
HOSTNAME=`hostname`
MAIL=sendEmail
PERCENTAGE=`df -hP | egrep '^/dev/' | awk '{ print $6 "_:_" $5 }' | awk -F"_:_" '{ print $2 }' | cut -d'%' -f1 | head -n 1`
PERCENTAGE1=`df -hP | egrep '^/dev/' | awk '{ print $6 "_:_" $5 }' | awk -F"_:_" '{ print $2 }' | cut -d'%' -f1 | tail -1`
BODY=`df -hP | egrep '^/dev/'`

if [ $PERCENTAGE -ge $CRITICAL ];
then
        sendEmail -f alert@gmail.com -t $MAILLIST -u "$HOSTNAME - File System is CRITICAL $PERCENTAGE%" -m $BODY -s MAIL-EXCHANGE.com
elif [ $PERCENTAGE1 -ge $CRITICAL ];
then
        sendEmail -f alert@gmail.com -t $MAILLIST -u "$HOSTNAME - File System is CRITICAL $PERCENTAGE1%" -m $BODY -s MAIL-EXCHANGE.com
else
        echo ""
fi
#END