100 Linux Interview Questions

1. Give a few commands for performance monitoring and tuning.

Ans : Below are the commands for performance monitoring and tuning: 
      1.	uptime
      2.	top 
      3.	sar 
      4.	iostat 
      5.	mpstat 
      6.	free  
      7.	dstat

2.What is shell in Linux?

Ans: For executing any commands user uses a program known as the shell. Linux shell
is basically a user interface used for executing the commands and communicating 
with Linux operating system. Shell does not use the kernel to execute certain
programs, create files, etc. There are several shell available with Linux which
includes the following:
•	BASH (Bourne Again SHell)
•	CSH ( C Shell)
•	KSH ( Korn Shell)
•	TCSH
•	Nologin
There are basically two types of Shell commands Built-in shell commands.
These commands are called from the shell and executed directly within the shell.
Examples: ‘pwd’, ’help’, ’type’,’set’, etc. 
External/ Linux commands: These commands are totally shell independent, have their 
own binary and are located in the file system.

3. What is the path for network config file?

Ans: /etc/sysconfig/network-scripts

4. Set never expiring password.

Ans: # chage -E never username

5. Command to check PCI devices.

Ans: # lspci

6. What are the port numbers of SSH, FTP, HTTP and HTTPS?

Ans: ssh-22, ftp - 20/21, http-80, https-443.

7. How to check the NFS version of the NFS server from NFS client?

Ans: # nfsstat -c

8. Command to collect detailed info about network/hardware?

Ans : Below commands are helpful in collecting the details of the network/hardware:
1. dmidecode
2. sysreport

9. How to check the kernel version.

Ans: See below commands:
1. uname -v (version date line),
2. uname -r(kernel release),
3. uname -a(give complete information architecture etc)

10. Which file defines the attributes like UI, password expiry, home directory creation or deletion while adding a user?

Ans: /etc/login.defs

11. What are passwd and shadow file permission in numbers.

Ans : Below are the default permissions of these files:
passwd - 644
shadow - 000

12. List block devices in Linux.

Ans: lsblk (list block devices)
[[email protected] ~]# lsblk 
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0   20G  0 disk 
├─sda1   8:1    0  300M  0 part /boot
├─sda2   8:2    0    2G  0 part [SWAP]
└─sda3   8:3    0 17.7G  0 part /
sr0     11:0    1 1024M  0 rom  

13. List total CPU cores and total CPU processors in a single command.

Ans: # cat /proc/cpuinfo | egrep 'processor|core id'

14. How to check current output of a log file.

Ans: tail -f <log-file-name>
Example: tail -f /var/log/messages

15. How to see first N lines of a file.

Ans:  # head -n filename

16. How to see last n lines of a file.

Ans: # tail -n filename

17. How to check background process IDs.

Ans: # jobs -l

18. How to bring back background processes.

Ans: # bg

19. How to send a process in background?

Ans: Adding & at the last of the command.

20. How to create nested directories in a single command.

Ans:  Use -p option when creating directories.
Example:
# mkdir -p /new/directory/technicalmint

21. Run a command that shows all lines except any lines starting with a character # in a file ?

Ans: # cat /etc/crontab  | grep -v ^#

22. Which 2 files contain default values when creating a user with useradd command ?

Ans: /etc/default/useradd & /etc/login.defs

23. What is the command to create a user with a pre-defined uid, shell and home directory?

Ans: # useradd -m -d /home/user -s /bin/bash -u 9000 username

24. How to delete a user with his home directory?

Ans: # userdel -r user

25. How to create a user specifying a primary/secondary group?

Ans: # useradd user -g primary -G other groups

26. How to change primary group for any user?

Ans: # usermod -g primarygroup user

27.  How to make sudo access without asking for password?

Ans: Make below changes in sudoers file for the sudo user:
# vi /etc/sudoers
   user ALL=(ALL) NOPASSWD:ALL
# sudo -l ---> List what command can run

28. How to view the user’s login and logout details?

Ans: # last user

29. How to lock and unlock the user account?

Ans: 
# passwd -l user       -->  To lock a user
# passwd -u user      -->  To unlock a user

30.What is the command to view and change the expiry date for any user?

Ans: Below are the commands to view and change the expiry date for a user:
     # chage -l user
     # chage -E YYYY-MM-DD user

31. How will you change the priority of a process?

Ans: Change the nice value of the process:
      e.g. # nice -10 perl test.pl 

32. How will you kill all sub processes of a master process ID or keyword?

Ans: # killall process_name

33. What system calls happen for KILL and what’s difference between using -9?

Ans: Default it's -15 - SIGTERM, -9 is SIGKILL

34. What is Process ID 0 and 1 in linux?

Ans: There are two tasks with especially distinguished process IDs: swapper or 
sched has process ID 0 and is responsible for paging, and is actually part of the
kernel rather than a normal user-mode process.

Process ID 1 is usually the init process primarily responsible for starting and 
shutting down the system.

35. How is load average calculated?

Ans: There isn't really a maximum load average. It can increase based on other 
resources besides pure CPU processing such as waiting for IO.
But you can expect to see 1 load average per core on a fully utilized system when
it is CPU bound.
i.e.    4 core = 4 load avg

36. What does sar provide? Where are sar logs stored?

Ans: The sar command collects, reports or saves system activity information. It logs
and evaluates a variety of information regarding system activity. With performance
problems, sar also permits retroactive analysis of the load values for various 
sub-systems (CPUs, memory, disks, interrupts, network interfaces, etc). By default, 
logs of sar command are located at /var/log/sa/sadd file, where dd  indicates the 
current day.

37. How to check Memory stats and CPU stats?

Ans: Using ‘free’ & ‘vmstat’ command, we can display the physical and virtual 
memory statistics, respectively. With the help of ‘sar’ command, we can see the 
CPU utilization & other stats.

38. How to change the IP of a server?

Ans: Change IP address temporarily:
  # ifconfig eth0 192.168.x.x netmask 255.255.255.0 up
  # route add default gw 192.168.x.y eth0   --> To change the default gateway
We can also configure IP Address using Configuration file:
  # vi /etc/sysconfig/network-scripts/ifcfg-eth0
         DEVICE=eth0
         TYPE=Ethernet
         ONBOOT=yes
         NM_CONTROLLED=no
         BOOTPROTO=none
         IPADDR=192.168.x.x
         GATEWAY=192.168.x.y
         NETMASK=255.255.255.0

39. How will you check on your server or system if device-mapper is installed or not?

Ans: Check the following file:
  # cat /proc/misc
If this file contains “device-mapper” term it means device mapper is installed on
your system.

40. What are the fields of /etc/passwd file?

Ans: # cat /etc/passwd
technicalmint:x:1000:1000:kellstech:/home/kellstech:/bin/bash
The above fieldsa re explained below:
<user>:<password>:<uid>:<gid>:<comment>:<home directory>:<shell>

41. What is the difference between .bash_profile and .bashrc?

Ans: When you login to a linux machine .bash_profile file is executed but
if you are already logged in and you open a new terminal then .bashrc file
is executed.

42. What are the details you get with finger command ?

Ans: finger command is user lookup program: 
# finger <username>
Login	Name	Tty	    Idle	 Login	Time	Office	 Office	  Phone	Host
Root	root	pts/0		       May 23 	    13:22            (192.168.21.1)
Note: You can use -s with finger command to get the output in format.

43. Name 3 files which are automatically created inside any user’s home directory when a user is added.

Ans: Below the the 3 files:
    .bashrc
    .bash_profile
    .bash_history

44. What is the command to view all logged in users?

Ans: w

45. How to view all messages generated by the system since the last reboot on RHEL7?

Ans: 
# journalctl
# journalctl | grep ssh
Use journalctl to view the systemd journal. The boot process, kernel and
all systemd services put messages into the systemd journal.

46. What are the 2 different ways of showing the kernel messages?

Ans: 
1. dmesg
2. journalctl -k

47. How can you continuously monitor logs as they come in?

Ans: 
# journalctl -f
# tail -f /var/log/messages

48. Where can you find messages related to the installation of linux?

Ans: 
Config file - anaconda.cfg
Log file - /var/log/anaconda/anaconda.log

49. To improve performance, how can you safely set the limit of process for the super user to be unlimited?

Ans: ulimit -u unlimited

50. Where can you set the resource limits for users logged in via PAM?

Ans: /etc/security/limits.conf
     <domain>      <type>      <item>         <value>
     #@student      hard         nproc              20
     #@faculty        soft          nproc              20
A hard limit is the maximum allowed to a user, set by the superuser/root. 
This value is set in the file /etc/security/limits.conf. Think of it as an upper
bound or ceiling or roof.
A soft limit is the effective value right now for that user. The user can increase
the soft limit on their own in times of needing more resources but cannot set the
soft limit higher than the hard limit.

51. How to check ulimit for a user?

Ans: ulimit –a

52. How to check and increase the limit of opened files in linux?

Ans: cat /proc/sys/fs/file-max
To change:
  # vim /etc/sysctl.conf
     (add line)
     2- fs.file-max=98321
     3- sysctl -p
   # cat /proc/sys/fs/file-max

53. How to view run time kernel parameter?

Ans: sysctl -a

54. How to change runtime kernel parameter for maximum shared segment size in bytes?

Ans: Append "kernel.shmmax = 18446744073692774399" to /etc/sysctl.conf
i.e. # echo "kernel.shmmax = 18446744073692774399" >> /etc/sysctl.conf
      # sysctl -p

55. How to view boot time parameters and which file is modified to change these parameters?

Ans: 
To view boot time parameters run: # cat /proc/cmdline
These are supplied /boot/grub2/grub.cfg

56. How can you get the physical and virtual memory statistics?

Ans: 
# free -m or g
# vmstat -a (active and inactive memory), -d disk stats, -t time

57. How to check CPU utilisation and other statistics?

Ans: Use sar command which is part of sysstat package
      # sar -u (shows cpu utilization stats for the current day)
      # sar -u 2 3
      # sar -r (memory utilization)
      # sar -S (swap space)
      # sar -q -f /var/log/sa/sa22  
where -q  --> report load avg and queue lenght  and -f --> Extract records from filename.
      # sar -q -s 22:00:00 -e 00:00:00 -f /var/log/sa/sa10
The -s argument is for the starting time and -e for the ending time. 
In both cases you specify the time in 24 hour format: 

58. How to list all open files by specified user?

Ans: 
    # lsof -u user
    # lsof -c cat     --> list all files opened by particular command. 
                           --> List opened files based on process names starting with
    # lsof -i :22                  --> list all network connections by port 22.
    # lsof /var/log/syslog   --> list processes which opened a specific file
    # lsof +D /var/log/        --> List opened files under a directory
    # lsof -u ^technicalmint --> exclude any particular user.
    # lsof -p 1753              --> list of open files by specific process

59. Run a command that shows all lines except any lines starting with a character # or blank line in a file?

Ans: # cat /etc/vsftpd/vsftpd.conf  | grep -v ^# | grep -v ^$

60. How to create users on a Linux system and send them to a file?

Ans: 
# useradd username
# cut -d: -f1 /etc/passwd > file.txt

61. How to broadcast a message to all logged in users?

Ans: # wall -n "server is going down for maintainance in 5 minutes"

62. How to create a user with no login access?

Ans: useradd -s /sbin/nologin technicalmint

63. How to schedule a server reboot in 15 minutes?

Ans: shutdown -r +15 or now or 23:00:05

64. How to find disk usage by the largest directories?

Ans: 
# du -S | sort -n  
Where -S --> Separate directory, for directories do not include size of subdirectories
# du -sm * | sort -nr 
Where 
-m = like --block-size=1M
-s = summarize

65. What necessary steps should be taken to enhance the security of a server after the initial install?

Ans: 
1. Package should be the latest version
    # yum update 
2. Any unnecessary service and daemons should be disabled.
3. Setup a complex password policy, apply the company policies.
    # /etc/pam.d this is where the most of the settings are.
4. Disable root login /etc/sshd/sshd_config

66. How to disable ping/icmp ?

Ans: echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all    --> Temporary
For permanent --> edit the sysctl.conf and 
add net.ipv4.icmp_echo_ignore_all = 1
# sysctl -p

67. How to check if a port is listening?

Ans: # netstat -anp or tulnp | grep <port number>

68. How to find all files in a directory with specified (755) permission?

Ans: # find /var/log -perm 755 -ls

69. How to allow only specific users to ssh your Linux server?

Ans: 
# vim /etc/ssh/sshd_config
     AllowUsers user1 user2 
Restart the sshd service after making above changes
# systemctl restart sshd
MaxSession in ssh is 10 by default.

70. What is scp in relation to ssh and how is it used?

Ans: Secure copy - It uses ssh for data transfer & uses the same authentication
and provides the same security as ssh. It is basically used to copy data from one
server to another.
Example:
# scp <file-name> [email protected]<server-ip>:<destination path>
# ssh -V -->> to check the version

71. How to enable passwordless ssh authentication in linux?

Ans: 
# ssh-keygen
# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]<server-ip>

72. What is the difference between authorized_keys and known_hosts file for SSH?

Ans: 
1. ~/.ssh/authorized_keys: Holds a list of authorized public keys for servers. 
    When the client connects to a server, the server authenticates the client by
    checking its signed public key stored within this file.
2. ~/.ssh/known_hosts: Contains DSA host keys of SSH servers accessed by the user. 
    This file is very important for ensuring that the SSH client is connecting the
    correct SSH server.

73. How to extend swap space? 500M to 1G.

Ans: 
# lvextend -L 1G /dev/vg01/swap
# swapon -s    --> current status
# swapoff -v /dev/vg01/swap
# mkswap /dev/vg01/swap
# swapon -va

74.  How to extend a logical volume?

Ans: 
# lvextend -L +100M /dev/new_vg/test_lv
# resize2fs /dev/new_vg/test_lv

75. How to create a logical volume?

Ans: 
# lvreate -n test_lv -L 500M new_vg
# mkfs.ext4 /dev/new_vg/test_lv
# df -h
# mkdir /test
# mount /dev/new_vg/test_lv /test
# vim /etc/fstab
# /dev/new_vg/test_lv /test ext4 defaults 0 0

76. How to create volume group?

Ans: 
# pvcreate /dev/sdb -->> to create physical volume
# vgcreate new_vg /dev/sdb

77. Increase the logical volume on the fly?

Ans: # lvextend -L 10G /dev/new_vg/test_lv

78. How to reduce the logical volume? Is it possible to reduce it on the fly?

Ans: No, we can't reduce logical volume on the fly.
Steps:
1. Unmount the filesystem
2. Run e2fsck on the volume device
3. Reduce the logical volume using lvreduce
4. Reduce the filesystem using resize2fs
5. Mount the filesystem back.

Example:
# umount /test
# e2fsck -f /dev/new_vg/test_lv
pass 1: checking inodes, blocks, and sizes
pass 2: checking directory structure
pass 3: checking directory connectivity
pass 4: checking reference counts
pass 5: checking group summary information
# resize2fs /dev/new_vg/test_lv
# lvreduce -L 400M /dev/new_vg/test_lv
# mount /dev/new_vg/test_lv /test

79. How to stop/deactivate the logical volume?

Ans: 
# lvchange -an /dev/new_vg/test_lv   --> to disable
# lvchange -ay /dev/new_vg/test_lv   --> to enable
# vgchange -an new_vg                     --> to disable vg
# vgchnage -ay new_vg                     --> to enable vg

80. How to find files that are over 100mb in size?

Ans: # find / -size +100M

81. How to find files not accessed over 3 days?

Ans: # find / -type f -atime +3

82. Difference between /sbin/nologin and /bin/false?

Ans: When /sbin/nologin is set as the shell and if a user with that shell logs in,
they'll get a polite message saying 'This account is currently not available.'
This message can be changed with the file /etc/nologin.txt./bin/false. It is
just a binary that immediately exits, returning false when it's called, so when
someone who has false as shell logs in, they're immediately logged out when 
false exits. Setting the shell to /bin/true has the same effect of not allowing 
someone to log in but false is probably used as a convention over true since it's 
much better at conveying the concept that person doesn't have a shell.

83. How to remove files older than 7 days by creating cron job to run every night?

Ans: 
# find /var/log/secure -type f -mtime +7 -exec rm -rf {} \;
# crontab -l
# cat /etc/crontab
# crontab -e
0 2 * * * /usr/bin/find var/log/secure -type f -mtime +7 -exec rm -rf {} \;
{} indicates (contains) the result(s) from the find expression i.e. find . -name 
"FILE-TO-FIND" in this case. Note that empty curly braces {} have no special meaning 
to shell so we can get away without escaping {} As bash treats; as end of a command, 
we need to escape this with \ i.e. \; so that it can be parsed by -exec not by bash itself.

84. What is the DNS record for IPv6?

Ans: An AAAA (pronounced quad A) record is a DNS record that maps to an IPv6 address.

85. What is the Equivalent of 127.0.0.1 in IPv6?

Ans: ::1 or in longhand, 0:0:0:0:0:0:0:1 is the loopback address in the IPv6 protocol.

86. What last command does? How to check if the system is rebooted at last?

Ans: last command searches back through the file /var/log/wtmp and displays a list
of all users logged in (and out) since that file was created. Name of users and tty's 
can be given in which case last command will show only those entries matching the 
arguments. Command to check last reboot: 
# last reboot

87. How to print the 3rd column of a file?

Ans: # awk '{ print $3 }' filename

88. What is $# in bash script?

Ans: `$` refer to `value of` and `#` refer to `number of (or) total number`
So together, `$#` refer to “The value of the total number of command 
line arguments passed.”

89. How to check if a new disk is added and how to discover it?

Ans: Run below command to discover the new disk.
# echo "- - -" > /sys/class/scsi_host/hostX/scan
   where hostX is host 0, host1, host2 etc.

90. What does “- – -” in echo command to rescan the drive stands for?

Ans: The three values stand for Channel, SCSI target ID, and LUN. 
The dashes act as wildcards meaning "rescan everything".

91. If a non-root user cannot edit passwd file then how shadow file gets updated when a non-root user changes its password?

Ans: The passwd command has SUID bit enabled. When a normal user 
changes his password this script update few system files like /etc/shadow
which can't be updated by non-root account. So that passwd command 
process always run with root user rights.
# ls -l `which passwd`
-rwsr-xr-x. 1 root root 27832 Jun 9 2014 /usr/bin/passwd

92. What would happen if I typed in mv * then hit enter at a shell?

Ans: If the last file in the directory is a directory itself it will move all the 
files into that directory. 
If the last file in the directory is a file you get the error returned that the 
last argument has to be a directory and nothing is done.

93. How is RCA sent and what logs do you send for RCA? What logs should you send for crashing of the system to RHEL and SLES team?

Ans: We may send them kdump if it’s configured and we usually send heap
and thread dumps and have a discussion with the respective team over the 
call and send them the details whatever they ask for.

94. What is the differences between tcp and udp for NAT?

Ans: UDP allows you to traverse some NAT devices without using port 
forwarding using a technique called UDP hole punching.

95. Find a file with 0 bytes in a partition directory without ls command?

Ans: # find / -size 0

96. How to find files in a directory which are accessed 30 days ago.

Ans: # find / -type f -atime 30

97. How to find files in a directory which are modified 30 days ago.

Ans: # find / -type f -mtime 30

98. Difference between Swapping and Paging?

Ans: In paging, blocks of equal size (called pages) are transferred between
the main memory and a secondary storage device, while in swapping, all the 
segments belonging to a process will be moved back and forth between the main 
memory and a secondary storage device. Since paging allows moving pages 
(it could be a part of the address space of a process), it is more flexible than
swapping. Since, paging only moves pages (unlike swapping, which move a 
whole process), paging would allow more processes to reside on the main memory
at the same time, when compared with a swapping system. Swapping is more suitable 
when running heavier workloads.

99. User is unable to run cronjob. How will you troubleshoot?

Ans: Check cron.deny file, if that user is there then remove it and try to run the
cron job. Look at the logs; cron logs its actions via syslog which 
(depending on your setup) often go to /var/log/cron or /var/log/syslog.
If required you can filter the cron statements with e.g.
# grep CRON /var/log/syslog

100. What are the basic commands of user management?

Ans: Below are the basic commands of user management:
    • # last
    • # chage
    • # chsh
    • # lsof
    • # chown
    • # chmod
    • # useradd
    • # userdel
    • # newusers, etc.

That’s it. Please let us know your opinion using the comment section. We are working on creating another article in continuation to this one and will be publishing that soon. Kindly subscribe us to get the notifications for the new articles. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *