Sunday, 5 July 2020

What is the difference between Linux and Unix?


76. What is the difference between Linux and Unix?

Linux Unix

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

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

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

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

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

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

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

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

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

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

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

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

 Some features of softlinks are:

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

The linux directory commands are :

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

84. What is the full form of grep?

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

85. Explain Window Manager in Linux?

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

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

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

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

86. What is the FTP Server?

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

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

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

87. Differences between Softlink and Hardlink?

Hard Links 

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

Soft Links

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

88. What is the difference between umask and ulimit?

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

umask [-S] [mask]

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


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

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

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

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

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

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

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

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

91. What is Samba Share?

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

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

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

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

92. What is IRIX Mode in top command?

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

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

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

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

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

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

# ls -lrt | grep "^l"

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

# hping3 -S 192.168.1.1 -p 80 -i u1

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

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

$ touch file
$ chmod 400 file

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

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

99. How to search files in linux?

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

100. How to remote login to another linux computer?

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

                                                                                           MENU         PREVIOUS | NEXT

How to create and delete a directory in Linux?


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

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

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

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

52. How to list and mount devices in Linux?

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

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

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

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

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

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

Here are few of the command line options for crontab.

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

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

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

The format is explained as follows:

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

54. What are the basic Vim commands you know?

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

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

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

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

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

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

55. Explain are different process states in Linux?

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

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

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

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

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

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

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

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

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

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

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

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

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

# ls -li or # ls -li file_name 

# find /root -inum inode_number

57. Explain file permission in Linux?

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

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

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

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

Decimal Permission Representation

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

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

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

Steps to secure ssh services as below:-

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

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

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

60. What is a process?

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

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

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

62. How are threads different from processes?

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

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

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

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

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

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

# strace -p PID
# ltrace libraryfile

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

# pmap -x PID

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

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

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

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

+

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

# free -s 5

69. How to stop a running process in Linux?

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

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

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

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

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

71. What is the advantage of Network Bonding?

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

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

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

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

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

Below is the explanation of the fields.

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

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

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

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

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

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

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

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

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

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

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

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

What is Linux shell?


26. What is Linux shell? How to check current shell?

A Linux shell is a command interpreter or a program that accepts commands and passes them to the operating system for execution. To check the shell that you are using, run # echo $0.

27. What command to find memory and swap usage?

# free -m
              total        used        free      shared  buff/cache   available
Mem:            972         347         460           7         164         481
Swap:          2047           0        2047

28. Mention the steps to find out the memory usage by Linux?

# cat /proc/meminfo

When you will enter this command then you will see a list of memory usage like Total Memory, Free Memory, Cache memory, and many other memory usages by Linux. 

Other commands used in Linux are:

• $ free –m    # this is the simplest command where it will show the memory usage in MB.
• $ vmstat –s # this command gives a report on virtual memory statistics.
• top              # this command checks the usage of memory and cpu usage.
• htop            # similar like top command.

29. How to rename file and directory in Linux?

To rename files, use the mv command. Note that for this to work, the path of the file to be renamed needs to be the same. 

For example, to rename the file file1.doc in /data/files directory to file2.doc 
execute the command: mv /data/files/file1.doc /data/files/file2.doc

30. What is Input/output Redirection?

Directing input & outputs data to and from processes is called Input/Output Redirection. Input / Output redirection is a required feature for good programming and shell scripting. It’s used for taking input and showing results as per requirement. Input from user and passing to other process is called input redirection whereas if process further pass its output to another process or function that will be output redirection for that and input redirection for receiving one.

three redirections available as below: -

• Input Redirection: ‘<’ symbol is used for input redirection to the new process.
• Output Redirection: ‘>’ symbol is used for output redirection to a new process or log file.
• Error Redirection: It is denoted as STDERR(2). This is very useful for error handling.

31. How to copy files and directory in Linux?

To copy files in Linux, use the cp command. The syntax is quite simple
# cp  /source/of/the/file  /destination/of/the/file

32. How to create empty file in Linux?

To create an empty file in Linux, use the touch command as shown:
touch new_file

33. Briefly define ls command and options?

This is one of the most basic and useful commands. This command (“ls”) is used by a normal user or system administrator on a regular basis. This command is used to list down files and directories in the present working directory. 

“ls” Command comes up with multiple options:-

• -l This option will show file & directory permissions in rwxrwxrwx format for user, group & others
• -a This option allows you to view hidden & system files
• -i This option gives you inode details of files
• -s Helps you to list down file size

“ls” without any options will list down all files & directories in plain text. This command gives more desired outputs after clubbing it with grep & less command that allows your filter the list or highlights the required file. This command is also compatible with input-output redirection option which is very helpful for logging.

34. What is the difference between ctrl+z and ctrl+c?

When we have a process in progress which handle your prompt, there were some signals (orders) that we can send to theses process to indicate what we need:

Control+C sends SIGINT which interrupts the application. Usually causing it to abort, but a process is able to intercept the signal and do whatever it likes: for instance, from the Bash prompt, try Ctrl-C. In Bash, it cancels whatever you've typed and gives you a blank prompt (as opposed to the quitting Bash)

Control+Z sends SIGTSTP to foreground application, effectively putting in the background on suspended mode. This is very much useful when we want the application to continue its process while we are doing another job in the current shell. When we finish the job, we can go back into the application by running FG (or %x where x is the job number as shown in jobs).

35. How to create files in Linux?

To create files, use the touch command. For example to create a file file1.doc run the command:
# touch file1.doc

Also use cat command followed by the redirection operator or greater than sign >
# cat > file1.doc
Type the file contents and hit CTRL + D

Using the vi command,
# vi file1.doc
Type the file contents and hit ESC and save :wq

36. What is a Socket?

A Socket is a form of Interprocess Communication and Synchronization that can be used to transfer data from one process to another, either on the same host computer or on different hosts connected by a network; Network sockets are identified by source IP address source port and destination IP address and port.

37. What is the difference between the tar, gz, and zip?

Tar & ZIP are two most commonly used utilities in Linux system

TAR is archiver utility which will archive the selected files or directories. Extension of TAR is .tar.

gz is known as gunzip used compress files only. Extension of gz is .gz. You can use gz on TAR to compression directories achieved by TAR.

ZIP is archiver and compression utility for files and directory. Extension of ZIP is .zip.

The benefit of TAR can be applied on directories. Sometimes, you do not want to compress the filer but want to bundle them, TAR is perfect for it. TAR with GZIP is the best combination. Like GZIP, we also have bzip2 which use a completely new algorithm to compress files has given less size in compare to gzip.

38. Briefly explain the process of sending an email?

The basic steps of this process are mentioned below for your convenience.

• Step 1: After composing a message and send, your email client - whether it's Outlook Express or Gmail - connect to the domain's SMTP server. This server can name many things; a standard example would be smtp.local.com.

• Step 2: In this step, the email client communicates with the SMTP server by giving your email address, the recipient's email address, the message body, and any attachments.

• Step 3: Now SMTP server has complete details to processes the recipient's email address - especially its domain. If the domain name is the same as the sender's, the message is routed directly over to the domain's POP3 or IMAP server - no routing between servers needed. If the domain is different, though, the SMTP server will have to communicate with the other domain's server.

• Step 4: To deliver email and to find the recipient's server, the sender's SMTP server has to communicate with the DNS or Domain Name Server. The DNS will take the recipient's email domain name and translates this into an IP address. The sender's server cannot route an email properly with a domain name alone; an IP address is a unique number that is assigned to every computer that is connected to the Internet. By knowing information, an outgoing mail server can perform its work more efficiently.

• Step 5: Once SMTP server got the recipient's IP address, it can connect to its SMTP server. This isn't done directly, though; instead, the message is routed along with a series of unrelated SMTP servers until it arrives at its destination.

• Step 6: The recipient's SMTP server scans the incoming message. If the domain and user name are valid, it forwards the message along to the domain's POP3 or IMAP server. From there, it is placed in a send mail queue until the recipient's email client allows it to download. At that point, the message can read by the recipient.

39. What is the difference between the mail client and the mail server?

Email client primarily is a desktop or mobile application that enables users to receive and send emails directly on the desktop or mobile. Typically, email client requires an email address to be set up, mail server details & connectivity to the mail server to configure and use email service. These configuration and settings include email address, password, POP3/IMAP and SMTP address, port number, email aliases, and other related preferences.

A mail server or an email server is a server that supports email function in network and support clients to handles and delivers e-mail over a network. This can be over intranet or internet. Email server receives emails from client computers and delivers them to other mail servers after proper authentication and authorization. Mail servers use MTA (Mail transfer agent) with SMTP (Simple Mail Transfer Protocol) to support email transmission. You have used any open source free MTA or any paid version the basis of your requirements and security policies.

40. What are network zones?

Network Zone explains the trust level of a network connection. Creating Zones helps in identifying the secure network or unsecured network. This helps Network administrators to plan the level of monitoring for different networks.

The network zone example,

Trusted:                 Fully trusted connections. All the incoming traffic is allowed.
home work internal:         Partly trusted connections. User/administrator defines open services.
DMZ:                 Mostly untrusted connections, the demilitarized zone.
Public external:         Mostly untrusted connections. User/administrator defines the open services.
Block:         Fully untrusted connections. No incoming traffic is allowed.
Drop:         Fully untrusted connections. All packets are dropped immediately.

41. How to check if a particular service in running?

To check if a service is running, use the syntax:
# systemctl status service_name

For instance, to check is Postfix is running, run the command:
# systemctl status postfix

42. How to start a service on reboot?

To start a service on reboot run use the syntax:
# systemctl enable service_name

For example, to start httpd web server upon a reboot, run
# systemctl enable httpd

43. How do you start and stop a service?

To start a service in a systemd system, run the command:
# systemctl start service_name

For example, to start ssh service, run the command:
# systemctl start sshd

To stop the service, run:
# systemctl stop service_name

To stop ssh run:
# systemctl stop sshd

44. How do you check disk usage?

Use the df command to check the space used on your hard drive and the space remaining / free space.
Additionally, use the du command to check usage by specific files and directories.

45. What is initrd image?

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.

46. Explain the terms suid, sgid and sticky bit?

In addition to the basic file permissions in Linux, there are few special permissions that are available for executable files and directories.

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 privileges of the file on execution, not user privileges. Similar way when you create a file within the 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.

47. Which one is the default sticky bit directory?

/tmp

48. Explain /proc filesystem?

/proc is a virtual file system that provides detailed information about the Linux kernel, hardware, and running processes. /prod is a generic file available in all flavors of Linux. Files under /proc directory named as Virtual files. These files are created when the system boots up and dissolve on shutdown. It contains information about running processes and works as an information zone for the kernel.

/proc is also a hidden tool for a system administrator for analyzed and troubleshooting performance and system bottleneck related issues.
These virtual files have unique qualities. Most of them are listed as zero bytes in size as they reside in memory, not on disk. Virtual files such as the /proc/interrupts, /proc/meminfo, /proc/mounts, and the /proc/partitions provide an up-to-the-moment glimpse of system’s hardware. Others: /proc/filesystems file and /proc/sys/ directories provide system configuration information and interfaces. These are tools for a system administrator to troubleshoot and analyze the issues.

49. 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 a Linux system for the different purpose. 

The descriptions are given below.

0: Halt System (To shutdown the system)
1: Single user mode
2: Basic multi user mode without NFS
3: Full multi user mode (text based)
4: unused
5: Multi user mode with Graphical User Interface
6: Reboot System

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 command line, this will move the system from current runlevel to runlevl 3. Current level can be listed by typing the command 'who -r'

50. How can multiple machines share a single internet connection in Linux?

Linux machine can be made as a router so that multiple devices can share a single internet connection. For this, we have to use a feature called “IP Masquerade.” This functionality will help to connect multiple computers to connect to the Linux machine as well as internet. This functionality will also allow those internal computers to connect who do not have IP addresses.

                                                                                        MENU       PREVIOUS          NEXT 

300 Linux interview questions and answers


The set of below mentioned 300 Linux interview questions and answers would act as a last minute interview preparation guide for you. These questions are useful for the fresher as well as the experienced candidates.


The answers were curated from multiple sources and one can read more on the web about each topic if they are unfamiliar with it. These questions are not mandatory but just an example of what may come in the interview. Hope they are helpful to you for your interview. The key is not to go in-depth but to explain the concept. Good preparation and a smart approach may help you get through this interview. All the best!!

Ref :-

Who invented Linux?


1. Who invented Linux? Explain the history of Linux?

Linus Torvalds created Linux. He was a student at the University of Helsinki, Finland in 1991. He started writing code on his own to get the academic version of Unix for free. Later on, it became popular as Linux Kernel.

2. What is the Linux Kernel?

A Linux kernel is the core of the Linux system. It interfaces the underlying hardware with the operating system.

3. What are the Linux basic components?

Kernel: This is the core of the Linux system. It's responsible for interacting with the hardware components and ensuring the operating system communicates with hardware devices.

Shell: A shell is an interface between the Linux user and the kernel. 

System libraries: These are special programs or functions which are responsible for implementing a majority of the functionalities of the operating system without relying on the kernel modules code access rights.

System Utilities: These are specific programs that executed certain tasks. e.g LibreOffice, Brasero, Gparted.

4. What is BASH?

Bash is a Unix shell and command processor written by Brian Fox for the GNU project. It is free software and acts as a replacement for Bourne Shell. It is an interpreted and not compiled process which can also be run in the terminal window. This allows users to write commands and cause actions. Bash is capable of reading commands from shell scripts.

5. How many types of Shells are there in Linux?

They are five Shells in Linux:

• C Shell (csh): It is like C syntax and provides spelling checking and job control.

• Korn Shell (ksh): Is a high-level programming language shell.

• Z Shell (Zsh): It provides some unique nature like it observes login/logout watching, file name generating, startup files, closing comments. 

• Bourne Again Shell (bash): It is the default to Linux distributions.

• Friendly Interactive Shell (Fish): It provides web-based configuration,  auto-suggestions, etc. 

6. Explain Root and it’s significance in the Linux system?

The root is the most privileged account in Linux for the system administrator. The root user has you full access to the system to perform all kind of access. The root is default account of Linux, created with Linux installation only. The root user is also known as the Root account or superuser. Due to uncontrolled access of Root account, this account needs to be secured and used crucially and carefully.

Some of the functions can be performed by the Root account:-

    •  The root can create/delete/ modify any user, user group, files, directory and permissions.
    •  The root can connect by using any user without password
    •  System / Library / function calls
    •  Managing hidden & config files
    •  System administrator commands

7. List down some of major Linux distributions?

Linux is an open-source operating system which allows users to modify kernel as per their requirement. This facilitates the different part of Linux to be deployed, modified and tested by a different organization. This result in multiple flavors of Linux available in the market and each has its own feature.

Major Linux distributions are as below:-

Ubuntu: It’s the most common and well-known distribution. It has lots of free installed apps for user’s easiness. It’s very easy to use and available in the command line and GUI both.

Red Hat Enterprise: Red Hat Enterprise Linux or RHEL is commercial Linux distribution. It stale, tested, user-friendly and most important NOT free to use.

Debian: Debian is one of the fastest and user-friendly Linux version.

Linux Mint: Its a special type of distribution works on the windows system as well. This for beginners to get hands-on the Linux system.

Fedora: Fedora is not in use on high numbers due to less stability. It supports a GNOME3 desktop environment by default.

8. What is the minimum requirement for Linux installation?

With newer Linux distributions being launched every other week or month, there's no clear cut minimum requirement. Newer versions will demand higher minimum requirements than older versions due to revamped GUI features and architecture. Nevertheless, any Linux distribution should work with a PC with the following minimum requirements:
25 GB of hard disk space
2 GB RAM
2 Ghz dual core processor
A screen resolution of 1024x768
A CD/DVD ROM or USB port for inserting installation media

9. Explain Command Line Interface?

Command Line Interface is also known as CLI. This is an interface for users to interact and instruct system in command line fashion. CLI is the basis on text-based interact to accept user request and response. While comparing with GUI, CLI is lightweight and consume less CPU & Memory resources.
considering the GUI of different versions and flavour, User needs to change there way of working and need additional learning. Whereas CLI is independent of this and allows the user to use any Linux system in the same manner. CLI also comes up with help option so that users need not remember all commands and option and they can refer help or man page for details options and definitions.

Advantages

• Easy, Fast & Flexible
• Very less load on CPU or Memory

Disadvantages

• Commands syntax is a bit tricky and tough to learn
• Long Text inputs can be problematic
• In Compare of GUI, bit tuff to use

10. What is LILO?

LILO is a boot loader for Linux. LILO stands for Linux Loader that is used to load Linux into memory.
It is used mainly to load the Linux operating system into main memory so as to begin operation.

Lilo handles some tasks such as locating the kernel, identifying other supporting programs, load memory and starts the kernel. The configuration file of lilo is located at “/etc/lilo.conf”. Lilo reads this configuration file and it tells Lilo where to place the bootloader.

11. What is GNU project?

The GNU Linux project was created for the development of a Unix-like operating system that comes with source code that can be copied, modified, and redistributed. Richard Stallman announced the GNU Linux project in 1983 and, with others, formed the Free Software Foundation in 1985.

According to the GNU Linux project, there is no independent GNU operating system. Furthermore, they claim that there is no independent Linux operating system either. The OS known as Linux is based on the Linux kernel but all other components are GNU. As such, many believe that the OS should be known as GNU/Linux or GNU Linux.

GNU stands for GNU's not Unix, which makes the term a recursive acronym (an acronym in which one of the letters stands for the acronym itself).

12. Explain the importance of the GNU project?

The GNU project was begun to make a working framework which will be free for clients. The clients would have the opportunity to run, share, circulate, study, change, and enhance or roll out new improvements to the product.

The point of this task was to construct a working framework that is free and furthermore “everything valuable that typically accompanies a UNIX framework so one could get along with no product that isn’t free”.

13. What is the level of Security that Linux provides in comparison to other Operating Systems?

In comparison to other operating systems, Linux is the most secure operating system as it consists of Pluggable Authentication Modules. A secure layer is created between the authentication process and applications. It is because of PAM only by which an admin can give access to other users to log into the system.  You can find the configuration of PAM applications in the “/etc/pam.d” or “/etc/pam.conf” directory.

14. What do you mean by SELinux?

SELinux is the abbreviation for Security Enhanced Linux. It is designed to protect the server against misconfigurations and/or compromised daemons. It is an access control implementation and security feature for the Linux kernel. For example, the users can be stopped from running the scripts and accessing their own home directories. SELinux has the capability to support the access control and security policies. 

It basically operates on three different modes:

• Enforcing –to enforce its policies.
• Permissive –Polices want to apply but will be locked in case of violation.
• Disabled –SELinux will stay in disabled mode.

To check the status of SELinux, just type: # getenfore OR # sestatus

15. List the differences between BASH and DOS?

There are many differences between BASH and DOS that are as below:

    •  BASH is case sensitive while DOS is not case sensitive.
    •  In BASH ‘/’ acts the directory separator while in DOS ‘/’ acts as the command argument delimiter.
    •  In BASH ‘\’ is used as the escape character while in DOS ‘\’ acts as the directory separator.
    •  In BASH there is no any file convention used. DOS follows the naming convention under which a file must have an 8-character filename followed by a dot and 3-character extension.

16. What are the different file system types in Linux?

In Linux, there are many file systems:

Ext, Ext2, Ext3, Ext4, JFS, XFS, btrfs, ufs, autofs, devpts, ntfs and swap.

17. What are the different types of Kernels? Explain.

We can build kernels by many different types, but 3 of the types of kernels are most commonly used: monolithic, microkernel and hybrid.

Microkernel: This type of kernel only manages CPU, memory, and IPC. This kind of kernel provides portability, small memory footprint and also security.

Monolithic Kernel: Linux is a monolithic kernel. So, this type of kernel provides file management, system server calls, also manages CPU, IPC as well as device drivers. It provides easier access to the process to communicate and as there is not any queue for processor time, so processes react faster.

Hybrid Kernel: In this type of kernels, programmers can select what they want to run in user mode and what in supervisor mode. So, this kernel provides more flexibility than any other kernel but it can have some latency problems.

18. Explain Linux Boot Sequence?

There are six levels of a Linux Boot Sequence. These are as follows:

BIOS: Full form of BIOS is Basic Input or Output System that performs integrity checks and it will search and load and then it will execute the bootloader.

MBR: MBR means Master Boot Record. MBR contains the information regarding GRUB and executes and loads this bootloader.

GRUB: GRUB means Grand Unified Bootloader. In case, many kernel images are installed on your system then you can select which one you want to execute.

Kernel: Root file system is mounted by Kernel and executes the /sbin/init program.

Init: Init checks the file /etc/inittab and decides the run level. There are seven-run levels available from 0-6. It will identify the default init level and will load the program.

Runlevel programs: As per your default settings for the run level, the system will execute the programs.

19. Explain Interrupts in Linux and also explain Interrupt handlers?

Interrupts means the processor is transferred temporarily to another program or function. When that program is completed, the processor will be given back to that program to complete the task.

Interrupt handler is the function that the kernel runs for a specific interrupt. It is also called Interrupt Service Routine. Interrupts handlers are the function that matches a particular prototype and enables the kernel to pass the handler information accurately.

20. Where the kernel modules are located?

lib/modules/kernel-version/, this directory stores all the information about the compiled drives under the Linux system. Using lsmod command also we can see the installed kernel modules. 

21. Where are the log files stored usually in Linux?

The log files are stored in /var/log.

22. How do you check the boot messages (kernel ring buffer)?

Check the boot messages using # dmesg or # cat /var/log/dmesg.

23. what is kernel ring buffer linux?

A ring buffer is a circular data architecture that is often used to hold data that is produced and exhaust by different processes without synchronization. The information is produced by the kernel foreign of any specific process background, but the customer is in user space. The kernel needs to grip out pages from the head of the ring intermediary to user space for expenditure, while ensuring that it doesn't overwrite that data as it create to the butt of the buffer.

24. How to increase size of ‘kernel ring buffer’ file (dmesg)?

By default the kernel ring buffer size is 512 bytes. So, to increase this space add “log_buf_len=4M” to the kernel stanza in grub.conf file.

25. What is the difference between YUM and rpm?

Rpm: need local rpm file and dependencies.
Yum: need repository (collections of rpm) local or internet.

                                                                                           MENU                  | NEXT

Tuesday, 5 May 2020

A simple animation bash script

Animation bash script

$ cat frame1

    =========
  =                  =
 =      -     -      =
 =         ^         =
 =         -         =
   \_________/
           ##
         ####
        # ## #
           | |
         _| |_

$ cat frame2

    =========
  =                  =
 =      o     o     =
 =         ^         =
 =         -        =
   \_________/
           ##
         ####
        # ## #
           | |
         _| |_

$ cat frame3

    =========
  =                  =
 =      0     0     =
 =         ^         =
 =      @@@      =
   \_________/
           ##
         ####
        # ## #
           | |
         _| |_

$ cat animation.sh
for ((i; i<=10; i++))
do

clear
cat frame1
sleep .5
clear
cat frame2
sleep .1
clear
cat frame3
sleep .5
done

$ chmod +x animation.sh
$ ./animation.sh



Sunday, 3 May 2020

Bash scrip to check internet speed frequently in Linux

Check internet speed frequently

$ crontab -l
   # set frequency
   20,50 * * * * sh /usr/local/src/internet_speed_test.sh

$ vim internet_speed.sh
   #!/bin/bash
   # run python to get speed
   python speedtest.py > /var/log/speed_test.log

   # process speed_test.log file
   date=$(date "+%d %B %Y %H:%M")
   echo -n "$date" >> /var/log/speed.log
 
   while IFS= read -r line
   do
     if [[ "$line" == *"Download"* ]] || [[ \n\t"$line" == *"Upload"* ]] ; then
           echo -n  '   ' "$line" >> /var/log/speed.log
     fi
   done < /var/log/speed_test.log
 
   echo -e "\n" >> /var/log/speed.log'

$ tail -f /var/log/speed.log
   03 May 2020 18:05    Download: 9.40 Mbit/s    Upload: 6.34 Mbit/s
   03 May 2020 18:22    Download: 11.34 Mbit/s    Upload: 6.12 Mbit/s

Friday, 1 May 2020

Internet Speed Test in Linux Terminal

speedtest using python and fast

  python
$ python3 --version
  Python 3.8.2
$ cat /etc/redhat-release
  CentOS Linux release 7.7.1908 (Core)

$ git clone https://github.com/jpmolekunnel/Speed.git
$ cd Speed/
$ python speedtest.py
  Retrieving speedtest.net configuration...
  Testing from Comcast Cable (71.214.251.133)...
  Retrieving speedtest.net server list...
  Selecting best server based on ping...
  Hosted by Sprint (Fairfax, SC) [114.89 km]: 75.946 ms
  Testing download speed................................................................................
  Download: 8.19 Mbit/s
  Testing upload speed.....................................................................................................
  .Upload: 5.94 Mbit/s

  fast
$ wget https://github.com/ddo/fast/releases/download/v0.0.4/fast_linux_amd64 -O fast
$ chmod +x fast
$ ./fast
   -> 11.64 Mbps

Ref:- addictivetips.com tecmint.com

Thursday, 30 April 2020

Install SQLite3 from Source on Linux

Install SQLite3 from Source

$ wget https://www.sqlite.org/src/tarball/sqlite.tar.gz

$ tar xzf sqlite.tar.gz     #  Unpack the source tree into "sqlite"
$ mkdir bld                   #  Build will occur in a sibling directory
$ cd bld                        #  Change to the build directory
$ ../sqlite/configure     #  Run the configure script
$ make                         #  Run the makefile.
$ make sqlite3.c           #  Build the "amalgamation" source file
$ make test                  #  Run some tests (requires Tcl)

$ whereis sqlite3
sqlite3: /usr/bin/sqlite3 /usr/include/sqlite3.h /usr/share/man/man1/sqlite3.1.gz

$ sqlite3 --version
3.7.17 2013-05-20 00:56:22 118a3b35693b134d56ebd780123b7fd6f1497668

$ sqlite3
   SQLite version 3.7.17 2013-05-20 00:56:22
   Enter ".help" for instructions
   Enter SQL statements terminated with a ";"
   sqlite> .help
   [...]
   sqlite> .show
   [...]
   sqlite> .database
   [...] 
   sqlite> .table
   [...]
   sqlite> .quit

Ref :- sqlite.org sqlite.org/cli.html

Monday, 27 April 2020

Install Python 3.8 using tarball in Linux

Install Python 3.8.2

$ cat /etc/redhat-release
  CentOS Linux release 7.7.1908 (Core)

$ python --version
  Python 2.7.5
$ which python
  /usr/bin/python

$ yum update
$ yum install yum-utils
$ yum-builddep python3

$ wget https://www.python.org/ftp/python/3.8.2/Python-3.8.2.tgz
$ tar -xvzf Python-3.8.2.tgz
$ cd Python-3.8.2

$ ./configure --enable-optimizations
$ make
$ make test
$ make install

$ python3.8 --version
  Python 3.8.2
$ which python3.8
  /usr/local/bin/python3.8

Since the python2.7 is a default system wide python interpreter and need explicitly set to new version. To change python version only for a single user edit ~/.bashrc.

$ vi ~/.bashrc
  alias python='/usr/local/bin/python3.8'
$ cd /root
$ . .bashrc #apply changes

$ python
  Python 3.8.2 (default, Apr 27 2020, 08:41:59)
  [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
  Type "help", "copyright", "credits" or "license" for more information.
  >>>

Ref:- linuxconfig.org

Saturday, 11 April 2020

Debug initramfs images in Linux

Debug initramfs images

$ mkdir /tmp/testdir

$ ls /boot/
   config-3.10.0-957.el7.x86_64
   efi
   grub
   grub2
   initramfs-0-rescue-e45307abc30a407dbbd42a0632810083.img
   initramfs-3.10.0-957.el7.x86_64.img
   initramfs-3.10.0-957.el7.x86_64kdump.img
   symvers-3.10.0-957.el7.x86_64.gz
   System.map-3.10.0-957.el7.x86_64
   vmlinuz-0-rescue-e45307abc30a407dbbd42a0632810083
   vmlinuz-3.10.0-957.el7.x86_64

$ cp -r /boot/initramfs-3.10.0-957.el7.x86_64.img /tmp/testdir/i

$ ls /tmp/testdir/i
   i

$ cd /tmp/testdir/

$ file i
   i: ASCII cpio archive (SVR4 with no CRC)

$ cpio -i --no-absolute-filenames <i
   86917 blocks

$ ls /tmp/testdir/
   bin  etc init   lib64  root   sbinb          sys          tmp   var
   dev  i    lib    proc   run    shutdown   systoot    usr

$ ls -l init  
   lrwxrwxrwx. 1 root root 11 Apr   20 11:12 init -> usr/lib/systemd/systemd

Make a custom GRUB entry in Linux

How to make a custom GRUB entry

Copy menuentry for CentOS Linux 3.10.0-957.el7.x86_64 to 40_custom edit as,
$ vi /etc/grub.d/40_custom
#!/bin/sh
exec tail -n +3 $0
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
menuentry 'Custom Linux Boot Entry' --class centos --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-957.el7.x86_64-advanced-4f940ed7-acd6-4631-bf35-ee2f43b49c9f' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_msdos
        insmod xfs
        set root='hd0,msdos1'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 --hint='hd0,msdos1'  5971f3cb-eb26-4c88-af0a-b6c96e12965c
        else
          search --no-floppy --fs-uuid --set=root 5971f3cb-eb26-4c88-af0a-b6c96e12965c
        fi
        linux16 /vmlinuz-3.10.0-957.el7.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet initcall_debug
        initrd16 /initramfs-3.10.0-957.el7.x86_64.img
}

                                                OR

menuentry 'Custom Linux Boot' {
        linux16 /vmlinuz-3.10.0-957.el7.x86_64 root=/dev/mapper/centos-root ro rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet initcall_debug
        initrd16 /initramfs-3.10.0-957.el7.x86_64.img
}

$ grub2-mkconfig -o /etc/grub2.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.10.0-957.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-957.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-e45307abc30a407dbbd42a0632810083
Found initrd image: /boot/initramfs-0-rescue-e45307abc30a407dbbd42a0632810083.img
done

$ dmesg | grep initcall #check the current kernel have any init call
If no output then reboot and check.

$ dmesg | grep initcall | head
[    0.000000] Command line: BOOT_IMAGE=/vmlinuz-3.10.0-957.el7.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet initcall_debug
[    0.000000] Kernel command line: BOOT_IMAGE=/vmlinuz-3.10.0-957.el7.x86_64 root=/dev/mapper/centos-root ro crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap rhgb quiet initcall_debug
[    0.131139] initcall init_hw_perf_events+0x0/0x5f1 returned 0 after 0 usecs
[    0.131167] initcall set_real_mode_permissions+0x0/0x102 returned 0 after 0 usecs
[    0.131173] initcall trace_init_flags_sys_exit+0x0/0xf returned 0 after 0 usecs
[    0.131178] initcall trace_init_flags_sys_enter+0x0/0xf returned 0 after 0 usecs
[    0.131184] initcall register_trigger_all_cpu_backtrace+0x0/0x16 returned 0 after 0 usecs
[    0.131190] initcall kvm_spinlock_init_jump+0x0/0x28 returned 0 after 0 usecs
[    0.131197] initcall early_efi_map_fb+0x0/0x32 returned 0 after 0 usecs
[    0.131228] initcall spawn_ksoftirqd+0x0/0x26 returned 0 after 0 usecs

How to Interrupt GRUB and Override init process in Linux

Interrupt GRUB and Override init

This can be achieved by making temporary changes to a kernel menu entry
requirements: cent OS 7 installed in a virtual machine.

Booting with rdinit=/bin/sh will start with a shell in the initramfs.
while booting with init=/bin/bash will complete the initramfs and then start with a shell on the disk.

Scenario 1:  Change kernel parameters only during a single boot process. reboot vm on the GRUB 2 boot screen press 'e' key for edit regular kernel entry
at the end of last to previous line, add rdinit=/bin/sh



Press Ctrl+x, it will boot as shell prompt with logged in.
The init is restarted process as /bin/sh.
There will be a limited file system loaded in RAM











Scenario 2: reboot vm, on the GRUB 2 boot screen press 'e' key for edit regular kernel entry. At the end of last to previous line, add init=/bin/bash.



Press Ctrl+x to boot, It will boot as shell prompt with logged in.
The init is restarted process as /bin/bash, with no ordinary service like GUI or init processes.



Thursday, 9 April 2020

Bash script to monitor cpu usage in Linux

Script to monitor cpu usage 

$ vi cpu_usage.sh

#!/bin/bash

CPU_USAGE=$(top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -l | awk -F'id,' -v prefix="$prefix" '{ split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%s%.1f%%\n", prefix, 100 -v}' )

DATE=$(date "+%d %B %Y %H:%M")
CPU_USAGE="$DATE CPU: $CPU_USAGE"
echo $CPU_USAGE >> /var/log/scripts/cpu_usage.log

$ ./cpu_usage.sh

$ cat /var/log/scripts/cpu_usage.log
09 April 2020 08:36 CPU: 3.2% 0.2%
09 April 2020 15:00 CPU: 9.7% 0.0%
09 April 2020 15:34 CPU: 0.0% 0.2%

Bash script to guess a random one-digit number

Script to guess a random one-digit number

$ vi ch4_solution.sh game

#!/bin/bash
rand=$RANDOM
secret=${rand:0:1}

function game {
        read -p "Guess a random one-digit number! " guess
        while [[ $guess != $secret ]]; do
                read -p "Nope, try again! " guess
        done
        echo "Good job, $secret is it! You're great at guessing!"
}

function generate {
        echo "A random number is: $rand"
        echo -e "Hint: type \033[1m$0 game\033[0m for a fun diversion!"
}

if [[ $1 =~ game|Game|GAME ]]; then
        game
else
        generate
fi

$ ./ch4_solution.sh game
Guess a random one-digit number! 1
Nope, try again! 4
Nope, try again! 5
Good job, 5 is it! You're great at guessing!

Tuesday, 7 April 2020

Sample bash script to generate system report

Generate system report

vim /usr/local/src/test_my_scripts/system_report.sh
#!/bin/bash
# System Report
greentext="\033[32m"
bold="\033[1m"
normal="\033[0m"
freespace=$(df -h / | grep -E "\/$" | awk '{print $4}')
logdate=$(date +"%Y%m%d")
path=/var/log/script
logfile="$path$logdate"_report.log

echo -e $bold"Quick system report for "$greentext"$HOSTNAME"$normal
printf "\tSystem type:\t%s\n" $MACHTYPE
printf "\tBash Version:\t%s\n" $BASH_VERSION
printf "\tFree Space:\t%s\n" $freespace
printf "\tFiles in dir:\t%s\n" $(ls | wc -l)
printf "\tGenerated on:\t%s\n" $(date +"%m/%d/%y")
echo -e $greentext"A summary of this info has been saved to $logfile"$normal

cat <<- EOF > $logfile
        This report was generated using Bash script.
EOF

printf "\tGenerated on:\t%s\n" $(date +"%m/%d/%y") >> $logfile
printf "\tFree Space:\t%s\n" $freespace >> $logfile
printf "\tFiles in dir:\t%s\n" $(ls | wc -l) >> $logfile

sh /usr/local/src/test_my_scripts/system_report.sh
Quick system report for localhost.localdomain
        System type:    x86_64-redhat-linux-gnu
        Bash Version:   4.2.46(2)-release
        Free Space:     15G
        Files in dir:   6
        Generated on:   04/07/20
A summary of this info has been saved to /var/log/script20200407_report.log

cat /var/log/script20200407_report.log
This report was generated using Bash script.
        Generated on:   04/07/20
        Free Space:     15G
        Files in dir:   6

Monday, 6 April 2020

40 Examples of grep command in Linux

Searching and mining text inside a file with grep

man grep
grep "string" demo_file      #string search
grep "string" demo_file test_file.txt
grep "string" *.*

grep “^hello” file #match all lines start with ‘hello’
grep “done$” file #match all lines end with 'done'
grep “[^aeiou]” file #Match all lines not contain a vowel
grep -n "string" demo_file      # show line numbers with match

egrep is the same as grep -E
fgrep is the same as grep -F
rgrep is the same as grep -r
egrep IP /etc/hosts
egrep 'IP1|IP2' /etc/hosts

seq 10 | grep 5 -A 3        #print 5-8
seq 10 | grep 5 -B 3        #print 2-5
seq 10 | grep 5 -C 3        #print 2-8
echo -e "a\nb\nc\na\nb\nc" | grep a -A 1

grep word filename --color=auto #add color
grep --color "string" demo_file
grep --color -n "string" demo_file
yum search php | grep gd
grep -E "[a-z]+" demo_file #extented
grep "[a-z]+" demo_file

grep -v "string" demo_file     #inverted result
grep -c "string" demo_file #count the occurrence
echo -e "1 2 3 4\nhellow\n5 6" | grep -c "[0-9]"
grep -r  --exclude-dir=log "string" *
grep -c "[0-9]" demo_file

grep -o "[0-9]" demo_file | wc -l     #count no of times
echo -e "1 2 3 4\nhellow\n5 6" | grep -o "[0-9]" | wc -l
cat filename | grep -b -o "word"
grep -l "string" sample.txt sample1.txt     #with-match
grep -L "string" sample.txt sample1.txt     #without-match

grep "string" . -R -n       #recursive search
grep -i "string" demo_file #case insensitive
grep -i 'Model' /proc/cpuinfo
grep -e "count" -e "image" -o rename.sh     #multiple patterns
grep "main()" . -r --include *.{c,cpp}
grep "main()" . -r --exclude "README"
grep "string" file* -lZ | xargs -0 rm -rf

grep -o "is.*line" demo_file      #matched string
grep -v -E '^\#|^$' demo_file #skips line beginning "#" or empty
grep -v -f file1 file2 > file.out    #diff of 2nd with 1st
find . -type f -exec grep -il 'string' {} \; #find in directory tree

grep authentication failure /var/log/secure-20200329
export GREP_OPTIONS='--color=auto' #to enable all the time
grep -i break-in autth.log | awk {'print $12'}
ping -c 1 linuxmissive.com | grep 'bytes from'
ping -c 1 linuxmissive.com | grep 'bytes from' | cut -d = -f 4

# find all files named "*.java,v" containing both 'prevayl' and 'jtable'
grep -li "jtable" $(find . -name "*.java,v" -exec grep -li "prevayl" {} \;)
egrep 'sting1|sting2|sting3|sting4' file.txt # all lines matching multiple patterns
locate -i calendar | grep Users | egrep -vi 'twiki|gif|shtml|drupal-7|java|PNG'
   
ps auxwww | grep httpd               # all processes containing 'httpd'
ps auxwww | grep -i java             # all processes containing 'java', ignoring case
ls -al | grep '^d'                        # list all dirs in the current dir
#printing lines before and after of matching
grep --context=6 "string" demo_file      #6 lines before and after

Ref:- thegeekstuff.com

Saturday, 4 April 2020

Install MySQL on CentOS 7

Install and Configure MySQL

Install MySQL

wget https://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm
md5sum mysql57-community-release-el7-9.noarch.rpm
rpm -ivh mysql57-community-release-el7-9.noarch.rpm

Start MySQL

systemctl start mysqld
systemctl status mysqld #Active: active (running)
grep 'temporary password' /var/log/mysqld.log #A temporary password is generated

Configure MySQL

mysql_secure_installation #set a new password
mysqladmin -u root -p version

Packages for MySQL:- dev.mysql.com

Ref:- digitalocean.com

Friday, 3 April 2020

Bash script to List all the machines alive on a network

Ping all the machines alive

vi ping.sh
#!/bin/bash
#ping ping.sh

for ip in 192.168.0.{1..255} ;
do
 (
 ping $ip -c 2 &> /dev/null;

 if [ $? -eq 0 ];
 then
  echo $ip is alive
 fi
 )&
done
wait

./ping.sh
192.168.0.1 is alive
192.168.0.3 is alive
192.168.0.16 is alive
192.168.0.32 is alive
192.168.0.201 is alive


Linux script to monitor top ten CPU consuming process

CPU monitoring bash script for an hour

vi cpu_usage.sh
#!/bin/bash
#calculate cpu usage by processes for 1 hour

SECS=3600
UNIT_TIME=60

STEPS=$(( $SECS / $UNIT_TIME ))

echo Watching CPU usage... ;

for ((i=0;i<STEPS;i++))
do
 ps -eocomm,pcpu | tail -n +2 >> /tmp/cpu_usage.$$
 sleep $UNIT_TIME
done

echo
echo CPU eaters :

cat /tmp/cpu_usage.$$ | \
awk '
{ process[$1]+=$2; }
END{
 for(i in process)
 { printf("%-20s%d\n",i, process[i]); }
 }' | sort -nrk 2 | head

rm -rf /tmp/cpu_usage.$$

./cpu_usage.sh
Watching CPU usage...

CPU eaters :
xfs-reclaim/sda      0
xfs-reclaim/dm-     0
xfs_mru_cache       0
xfs-log/sda1           0
xfs-log/dm-0          0
xfs-eofblocks/s       0
xfs-eofblocks/d      0
xfs-data/sda1         0
xfs-data/dm-0        0
xfs-conv/sda1         0