Basic Linux Commands For Interview
Basic Linux Commands For Interview
Basic Linux Commands For Interview
questions
Aug 18, 2011
mkdir — For creating folders( use -p option to create multiple folders at a time)
ls –List folders/files( check what ls -1 do)
top — To monitor system activities
lsof –To check whats happening on the server and which process open which file.
netstat -tcp –Gives you complete picture about network connection details.
vnstat –Gives you Network band width statics
sh –For running shell scripts
history –For monitoring the commands executed by users
cd –For changing directories
vi –-For editing configuration files.
chmod –To change permissions of folders and files.
mount –For mounting formated partitions.
service –For start/restart/stop a service.
chkconfig –For permanent on/off a service.
fdisk -l –To list all the partitions
This is my own list, you can have your list.
6)What is the difference between man, info, whatis commands and a –help option
for a command?
whatis gives you one line answer.
–help option for a command gives you one line answers for each option supported by a
command
man command gives you medium size info.
info command gives full details about a commands, lots and lots of information about a
command.
Please share your interview questions with us, we post them here so that others can get
help from this.
A process is any piece of software that is running on a computer. For example, your anti-virus software runs
in the background as a process, which was automatically started when the computer booted. Some processes
start when your computer boots, others are started manually when needed.
Some processes are services that publish methods to access them, so other programs can call them as
needed. Printing services would be an example of a service type of process, where your email program can
just call the print services process to say it wants to print, and the service does the actual work.
3. My clients are getting services from servers but how to know which client is using which service. is there
any files to keep information about these? Clients used ftp, nis, samba, apache, squid, nfs and mail services
how to know how many users got service from server side with date, time and client system ip?
4. How to FTP user access other directory except his own home directory?
vim /etc/vsftpd/vsftpd.conf
Chroot_list_enable=yes
Selinux
Firewall
iptables
Tcp-wrappers
A firewall should be able to filter packets (drop/pass them) based on certain rules specified by the user. The
rules may be used to identify an incoming packet to the computer or outgoing packet from the computer, it
can be based on target port number/ip add , traffic from a particular Network card etc…
The firewall rules can be in a tabular form (saved on the disk) from where the firewall software can read them
and implement it. iptables firewall on Linux is a great example
7. What is a command to display top 10 users who are using huge space?
vim /etc/sysctl.conf
net.ipv4.ip_forward=1
system-config-network
eth0 192.168.1.120 eth0:1 172.24.0.1
255.255.255.0 255.255.0.0
172.24.0.1 192.168.1.120
10. What is the UID and GID of root user? Can a normal user can change the ownership of a file? What is
the command to change ownership of a file?
The root UID/GID is 0 (zero). Which is why he can able to intervene in all normal users files even though he
don’t had permission. A normal user will don’t have the permission to change ownership of file. The
command to change ownership is < chown user.user file >
Ext3 is a tiny bit slower than ext2 is, but it holds tremendous advantages. There is really only one difference
between ext2 and ext3, and that is that ext3 uses a journal to prevent filesystem corruption in the case of an
unclean shutdown (ie. before the filesystem is synced to disk). That makes ext3 a bit slower than ext2 since
all metadata changes are written to the journal, and then flushed to disk, but on the other hand you don’t
risk having the entire filesystem destroyed at power failure or if an unwitted person turns the computer off
uncleanly. You don’t have to check the filesystem after an unclean shutdown either. Ext3 has three levels of
journalling. Metadata (ie. internal filesystem structures) are always journalled, so that the filesystem itself is
never corrupted. How ordinary data is written to the file system is controllable, though. The default option is
the “ordered” mode, which causes file contents to be written to the filesystem before metadata is even
committed to the journal. The highest reliable mode is called the “journal” mode, which causes file data to be
committed to the journal before it is flushed to its final place, like the metadata. The least reliable mode, but
rumoured to be the fastest, is called the “writeback” mode, which makes no promises at all regarding the
consistency of file data. Only metadata is output reliably in writeback mode. So as for anything else, it’s
mainly a matter of priority. If you don’t want ultimate speed, go with ext3. If you need the highest speed that
is theoratically aquirable though, then go with ext2. For that to be effective you’ll probably need a really
advanced hard drive controller, though.
12. As the system administrator you need to review Bob’s cronjobs. What command would you use?
gpasswd –r groupname
RAID level 0
RAID level RAID level 1
RAID level 2
RAID level 3
RAID level 4
RAID level 5
RAID level 6
RAID level 10
RAID level 50
Nslookup is a program used to find information about internet Domain Name server.
The two modes of nslookup are: Interactive and non-interactive.
Using ‘interactive mode’ user can query the name servers for the information pertaining to hosts and
domains.
Using ‘non-interactive mode’ the user can just print the name and requested information of a host.
3.TCP gurantees that as long as you have a connection data sent will arrive at the destination, UDP provides
not guarantee delivery.
4.UDP is faster for sending small amounts of data since no connection setup is required, the data can be sent
in less time then it takes for TCP to establish a connection.
Need to run fsck [file system consistency check] command to check file system consistency and repair a
Linux / UNIX file system.
fsck
vi /etc/samba/smb.conf
smbpasswd -a username
smbpasswd -e username
The inode contains the metadata about files. Among the data stored in the inode is
File type
File permissions
Link count
User ID number of the file owner and the group ID number of the associated group
df -h
nmap -A –v 192.168.1.100
netstat –an
A system call is the mechanism used by an application program to request service from the operating system.
On Unix-based and POSIX-based systems, popular system calls are open, read, write, close, wait, exec, fork,
exit, and kill. Many of today’s operating systems have hundreds of system calls. For example, Linux has 319
different system calls. FreeBSD has about the same (almost 330). Tools such as strace and truss report the
system calls made by a running process.
Basic Questions
1. What is initrd image and what is its function in the linux booting
process ?
The initial RAM disk (initrd) is an initial root file system that is mounted prior to when the real root file
system is available.The initrd is bound to the kernel and loaded as part of the kernel boot procedure.
The kernel then mounts this initrd as part of the two-stage boot process to load the modules to make
the real file systems available and get at the real root file system. Thus initrd image plays a vital role
in linux booting process.
SUID : If setuid bit is set, when the file is executed by a user, the process will have the same rights
as the owner of the file being executed.
SGID : Same as above, but inherits group previleges of the file on execution, not user previleges.
Similar way when you create a file within directory,it will inherit the group ownership of the
directories.
Sticky bit : Sticky bit was used on executables in linux so that they would remain in the memory
more time after the initial execution, hoping they would be needed in the near future. But mainly it is
on folders, to imply that a file or folder created inside a stickybit enabled folder could only be deleted
by the owner. A very good implementation of sticky bit is /tmp ,where every user has write
permission but only users who own a file can delete them.
c) Removing the original file that your hard link points to does not remove the hardlink itself; the
hardlink still provides the content of the underlying file.
d) If you remove the hard link or the symlink itself, the original file will stay intact.
e) Removing the original file does not remove the attached symbolic link or symlink, but without the
original file, the symlink is useless
Usage :
# mutt -s "Subject of Mail" -a "path of attachment file" "email address of recipient" < "message text
containing body of the message"
6. What are the run levels in linux and how to change them ?
A run level is a state of init and the whole system that defines what system services are operating
and they are identified by numbers.There are 7 different run levels present (run level 0-6) in Linux
system for different purpose. The descriptions are given below.
To change the run level, edit the file “/etc/inittab” and change initdefault entry ( id:5:initdefault:). If we
want to change the run level on the fly, it can be done using ‘init’ command.
For example, when we type ‘init 3' in the commandline , this will move the system from current
runlevel to runlevl 3. Current level can be listed by typing the command 'who -r'
8. What is SeLinux?
SELinux is an acronym for Security-enhanced Linux. It is an access control implementation and
security feature for the Linux kernel. It is designed to protect the server against misconfigurations
and/or compromised daemons. It put limits and instructs server daemons or programs what files they
can access and what actions they can take by defining a security policy.
******
||||||
| | | | | +-- Year (range: 1900-3000)
| | | | +---- Day of the Week (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month (range: 1-31)
| +---------- Hour (range: 0-23)
+------------ Minute (range: 0-59)
The following will show the name of each object in the current directory together with its inode
number:
# ls -i
The avialble number inodes in a filesystem can be found using the below command :
# df -i
The other way we can get the inode details of a file by using the stat commmand.
Usage : # stat <file name>
Example :
Apart from the above basic questions, be prepared for answers for the below questions
4. How to find kernel / OS version and its supported bit (32/64) version ?
8. Have a look on ps, top, grep, find, awk and dmesg commands ?
n IP-based virtual hosting, we can run more than one web site on the same server machine, but
each web site has its own IP address while In Name-based virtual hosting, we host multiple websites
on the same IP address. But for this to succeed, you have to put more than one DNS record for your
IP address in the DNS database.
In the production shared webhosting environment, getting a dedicated IP address for every domains
hosted in the server is not feasible in terms of cost. Most of the customers wont be able to afford the
cost of having a dedicated IP address. Here is the place where the concepts of Name based virtual
hosting find its place.
There are 7 modes starting from 0 to 6 which decides how the bonding configuration behaves.
It the default mode. It transmits packets in sequential order from the first available slave through the
last.
This mode provides load balancing and fault tolerance.
mode=1 (active-backup)
Active-backup policy: In this mode, only one slave in the bond is active. The other one will become
active, only when the active slave fails. The bond’s MAC address is externally visible on only one
port (network adapter) to avoid confusing the switch. This mode provides fault tolerance.
mode=2 (balance-xor)
Transmit the traffic based on [(source MAC address XOR'd with destination MAC address) modulo
slave count]. This selects the same slave for each destination MAC address. This mode provides
load balancing and fault tolerance.
mode=3 (broadcast)
Broadcast policy: transmits everything on all slave interfaces. This mode provides fault tolerance.
mode=4 (802.3ad)
Creates aggregation groups that share the same speed and duplex settings. Utilizes all slaves in the
active aggregator according to the 802.3ad specification.
channel bonding that does not require any special switch support. The outgoing traffic is distributed
according to the current load (computed relative to the speed) on each slave. Incoming traffic is
received by the current slave. If the receiving slave fails, another slave takes over the MAC address
of the failed receiving slave.
It includes balance-tlb plus receive load balancing (rlb) for IPV4 traffic, and does not require any
special switch support. The receive load balancing is achieved by ARP negotiation.
/etc/sysconfig/network-scripts/ifcfg-bond0
/etc/modprobe.d/bonding.conf
/etc/sysconfig/network-scripts/ifcfg-eth[0-4]
/proc/net/bonding/bond0
6) Reboot your system, remove bootable CD and we should have the boot menu ready when the
system starts.
Note : There would be slight difference when using with other distros.
steve:$1$XOdE07rn$WA6qFm4W5UIqNfaqE5Uub.:13775:0:99999:7:::
Last password change : Days since Jan 1, 1970 that password was last changed
Warn : The number of days before password is to expire that user is warned that his/her password
must be changed
Inactive : The number of days after password expires that account is disabled
Expire : days since Jan 1, 1970 that account is disabled. It indicates an absolute date specifying
when the login may no longer be used
The /etc/passwd file stores essential information, which is required during login /etc/passwd is a text
file, that contains a list of user account related parameters like user ID, group ID, home directory,
shell, etc.
steve:x:6902:6902::/home/steve:/bin/bash
User ID (UID): Each user must be assigned a user ID (UID). UID 0 (zero) is reserved for root.
User Info: The comment field. It allow you to add extra information about the user.
Home directory: The absolute path to the directory the user will be in when they log in.
Rescue mode provides the ability to boot a small Linux environment from an external bootable
device like a CD-ROM, or USB drive instead of the system's hard drive.Rescue mode is provided to
help you with your system from repairing the file system or fixing certain issues which prevent your
normal operations.
In order to get into the rescue mode, change the BIOS settings of the machine to boot from the
external media. Once the system started booting using bootable disk, add the keyword rescue as a
kernel parameter or else you can give the parameter "linux rescue" in the graphical boot interface.
In single-user mode, the system boots to runlevel 1, but it will have many more additional
functionalities compared to switching to runlevel 1 from other levels.
The local file systems can be mounted in this mode, but the network is not activated.
1) At the GRUB splash screen during the booting process, press any key to enter the GRUB
interactive menu.
2) Select the proper version of kernel that you wish to boot and type "a" to append the line.
3) Go to the end of the line and type "single" as a separate word.
4) Press Enter to exit edit mode and type "b" to boot into single usermode now.
In emergency mode, you are booting into the most minimal environment possible. The root file
system is mounted read-only and almost nothing is set up. The main advantage of emergency mode
over single-user mode is that the init files are not loaded. If the init is corrupted , you can still mount
file systems to recover data that could be lost during a re-installation. To boot into emergency mode,
use the same method as described for single-user mode, with one exception, replace the keyword
single with the keyword "emergency".
16. In the ps results few of the processes are having process state
as "D" . What does it mean ? Briefly explain different process states
?
To have a dynamic view of a process in Linux, always use the top command. This command
provides a real-time view of the Linux system in terms of processes. The eighth column in the output
of this command represents the current state of processes. A process state gives a broader
indication of whether the process is currently running, stopped, sleeping etc.
Running – A process is said to be in a running state when either it is actually running/ executing or
waiting in the scheduler’s queue to get executed (which means that it is ready to run). That is the
reason that this state is sometimes also known as ‘runnable’ and represented by (R).
Waiting or Sleeping – A process is said to be in this state if it is waiting for an event to occur or
waiting for some resource-specific operation to complete. So, depending upon these scenarios, a
waiting state can be subcategorised into an interruptible (S) or uninterruptible (D) state respectively.
Stopped – A process is said to be in the stopped state when it receives a signal to stop. This usually
happens when the process is being debugged. This state is represented by (T).
Zombie – A process is said to be in the zombie state when it has finished execution but is waiting for
its parent to retrieve its exit status. This state is represented by (Z).
Apart from these four states, the process is said to be dead after it crosses over the zombie state; ie
when the parent retrieves its exit status. ‘Dead’ is not exactly a state, since a dead process ceases
to exist.
It is great that the Linux Kernel takes care about that.Linux Operating system is very efficient in
managing your computer memory, and will automatically free the RAM and drop the cache if some
application needs memory.
Kernels 2.6.16 and newer provide a mechanism to have the kernel drop the page cache and/or
inode and dentry caches on command, which can help free up a lot of memory. Now we can throw
away that script that allocated a ton of memory just to get rid of the cache.
To free pagecache:
This is a non-destructive operation in normal scenarios and will only free things that are completely
unused. Dirty objects will continue to be in use until written out to disk and are not freeable. However
it is always preferred to run "sync" first to flush useful things out to disk.
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/steve/.ssh/id_rsa):
b) Press Enter to confirm the default location (that is, ~/.ssh/id_rsa) for the newly created key.
d) Copy the content of ~/.ssh/id_rsa.pub into the ~/.ssh/authorized_keys on the machine to which
you want to connect,
appending it to its end if the file already exists.
e) Change the permissions of the ~/.ssh/authorized_keys file using the following command:
2) Now on your client side, open the remote connection agent like putty and browse your public key
and try SSH to the server, you should be able to login without a password now.
# ssh server1.myserver.com
The authenticity of host 'server1.myserver.com (192.168.44.2)' can't be established.
RSA key fingerprint is e3:c3:89:37:4b:94:37:d7:0c:d5:6f:9a:38:62:ce:1b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'server1.myserver.com' (RSA) to the list of known hosts.
Last login: Tue July 13 12:40:34 2014 from server2.myserver.com
3) Public key authentication can prevent brute force SSH attacks, but only if all password-based
authentication methods are disabled. Once public key authentication has been confirmed to be
working, disable regular password authentication by editing /etc/ssh/sshd_config and set the
following option to "no".
PasswordAuthentication no
a) The client sends a packet with the SYN bit set and a sequence number of N.
b) The server sends a packet with an ACK number of N+1, the SYN bit set and a sequence number
of X.
c) The client sends a packet with an ACK number of X+1 and the connection is established.
d) The client sends the data.
The first three steps in the above process is called the three way handshake.
20. As the disk space utilization was so high in the server, the
Administrator has removed few files from the server but still the
disk utilization is showing as high. What would be the reason ?
In Linux even if we remove a file from the mounted file system, that will still be in use by some
application and for this application it remains available. Its because file descriptor in /proc/ filesystem
is held open..So if there are such open descriptors to files already removed, space occupied by them
considered as used. You find this difference by checking them using the "df" and "du" commands.
While df is to show the file system usage, du is to report the file space usage. du works from files
while df works at filesystem level, reporting what the kernel says it has available.
You can find all unlinked but held open files with:
This will list the filename which is open witht he pid in which it is running. We can kill those Pids and
which will stop these process and will recover the disk space responsible for this file.
21. What is rDNS and explain its benefits in the Linux Domain Name
Systems ?
A typical DNS lookup is used to determine which IP address is associated with a hostname, and this
is called Forward DNS lookup. A reverse DNS lookup is used for the opposite, to determine which
hostname is associated with an IP address. Sometimes reverse DNS lookups are required for
diagnostic purposes. Today, reverse DNS lookups are used mainly for security purposes to trace a
hacker or spammer. Many modern mailing systems use reverse mapping to provide simple
authentication using dual lookup: hostname-to-address and address-to-hostname. The rDNS
( reverse DNS ) is implemented using a specialized zone record for reverse lookups called PTR
record. PTR records always resolve to names, never IP addresses.
# sosreport
This command will normally complete within a few minutes. Depending on local configuration and
the options specified in some cases the command may take longer to finish. Once completed,
sosreport will generate a compressed a file under /tmp folder. The file should be provided to Redhat
support representative as an attachment to open a support case.
23. What is swappiness in Linux Memory Management and how do
we configure that ?
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=0 tells the kernel to avoid swapping processes out of physical memory for as long as
possible
swappiness=100 tells the kernel to aggressively swap processes out of physical memory and move
them to swap cache
The default setting in Redhat/Ubuntu based Linux distros is swappiness=60. Reducing the default
value of swappiness will probably improve overall performance for a typical Ubuntu desktop
installation.
~$ cat /proc/sys/vm/swappiness
60
If we have enough RAM, we can turn that down to 10 or 15. The swap file will then only be used
when the RAM usage is around 80 or 90 percent.
To change the system swappiness value, open /etc/sysctl.conf as root. Then, change or add this line
to the file:
vm.swappiness = 10
You can also change the value while your system is still running
sysctl vm.swappiness=10
We can also clear swap by running swapoff -a and then swapon -a as root instead of rebooting to
achieve the same effect.
24. What is git ?
Git is a very popular and efficient open source Version Control System. It tracks content such as
files and directories. It stores the file content in BLOBs - binary large objects. The folders are
represented as trees. Each tree contains other trees (subfolders) and BLOBs along with a simple
text file which consists of the mode, type, name and Secure Hash Algorithm of each blob and
subtree entry. During repository transfers, even if there are several files with the same content and
different names, the GIT software will transfer the BLOB once and then expand it to the different
files.
Inode number
Access Control List (ACL)
Extended attribute
Direct/indirect disk blocks
Number of blocks
File access, change and modification time
File deletion time
File generation number
File size
File type
Group
Number of links
Owner
Permissions
Status flags
Inode structure of a directory consists of a name to inode mapping of files and directories in that
directory.In a directory, You can find the inode number corresponding to the files using the command
"ls -i"
# df -i /root
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/RootVol-lvmroot
524288 80200 444088 16% /