Sunday, 17 April 2016

RUN LEVELS/TARGETS IN LINUX

RUN LEVELS/TARGETS IN LINUX


Run Levels/Targets in Linux
Welcome guys to our linux tutorial, In this article we will discuss about different runlevels in unix-linux system. We will briefly describe runlevel, its associated configuration file, boot process,stages of boot process and finally we will discuss briefly about each runlevel. These runlevels or modes run system or boot process defined by user/system admin. But in latest version system uses target instead of runlevels so I am going to use both runlevel or target word so don’t confuse.
Introduction
Runlevels is basically modes in *nix based systems which is initializing operating system. Every runlevel has certain numbers of services started or stopped. This gives user flexibility to run/boot system in different modes( run system with certain services) as per requirements
Init stand for initialization is the program file in *nix operating system. Its run as a daemon and has typically process identity (PID)  1.
Feb2516-19usd-sitewide728X90
Configuration File
/etc/inittab is a configuration file used to setup the default runlevels for *nix system.After the linux system is booted the init program reads this configuration file and determines runlevel set in this file. If user/admin has not specified any runlevel system will boot with default runlevel.  Applications which  are started by init program located in the/etc/rc.d folder, then within this folder there are  separate folders for each runlevel  e.g rc0.d, rc1.d etc. These runlevels or targets are defined in below.
To Change in configuration file is open it in vi editor or any other editor of your own choice .
I am going to open with vi
vi /etc/inittab.
In older version you can change the run level in last line of this file see below example
id:5:initdefault: or id:3:initdefault    #(choose as per your requirement)
In latest version there are only two main targets by default
# multi-user.target: analogous to runlevel 3

# graphical.target: analogous to runlevel 5         #(choose as per your requirement)
BOOT Process
There are following stages of boot process.
runlevel or target in linux
Runlevel or Target with Commands
There are seven runlevels in *nix OS and runlevels are identified by numbers.
Init 0
Init 0 is for immediately shutdown system and powers it off you may also use halt and poweroff. Syntax init 0 orpoweroff or halt.
[fahmed@faraz ~]$ init 0

[fahmed@faraz ~]$ poweroff

[fahmed@faraz ~]$ halt
Init 1
It is also known as Single-User mode and it is used for system maintenance and root in CLI mode. Syntax init 1. No network interfaces configured
[fahmed@faraz ~]$ init 1
Init 2
Used for without networking in CLI mode and it is multi-user mode. Syntax init 2.
[fahmed@faraz ~]$ init 2
Init 3
It is also used as multi-user mode but with networking in CLI mode. Syntax init 3. this is like normal startup
[fahmed@faraz ~]$ init 3
Init 4
This is an un-defined mode or you can say not in used mode. Syntax init 4.
[fahmed@faraz ~]$ init 4
Init 5
This is a GUI mode. A standard and default runlevel/target  for most *nix OS. Syntax init 5.
[fahmed@faraz ~]$ init 5
Init 6
It is used to restart your system when required and you may also use reboot.
Syntax init 6 or reboot.
[fahmed@faraz ~]$ init 6
OR
[fahmed@faraz ~]$ reboot
NOTE: Don’t set runlevel 0, 1 and 6 as default runlevel. Otherwise you will face the problems.
To check who is logon in system by using command who. Or list of user login by using command who –u.
[fahmed@faraz ~]$ who

fahmed   :0           2016-02-24 06:09 (:0)

fahmed   pts/0        2016-02-24 06:10 (:0)

fahmed   pts/1        2016-02-24 06:10 (192.168.40.112)
To view current runlevel/target by using command who –r.
[fahmed@faraz ~]$ who -r

run-level 5  2016-02-24 05:33
To view boot system time by using command who –b.
[fahmed@faraz ~]$ who -b

system boot  2016-02-24 05:32

[fahmed@faraz ~]$
For all options by using who –a.
[fahmed@faraz ~]$ who -a

system boot  2016-02-24 05:32

fahmed   ? :0           2016-02-24 06:09   ?          4601 (:0)

run-level 5  2016-02-24 05:33

fahmed   + pts/0        2016-02-24 06:10 00:22        5430 (:0)

fahmed   + pts/1        2016-02-24 06:10   .          5584 (192.168.40.112)

[fahmed@faraz ~]$

In this tutorial we discussed about runlevels or targets with command init 0 to 6 and who command who –r, who –u, who –a and who –b. Please subscribe our newsletter for new upcoming tutorials.





Hello and welcome guys, In this new and exciting tutorial/article we will learn step by step how to configure DHCP Server in Linux (Red Hat/ CentOS). We will do configuration by using configuration file.  This is used for enterprise network to reduce manual  IP configuration efforts (for instance it will take hours and hours to do ip configuration on 1000 systems).

What is DHCP Server

DHCP stands for Dynamic Host Configuration Protocol.
Network/Server/System Administrator designs and implements DHCP server to centrally manage and automate the process of assigning Internet Protocol (IP) in company/organization. DHCP has ability to assign IP automatically for the system as well as Subnet Mask, Gateway and DNS (if you have configured),
when system boots it gets the IP from DHCP. DHCP uses DORA process in backend. DHCP uses the concept of lease time or we can say the amount of time that given an IP address is valid for computer. The lease time may vary depending on the user to require internet connection with a specific location. It is useful in education sector or other environment where users change frequently.
DORA Stand for Discover Offer Request Acknowledgement.

DHCP Discover

When a client is configure with obtain automatic IP address, then the client PC searches for DHCP server. The UDP is broadcasted to discover the DHCP server.
Available IP address in the pool offered by DHCP Server and the Client PC waiting for the IP address.

DHCP Request

In the response of the offer, Client will request IP address.

DHCP Acknowledge

In the response to the request, DHCP server will respond with IP address, subnet mask, Gateway and DNS info along with the acknowledgement.

DHCP PORTS

DHCP client is running on the client machine. It begins broadcasting requests for configuration information. By default, these requests are listening on UDP port # 68. The server responds to client on UDP port # 67.

Installation of DHCP Server on CentOS / Red Hat 7

For installation of DHCP server by using command yum. Syntax yum install dhcp
[root@faraz ~]# yum install dhcp*

Loaded plugins: fastestmirror, langpacks, priorities

base                                                                        | 3.6 kB  00:00:00
epel/x86_64/metalink                                                        | 4.0 kB  00:00:00
epel                                                                        | 4.3 kB  00:00:00
extras                                                                      | 3.4 kB  00:00:00
updates                                                                     | 3.4 kB  00:00:00

(1/4): epel/x86_64/updateinfo                                               | 523 kB  00:00:02
(2/4): extras/7/x86_64/primary_db                                           | 101 kB  00:00:03
(3/4): epel/x86_64/primary_db                                               | 3.9 MB  00:00:08
(4/4): updates/7/x86_64/primary_db                                          | 3.2 MB  00:00:22
After installation you need to configure a static IP address for DHCP server in the DHCP range for the listening interface. (e.g. enp0s3 for latest version, eth0 for older versions)

Configure Server Interface (Network Interface Card) for DHCP

Open the file /etc/sysconfig/network-scripts/ifcfg-enp0s3 with insertion mode through vim tool and make the changes as per requirement. Here we go…..;
[root@faraz ~]# vi /etc/sysconfig/network-scripts/ifcfg-enp0s3

TYPE=Ethernet
BOOTPROTO=static
ONBOOT=yes
IPADDR=192.168.56.10
NETMASK=255.255.255.0

DHCP Configuration

Now we are going to configure our DHCP server, for configuration we need to go to the file which is in/etc/dhcp/dhcpd.conf. In this file we need to add some parameters for DHCP server configuration by defining IP range, route, domain name server, default and max lease time within subnet and netmask parameters.
[root@faraz ~]# vi /etc/dhcp/dhcpd.conf

# DHCP Server Configuration file.
#   see /usr/share/doc/dhcp*/dhcpd.conf.example
#   see dhcpd.conf(5) man page
#

subnet 192.168.56.0 netmask 255.255.255.0
{
range 192.168.56.50 192.168.56.100;
# DNS server IP or additional DNS server IP
#       option domain-name-servers 8.8.8.8, 8.8.4.4 (remove the [#] hash sign if you have domain server)
#Domin name
#       option domain-name shahid-academy.com
option broadcast-address 192.168.56.255;
#Gateway IP
option routers 192.168.56.1;
 
default-lease-time 600;
max-lease-time 7200;
log-facility local7;
}

Reserve IP address with MAC

You can also reserve the IP address for printer or system/ Pc with MAC address in this regard add some parameter which is define in below example;
host myPC
{
hardware ethernet 00:00:00:00:00:00;
fixed-address 192.168.56.90;
}

Add rule for Firewall

If your system’s firewall in running position then you have two choices one is stop the service of firewall by usingsystemctl stop firewalld and the second one is to define the rule for the firewall by using below condition;
[root@faraz ~]# firewall-cmd --permanent --add-service=dhcp
[root@faraz ~]# firewall-cmd --reload

Service

Start the service by using command systemctl. Syntax systemctl start service – daemon – name
[root@faraz ~]# systemctl start dhcpd
You can start the service at the boot time by using enable option. Syntax systemctl enable service – daemon – name
[root@faraz ~]# systemctl enable dhcpd

Verification of DHCP Server Configuration

Finally you can verify whether you DHCP server configure accurately or not by using dhcpd configtest.
[root@faraz ~]# dhcpd configtest

In this tutorial/ article we have learnt how to configure DHCP server with reservation by adding firewall rule if firewall is running. I hope you like it and learn this practical knowledge. Let us know about your suggestions and problem through comment and subscribe our newsletter. Keep learning with us… :-)

Friday, 15 April 2016

Linux Commands Useful for Any Linux

LINUX COMMANDS

Here are some fundamental and common Linux commands with example usage:

FILESYSTEM

LS

Lists the content of the current directory (or one that is specified). Can be used with the -l flag to display additional information (permissions, owner, group, size, date and timestamp of last edit) about each file and directory in a list format. The-a flag allows you to view files beginning with . (i.e. dotfiles).

CD

Changes the current directory to the one specified. Can use relative (i.e.cd directoryA) or absolute (i.e. cd /home/pi/directoryA) paths.

PWD

Displays the name of the current working directory, i.e. pwd will output something like /home/pi.

MKDIR

Makes a new directory, e.g. mkdir newDir would create the directory newDirin the present working directory.

RMDIR

Remove empty directories, e.g. rmdir oldDir will remove the directoryoldDir only if it is empty.

RM

Removes the specified file (or recursively from a directory when used with -r). Be careful with this! Files deleted in this way are mostly gone for good!

CP

Makes a copy of a file and places it at the specified location (essentially doing a 'copy-paste'), for example - cp ~/fileA /home/otherUser/ would copy the filefileA from your home directory to that of the user otherUser (assuming you have permission to copy it there!). This command can either take FILE FILE(cp fileA fileB), FILE DIR (cp fileA /directoryB/) or -r DIR DIR(which recursively copies the contents of directories) as arguments.

MV

Moves a file and places it at the specified location (so where cp performs a 'copy-paste', mv performs a 'cut-paste'). The usage is similar to cp, somv ~/fileA /home/otherUser/ would move the file fileA from your home directory to that of the user otherUser. This command can either take FILE FILE(mv fileA fileB), FILE DIR (mv fileA /directoryB/) or DIR DIR(mv /directoryB /directoryC) as arguments. This command is also useful as a method to rename files and directories after they've been created.

TOUCH

Either sets the last modified time-stamp of the specified file(s) or creates it if it does not already exist.

CAT

Lists the contents of file(s), e.g. cat thisFile will display the contents ofthisFile. Can be used to list the contents of multiple files, i.e. cat *.txt will list the contents of all .txt files in the current directory.

HEAD

Displays the beginning of a file. Can be used with -n to specify the number of lines to show (by default 10), or with -c to specify the number of bytes.

TAIL

Displays the end of a file. The starting point in the file can be specified either through -b for 512 byte blocks, -c for bytes, or -n for number of lines.

CHMOD

Normally used to change the permissions for a file. The chmod command can use symbols u (user that owns the file), g (the files group) , o (other users) and the permissions r (read), w (write) and x (execute). Usingchmod u+x *filename* will add execute permission for the owner of the file.

CHOWN

Changes the user and/or group that owns a file. It normally needs to be run as root using sudo e.g. sudo chown pi:root *filename* will change the owner to pi and the group to root.

SSH

Secure shell. Connect to another computer using an encrypted network connection. For more details see SSH (secure shell)

SCP

Copies a file from one computer to another using ssh. For more details see SCP (secure copy)

SUDO

Run a command as a superuser, or another user. Use sudo -s for a superuser shell. For more details see Root user / sudo

DD

Copies a file converting the file as specified. It is often used to copy an entire disk to a single file or back again eg. dd if=/dev/sdd of=backup.img will create a backup image from an SD card or USB disk drive at /dev/sdd. Make sure to use the correct drive when copying an image to the SD card as it can overwrite the entire disk.

DF

Display the disk space available and used on the mounted filesystems. Usedf -h to see the output in a human readable format using M for MBs rather than showing number of bytes.

UNZIP

Extracts the files from a compressed zip file.

TAR

Store or extract files from a tape archive file. It can also reduce the space required by compressing the file similar to a zip file.
To create a compressed file usetar -cvzf *filename.tar.gz* *directory/* To extract the contents of a file use tar -xvzf *filename.tar.gz*

PIPES

A pipe allows the output from one command to be used as the input for another command. The pipe symbol is a vertical line |. For example to only show the first 10 entries of the ls command it can be piped through the head commandls | head

TREE

Show a directory and all subdirectories and files indented as a tree structure.

&

Run a command in the background freeing up the shell for future commands.

WGET

Download a file from the web directly to the computer e.g.wget http://www.raspberrypi.org/documentation/linux/usage/commands.mdwill download this file to your computer as commands.md

CURL

Download or upload a file to/from a server. By default it will output the file contents of the file to the screen.

MAN

Show the manual page for a file. To find out more run man man to view the manual page of the man command.

SEARCH

GREP

Search inside files for certain search patterns e.g. grep "search" *.txt will look in all the files in the current directory ending with .txt for the string search.
Supports regular expressions which allows special letter combinations to be included in the search.

AWK

Programming language useful for searching and manipulating text files.

FIND

Searches a directory and subdirectories for files matching certain patterns.

WHEREIS

Finds the location or a command. Looks through standard program locations until it finds the requested command.

NETWORKING

PING

Utility usually used to check if communication can be made with another host. Can be used with default settings by just specifying a hostname (e.g.ping raspberrypi.org) or an IP address (e.g. ping 8.8.8.8). Can specify the number of packets to send with the -c flag.

NMAP

Network exploration and scanning tool. Can return port and OS information about a host or a range of hosts. Running just nmap will display the options available as well as example usage.

HOSTNAME

Displays the current hostname of the system. A privileged (super) user can set the hostname to a new one by supplying it as an argument (e.g.hostname new-host).

IFCONFIG

Displays the network configuration details for the interfaces on the current system when run without any arguments (i.e. ifconfig). By supplying the command with the name of an interface (e.g. eth0 or lo) you can then alter the configuration (check the man-page for more details).

RC.LOCAL configuring on Linux

RC.LOCAL

In order to have a command or program run when the Pi boots, you can add commands to the rc.local file. This is especially useful if you want to be able to plug your Pi in to power headless, and have it run a program without configuration or a manual start.
An alternative for scheduled task management is cron.

EDITING RC.LOCAL

On your Pi, edit the file /etc/rc.local using the editor of your choice. You must edit with root, for example:
sudo nano /etc/rc.local
Add commands below the comment, but leave the line exit 0 at the end, then save the file and exit.

WARNING

If your command runs continuously (perhaps runs an infinite loop) or is likely not to exit, you must be sure to fork the process by adding an ampersand to the end of the command, like so:
python /home/pi/myscript.py &
Otherwise, the script will not end and the Pi will not boot. The ampersand allows the command to run in a separate process and continue booting with the process running.
Also, be sure to reference absolute filenames rather than relative to your home folder; for example, /home/pi/myscript.py rather than myscript.py.

TEXT EDITORS For LINUX

TEXT EDITORS

On Linux, you have a choice of text editors. Some are easy to use but have limited functionality, others require training to use and a long time to master but offer incredible functionality.

DESKTOP GRAPHICAL EDITORS

LEAFPAD

On Raspbian, you'll find an editor called Leafpad. This is a simple editor which opens in a window like a normal application. It allows use of the mouse and keyboard, and has tabs and syntax highlighting.
You can use keyboard shortcuts such as Ctrl + S to save a file andCtrl + X to exit.

IDLE

IDLE is a Python REPL and IDE, so you can write and edit Python code in a window and run it from there.
IDLE has independent windows and syntax highlighting. It's somewhat buggy but generally ok for basic use.
You can use keyboard shortcuts like Ctrl + S to save a file, or Alt + P(previous command) and Alt + N (next command) in the REPL.
Note that IDLE uses Python2 and IDLE 3 uses Python3.

GVIM

See Vim below

COMMAND LINE EDITORS

NANO

GNU Nano is at the easy-to-use end of command line editors. It's installed by default, so use nano somefile.txt to edit a file and keyboard shortcuts likeCtrl + O to save and Ctrl + X to exit.

VI

Vi is a very old (c. 1976) command line editor, which is available on most UNIX systems and is preinstalled on Raspbian. It is succeeded by Vim (Vi Improved), which requires installation.
Unlike most editors, Vi and Vim have a number of different modes. When you open Vi with vi somefile.txt, you start in command mode which does not (directly) permit entry of text. Press i to switch to insert mode in order to edit the file, and type away. To save the file you must return to command mode, so hit the Escapekey and enter :w (followed by Enter) which is the command to write the file to disk.
To search for the word 'raspberry' in a file, make sure you're in command mode (press Escape), then type /raspberry followed by n and N to flick forward/backward through the results.
To save and exit, enter the command :wq. To exit without saving, enter the command :q!.
Depending on your keyboard configuration you may find your cursor keys don't work. In this case, you can use the H-J-K-L keys to navigate the file (which move left, down, up, and right respectively) in command mode.

VIM

Vim is an extension of Vi and works in much the same way, with a number of improvements. Only Vi is installed by default so to get the full features of Vim, install it with APT:
sudo apt-get install vim
You can edit a file in vim with vim somefile.txt. Vim also has a graphical version which opens in a window and allows interaction with the mouse. This version is installable separately:
sudo apt-get install vim-gnome
To use the graphical version of vim, use gvim somefile.txt. You can save configuration in a .vimrc file in your user's home directory. To learn more about editing in Vi and Vim, you can run vimtutor and follow the tutorial.

EMACS

GNU Emacs is the GNU flavour of command line text editors; it is powerful, extensible, and customisable. You can install it with APT:
sudo apt-get install emacs
Use keyboard combination commands such as Ctrl + X Ctrl + S to save andCtrl + X Ctrl + C to close.

SCHEDULING TASKS WITH CRON on Linux

SCHEDULING TASKS WITH CRON

Cron is a tool for configuring scheduled tasks on Unix systems, used to schedule commands or scripts to run periodically and at fixed intervals. Tasks range from backing up the user's home folders every day at midnight, to logging CPU information every hour.
The command crontab (cron table) is used to edit the list of scheduled tasks in operation, and is done on a per-user basis; each user (including root) has their own crontab.

CRON GUI

A graphical application for Cron is available by installing the gnome-schedulepackage:
sudo apt-get install gnome-schedule
You can then launch the program Scheduled Tasks from the main menu.

EDITING CRONTAB

Run crontab with the -e flag to edit the cron table:
crontab -e

SELECT AN EDITOR

The first time you run crontab you'll be prompted to select an editor; if you are not sure which one to use, choose nano by pressing Enter.

ADD A SCHEDULED TASK

The layout for a cron entry is made up of six components: minute, hour, day of month, month of year, day of week, and the command to be executed.
# m h  dom mon dow   command
# * * * * *  command to execute
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 7) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)
For example:
0 0 * * *  /home/pi/backup.sh
This cron entry would run the backup.sh script every day at midnight.

VIEW SCHEDULED TASKS

View your currently saved scheduled tasks with:
crontab -l

RUN A TASK ON REBOOT

To run a command every time the Raspberry Pi starts up, write @reboot instead of the time and date. For example:
@reboot python /home/pi/myscript.py
This will run your Python script every time the Raspberry Pi reboots. If you want your command to be run in the background while the Raspberry Pi continues starting up, add a space and & at the end of the line, like this:
@reboot python /home/pi/myscript.py &