Archive | March 4, 2014

The SSH Protocol

SSH (Secure SHell) is a network protocol which provides a replacement for insecure remote login and command execution facilities, such as telnet, rlogin and rsh. SSH encrypts traffic in directions, preventing traffic sniffing and password theft. SSH standard port 22. SSH also offers several additional useful features:

• Compression: traffic may be optionally compressed at the stream level.

• Public key authentication: optionally replacing password authentication.

• Authentication of the server: making “man-in-the-middle” attack more difficult

• Port forwarding: arbitrary TCP sessions can be forwarded over an SSH connection.

• X11 forwarding: SSH can forward your X11 sessions too.

• File transfer: the SSH protocol family includes two file transfer protocols.

Check the installation status for SSH packages on RHEL6 Linuxssh_0701

[root@server1 Desktop]# rpm -qa | grep openssh*

openssl-1.0.0-20.el6.x86_64

openssh-5.3p1-70.el6.x86_64

openssh-clients-5.3p1-70.el6.x86_64

openssh-askpass-5.3p1-70.el6.x86_64

openssh-server-5.3p1-70.el6.x86_64

Required service stop| start | restart

[root@client1 Desktop]# service sshd status

openssh-daemon (pid  2221) is running…

Boot level service starting

[root@client1 Desktop]# chkconfig sshd –list | on | off

sshd                 0:off    1:off    2:on     3:on     4:on     5:on     6:off

Check the SSH configuration file

[root@client1 Desktop]# rpm -qlc openssh-server

/etc/pam.d/ssh-keycat

/etc/pam.d/sshd

/etc/ssh/sshd_config                –           configuration file

/etc/sysconfig/sshd

Check the SSH default port number

[root@server1 Desktop]# netstat -tulnp | grep ssh

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      2143/sshd

tcp        0      0 :::22                       :::*                        LISTEN      2143/sshd

Scan the remote server default SSH port numer

[root@server1 Desktop]# nmap -sTU -p 22 station1.example.com

Starting Nmap 5.21 ( http://nmap.org ) at 2012-12-10 15:43 IST

Nmap scan report for station1.example.com (192.168.1.101)

Host is up (0.00082s latency).

PORT   STATE  SERVICE

22/tcp open   ssh

22/udp closed ssh

MAC Address: 00:0C:29:39:E2:9B (VMware)

Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds

Basic SSH usage

Remote login

The basic syntax to log into a remote host is

ssh hostname

If you want to specify a username, you may do it using an rlogin-compatible format:

ssh -l user hostname    or         ssh user@hostname

If you are running your sshd on a non-standard port, you may also specify that on the command-line:

ssh -p 2222 user@hostname

Initial server key discovery

The first time you client connects to ssh server, it asks you to verify the server’s key.

[root@server1 Desktop]# ssh station1.example.com

The authenticity of host ‘station1.example.com (192.168.1.101)’ can’t be established.

RSA key fingerprint is 2e:53:bc:ff:f5:c7:39:34:e2:37:14:c1:59:00:fc:01.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added ‘station1.example.com,192.168.1.101’ (RSA) to the list of known hosts.

root@station1.example.com’s password:

This is done to prevent an attacker impersonating a server, which would give them the opportunity to capture your password or the contents of your session. Once you have verified the server’s key, it is recorded by the client in ~/.ssh/known_hosts so it can be automatically checked upon each connection. If the server’s key changes, the client raises a warning:

[root@server1 Desktop]# cat /root/.ssh/known_hosts

station1.example.com,192.168.1.101 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvf/OzChNlHyidERR2Rk+kv99gdT+CUh5ghPlM+Twc0GzD3xkTpTm0HBT5qD1VyiqNP9DQWf+MTbizRHCnKon/slItM6D4pZMBKT9TnBPAPaEiG8chAiLqY7G7OaclON8VUoPofcmr15wmJHcrSFkAsaZwF6x5HwZBcbD4hw3xO5h/GK5Tk5PsmNLiRLYcOWDhz3sI5HeR2SnigpsO9FynAeK0b2N0F+WHWCIu0CJBMsq2AgfMRNj01w+Ug0aVEoVuUe7VUngxFJTJYxaMKVBks29atmUE0OG+I8U0VQsyAYgd6xozh6DznkpaGgJ1nq5mRzyu4VObf3Scf1nxu8k9Q==

Executing commands remotely

SSH also supports remote command execution. When you log in, a pseudo-terminal is assigned to your session and your session will remain open until you explicitly log out or is killed from the server end. In remote command execution mode, SSH will execute your specified command with the remote user’s shell and then exit as soon as it finished:

[root@server1 Desktop]# ssh root@station2.example.com “cat /etc/hosts”

root@station2.example.com’s password:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

192.168.1.102 station2.example.com station2

[root@server1 Desktop]# ssh -t root@station2.example.com “vim /etc/hosts”

root@station2.example.com’s password:

:q!

Connection to station2.example.com closed.

[root@server1 Desktop]#

File transfer

SSH offers a number of ways to transfer files between machines. Most of these take advantage of the aforementioned input/output redirection features of SSH.

scp

scp is the original SSH file transfer mechanism. It is modeled on BSD rcp, a protocol with a 15+ year history which has no RFC. Its syntax is very simple:

scp [user@]host:/path/to/source/file /path/to/destination/file

Will copy a remote file to a local destination. To copy a local file to a remote destination, one

uses the opposite syntax:

scp /path/to/source/file [user@]host:/path/to/destination/file

In either of these cases, the source file may be a wild-card matching multiple files. If a patch is left off the destination file specification, the remote user’s home directory is assumed. E.g.:

scp /home/djm/*.diff hachi:

scp does not support copying between two remote destinations very well. It is possible using the following syntax:

scp [user@]host1:/path [user@]host2:/path

For this to work, host1 must be configured for password less access to host2 (see section 4). Also

little feedback is given to the user on whether the operation succeeded. scp can also copy files recursively:

scp -r source-path [user@]host:/destination-path

scp -r [user@]host:/source-path /destination-path

rsync

Rsync4 is a package and algorithm to two sets of files into synchronisation. Rsync just sends the differences between the two sets of files over the network instead of sending their entire contents.

Rsync is often used as a very powerful mirroring process or as a replacement for the scp/rcp command. Rsync includes support for ssh with a single command-line option.

Rsync can be used to simple list files on the remote machine, in a particular directory:

rsync -e ssh djm@hachi:/tmp/

To synchronise/copy a remote set of files to a local set:

rsync -ve ssh djm@hachi:/bin/c* /tmp

To synchronise/copy a local set of files with a local set:

rsync -ve ssh djm@hachi:/bin/c* /tmp

Rsync has many more options and features, these are best described in its excellent man page.

[root@server1 Desktop]# touch a b c

[root@server1 Desktop]# rsync -r /root/Desktop/    station1.example.com:/root/Desktop/

root@client1.example.com’s password:

Public key authentication

SSH includes an ability to authenticate users using public keys. Instead of authenticating the user with a password, the server will verify a challenge signed by the user’s private key against its copy of the user’s public key. Setting up public key authentication requires you to generate a public/private key pair and install the public portion on the server. It is also possible to restrict what a given key is able to do and what addresses they are allowed to log in from.

Generating public keys

To generate a public key, use the ssh-keygen utility. ssh-keygen can generate three types of keys: rsa, dsa and rsa1. rsa1 keys are used for authentication by the legacy SSH protocol v.1, the other two types may be used for SSH protocol v.2 public key authentication. Select the type of key that you wish to generate by passing the -t option to ssh-keygen. Normally you will want to use rsa keys as they are somewhat faster to authenticate than dsa keys.

[root@server1 Desktop]# su – senthil

[senthil@server1 ~]$ ssh-keygen -t rsa

Generating public/private rsa key pair.

Enter file in which to save the key (/home/senthil/.ssh/id_rsa):

Created directory ‘/home/senthil/.ssh’.

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/senthil/.ssh/id_rsa.

Your public key has been saved in /home/senthil/.ssh/id_rsa.pub.

The key fingerprint is:

93:4e:69:c2:a2:5b:a6:f3:04:e1:c3:cc:2d:69:a2:a7 senthil@server1.example.com

The key’s randomart image is:

+–[ RSA 2048]—-+

|                 |

|                 |

|  .              |

| = + .   o       |

|. @ o o S        |

|.o = . = .       |

|. o +   .        |

| o.*             |

|E oo.            |

+—————–+

[senthil@server1 ~]$ ssh-copy-id babu@station1.example.com

The authenticity of host ‘station1.example.com (192.168.1.101)’ can’t be established.

RSA key fingerprint is 2e:53:bc:ff:f5:c7:39:34:e2:37:14:c1:59:00:fc:01.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added ‘station1.example.com,192.168.1.101’ (RSA) to the list of known hosts.

babu@station1.example.com’s password:

Now try logging into the machine, with “ssh ‘babu@station1.example.com'”, and check in:

.ssh/authorized_keys

to make sure we haven’t added extra keys that you weren’t expecting.

Now doesn’t required ssh login password

[senthil@server1 ~]$ ssh babu@station1.example.com

[babu@station1 ~]$ logout

Connection to station1.example.com closed.

[senthil@server1 ~]$ logout

Now check other user ssh login password required

[root@server1 Desktop]# ssh babu@station1.example.com

babu@station1.example.com’s password:

Last login: Mon Dec 10 18:16:17 2012 from server1.example.com

[babu@station1 ~]$ logout

Connection to station1.example.com closed.

[root@server1 Desktop]#

[root@server1 Desktop]# ll -a /home/senthil/.ssh/

total 20

drwx——. 2 senthil senthil 4096 Dec 10 18:15 .

drwx——. 5 senthil senthil 4096 Dec 10 18:15 ..

-rw——-. 1 senthil senthil 1675 Dec 10 18:15 id_rsa

-rw-r–r–. 1 senthil senthil  409 Dec 10 18:15 id_rsa.pub

-rw-r–r–. 1 senthil senthil  416 Dec 10 18:15 known_hosts

[root@server1 Desktop]# su – senthil

[senthil@server1 ~]$ ssh babu@station1.example.com

Last login: Mon Dec 10 18:16:36 2012 from server1.example.com

[babu@station1 ~]$ pwd

/home/babu

[babu@station1 ~]$ ll -a .ssh/

total 12

drwx——. 2 babu babu 4096 Dec 10 18:15 .

drwx——. 5 babu babu 4096 Dec 10 18:15 ..

-rw——-. 1 babu babu  409 Dec 10 18:15 authorized_keys

[babu@station1 ~]$ cat .ssh/authorized_keys

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApcKFNDg7+12XyCTO2khbUaLTdyrxD+HoHy4e2Kq4ihghQJW7A/FPJqZdd5yreKxiolHAcqnSHFCDCiTk/v7C3l8LJpx4mifM81x6ZwXTBBfNANKFERob3cIbWstW2nv+smar+2j+KzkdXKIcc87V7IIG5mUAzHfN+1F8PUOg+bwGzbjwxuXK/aZZAR1DlrBnoqY6XZXmSLwCg0LmkPMZ0aXcL5gFHVeUEZBZOJQ0duVoJufSJm6giQu8CWqgvQJKKN4uTB/rCfLsiGzq7qOSK6As+8swtdySVP10c6PyWBf/XNQZx4mvYRu1acbY4TdjBE5gnrzHMkr5xCXIUZ4X5Q== senthil@server1.example.com

[babu@station1 ~]$ logout

Connection to station1.example.com closed

.

[senthil@server1 ~]$ cat .ssh/id_rsa.pub

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApcKFNDg7+12XyCTO2khbUaLTdyrxD+HoHy4e2Kq4ihghQJW7A/FPJqZdd5yreKxiolHAcqnSHFCDCiTk/v7C3l8LJpx4mifM81x6ZwXTBBfNANKFERob3cIbWstW2nv+smar+2j+KzkdXKIcc87V7IIG5mUAzHfN+1F8PUOg+bwGzbjwxuXK/aZZAR1DlrBnoqY6XZXmSLwCg0LmkPMZ0aXcL5gFHVeUEZBZOJQ0duVoJufSJm6giQu8CWqgvQJKKN4uTB/rCfLsiGzq7qOSK6As+8swtdySVP10c6PyWBf/XNQZx4mvYRu1acbY4TdjBE5gnrzHMkr5xCXIUZ4X5Q== senthil@server1.example.com

[senthil@server1 ~]$

How to reduce the Delay in SSH Login Prompt:

You may came across this situation. At the time of logging in the shell prompt using SSH,

– Connection will be taking a fraction of second

– After/While entering the Password its taking more time to provide the shell prompt.

To fix this issue:

This is related to DNS. We have to change dns related entries in ssh config file to reduce this delay.

Note :

Be careful when doing this on production servers.

This activity may disconnect all the users from the system who are logged in to that machine using SSH.

By default UseDNS option in this file is disable. We have to uncomment this option and then edit this entry to no. As below..

# vi /etc/ssh/sshd_config 

Just search for UseDNS..

#UseDNS yes  

Change that to, (Simply Uncomment it)

UseDNS no

save and exit the file and then just reload ssh service to take effect what ever changes we did..

# service sshd reload

Now try to login and observe, delay will be reduced.

How to Disable SSH root login:

Providing direct login access to root via SSH is not a good practice. Administrators should use sudo to switch to root after logged in as themselves. this will helpful in auditing in terms of security.

Here is the step by step procedure to disable/deny direct root login via SSH

1. Login to the server as Root

2. Edit /etc/ssh/sshd_config

Look for the line,

PermitRootLogin=Yes

and then change the value of it to,

PermitRootLogin=No 

3. Restart the sshd service and make sure its turned on

service sshd restart        or     /etc/init.d/sshd restart
service sshd status

 

 

Network File System (NFS)

Network File System (NFS)

A NFS allows remote hosts to mount the file system over a network and interact with those file system as though they are mounted locally.

1.      Currently there are three version of NFSv2, NFSv3 and NFSv4

2.      NFSv2 is older and is widely supported. NFSv3 support safe asynchronous writes and a more robust error handling that NFSv2; it also support 64-bit file sizes and offsets, allowing clients to access more than 2GB of file data.

3.      NFSv4 works through firewalls and on the internet, no longer requires an “rpcbind” service, supports ACLs, and utilizes “stateful” operations. RHEL 6 support NFSv2, NFSv3 and NFSv4 clients. When mounting a file system via NFS, Red hat Enterprise Linux uses NFSv4 by default, if the server supports it.

4.      All version of NFS can use “Transmission Control Protocol” (TCP) running over an IP network, with NFSv4 requiring it. NFSv2 and NFSv3 can use the “User Datagram Protocol” (UDP) running over an IP network to provide a “stateless” network connection between the client and server.

5.      TCP port 2049 is the default protocol for NFSv2 and NFSv3 under RHEL. UDP can be used for compatibility purpose as needed, but is not recommended for wide usage. NFSv4 requires TCP.

Note:

1.      A “stateful” protocol expects a response. A “stateless” protocol doesn’t care.

Example

A stateless protocol is akin to TV broadcast –the broadcast doesn’t care if you watch it, if you like it, if you talk to it etc. The TV broadcast has no expectations.

TCP

UDP

Reliable

Unreliable

Connection – oriented

Connectionless

Segment retransmission and flow control through windowing

No windowing or retransmission

Segment sequence

No sequence

Acknowledge segments

No acknowledgement

 

2.      The “portmap” services was used to map RPC program numbers to IP address port number combination in earlier version of RHEL. This service is now replaced by “rpcbind” in RHEL 6 to enable IPv6 support.

Configuration and status files
*/etc/exports
*/var/lib/nfs/rmtab
*/var/lib/nfs/xtab
*/etc/hosts.allow
*/etc/hosts.deny
Daemons
*rpc.portmap(rpcbind for RHEL 6)
*rpc.mountd
*rpc.nfsd
*rpc.statd
*rpc.lockd
*rpc.rquotad
Scripts and commands
*/etc/rc.d/init.d/nfs
*nfstat
*showmount
*rpcinfo
*exportfs
Required Services

a>    nfs

“service nfs start” starts the NFS server and the appropriate RPC processes to service request for shared NFS file system.

b>    nfslock

”service nfslock start” activates a mandatory service that starts the appropriate RPC processes which allow NFS clients to lock files on the server.

c>    rpcbind

“rpcbind” accept port reservation from local RPC services. These ports are then made available (or advertised) so the responding remote RPC services can access them. rpcbind responds to request for RPC services and sets up connections to the requested RPC service. This is not used with NFSv4.

RPC services

rpc.mountd

This process is used by an NFS server to process MOUNT requests from NFSv2 and NFSv3 clients. It checks that the requested NFS share is currently exported by the NFS server, and that the client is allowed to access it. If the mount request is allowed, the rpc.mountd server replies with a Success status and provides the File-Handle for this NFS share back to the NFS client.

rpc.nfsd

rpc.nfsd allows explicit NFS versions and protocols the server advertises to be defined. It works with the Linux kernel to meet the dynamic demands of NFS clients, such as providing server threads each time an NFS client connects. This process corresponds to the nfs service.

lockd

lockd is a kernel thread which runs on both clients and servers. It implements the Network Lock Manager (NLM) protocol, which allows NFSv2 and NFSv3 clients to lock files on the server. It is started automatically whenever the NFS server is run and whenever an NFS file system is mounted.

rpc.statd

This process implements the Network Status Monitor (NSM) RPC protocol, which notifies NFS clients when an NFS server is restarted without being gracefully brought down. rpc.statd is started automatically by the nfslock service, and does not require user configuration. This is not used with NFSv4.

rpc.rquotad

This process provides user quota information for remote users. rpc.rquotad is started automatically by the nfs service and does not require user configuration.

rpc.idmapd

rpc.idmapd provides NFSv4 client and server upcalls, which map between on-the-wire NFSv4 names (which are strings in the form of user@domain) and local UIDs and GIDs. For idmapd to function with NFSv4, the /etc/idmapd.conf must be configured. This service is required for use with NFSv4, although not when all hosts share the same DNS domain name.

 

 

Starting and Stopping NFS

 

[root@server1 Desktop]# service rpcbind start

[root@server1 Desktop]# service nfs start

Starting NFS services:                                      [  OK  ]

Starting NFS quotas:                                        [  OK  ]

Starting NFS daemon:                                     [  OK  ]

Starting NFS mountd:                                      [  OK  ]

 

nfslock must also be started for both the NFS client and server to function properly. To start NFS locking, use the following command:

 

[root@server1 Desktop]# service nfslock start

 

[root@server1 Desktop]# chkconfig nfslock on

[root@server1 Desktop]# chkconfig nfs on

[root@server1 Desktop]# chkconfig rpcbind on

 

NFS Configuration

 

There are two ways to configure an NFS server

a>     By manually editing the NFS configuration file, i.e. /etc/exports

b>    Through the command link, i.et. through “exportfs”

 

The “/etc/exports” configuration file

Refer to “man exports” for details on these less-used options.

 

Export host(options)

 

Export –           the directory being exported

Host    –           the host or network to which the export is being shared

Options           –           the options to be used for host

 

Export host1(options1)           host2(options2)           host3(options3)

 

Examples

/exported/directory    server1.example.com

 

The default settings are (ro, sync, wdelay, root_squash)

ro, rw, sync, async, wdelay, no_wdelay, root_squash, no_root_squash

 

By default, access control lists ( ACLs) are supported by NFS under Red Hat Enterprise Linux. To disable this feature, specify the no_acl option when exporting the file system.

 

ro         –           read only

rw        –           read,write

sync     –           the server will only acknowledge data after it’s written out in the disk.

aync     –           the server will acknowledge data before it’s committed to disk, which can lead to data corruption if the server crachses.

wdelay –           the nfs server will delay writing to the disk if it suspects another write request is imminent.

no_wdelay       –           disable the wdelay

root_squash     –           the nfs server will assign them the user ID nfsnobody.

no_root_squash           –           disable the root_squash

 

The exportfs command

 

Update the /etc/exports shared directory

Syntax:

exportfs           [options]

-a         –           exports / unexports all directories

-r         –           reexports all directories

-u         –           unexports one or more directories

-v         –           provides verbose output

 

Example:

[root@server1 Desktop]#mkdir /share

 

[root@server1 Desktop]# vim /etc/exports

/share   *.example.com(rw)

:wq!

 

[root@server1 Desktop]# exportfs -ar

[root@server1 Desktop]# exportfs -v

/share              *.example.com(rw,wdelay,root_squash,no_subtree_check)

Discovering the NFS exports

 

[root@server1 Desktop]# showmount -e

Export list for server1.example.com:

/share *.example.com

 

[root@client1 Desktop]# showmount -e server1.example.com

Export list for server1.example.com:

/share *.example.com

 

[root@client1 ~]# mkdir /nfs

[root@client1 ~]# mount -t nfs server1.example.com:/share /nfs

[root@client1 ~]# cd /nfs

[root@client1 nfs]# ll

total 0

-rw-rw-r–. 1 nobody    nobody    0 Nov 20 08:22 a

-rw-r–r–. 1 nfsnobody nfsnobody 0 Nov 20 08:23 b

-rw-rw-r–. 1 nobody    nobody    0 Nov 20 08:25 c

[root@client1 nfs]#

 

Mounting NFS File Systems using /etc/fstab

Syntax:

server:/remote/export /local/directory nfs options 0 0

 

Example:

[root@client1 ~]# vim /etc/fstab

192.168.1.100:/share  /nfs                              nfs       defaults           0 0

 

:wq!

 

[root@client1 ~]# mount –a

 

[root@client1 ~]# mount | grep nfs

sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)

192.168.1.100:/share on /nfs type nfs (rw,vers=4,addr=192.168.1.100,clientaddr=192.168.1.101)

 

Mount options

-ro     Read only
-rw     Mount the file system read and write, but can be restricted by the server, and a warning is flagged
-soft   if the server fails to respond, return an error after the timeout period ( -timeo=value ) expires and don’t bother to try again
-hard   if the server fails to respond, retry until it does respond
-bg     do the retrys in background mode
-nosuid Do not allow executables on the mounted file system to run as setuid.
-fstype file system type of the remote partition to mount
ext2    linux native
nfs     NFS type
iso9660 CDROM
-user   Allow users to mount the filesystem
-noexec Don’t allow execution of files from this filesystem
-nosuid Don’t allow programs in this filesystem to run as setuid or setgid

 

 

 

 

Running NFS behind a Firewall

NFS requires rpcbind, which dynamically assigns ports for RPC services and can cause problems for configuring firewall rules. To allow clients to access NFS shares behind a firewall, edit the /etc/sysconfig/nfs configuration file to control which ports the required RPC services run on.

The /etc/sysconfig/nfs may not exist by default on all systems. If it does not exist, create it and add the following variables, replacing portwith an unused port number (alternatively, if the file exists, un-comment and change the default entries as required):

 

MOUNTD_PORT=port

Controls which TCP and UDP port mountd ( rpc.mountd) uses.

STATD_PORT=port

Controls which TCP and UDP port status ( rpc.statd) uses.

LOCKD_TCPPORT=port

Controls which TCP port nlockmgr ( lockd) uses.

LOCKD_UDPPORT=port

Controls which UDP port nlockmgr ( lockd) uses.

If NFS fails to start, check /var/log/messages. Normally, NFS will fail to start if you specify a port number that is already in use. After editing /etc/sysconfig/nfs, restart the NFS service using service nfs restart. Run the rpcinfo -p command to confirm the changes.

To configure a firewall to allow NFS, perform the following steps:

Configure a firewall to allow NFS

  1. Allow TCP and UDP port 2049 for NFS.
  2. Allow TCP and UDP port 111 ( rpcbind/ sunrpc).
  3. Allow the TCP and UDP port specified with MOUNTD_PORT=”port
  4. Allow the TCP and UDP port specified with STATD_PORT=”port
  5. Allow the TCP port specified with LOCKD_TCPPORT=”port
  6. Allow the UDP port specified with LOCKD_UDPPORT=”port

Note

To allow NFSv4.0 callbacks to pass through firewalls set /proc/sys/fs/nfs/nfs_callback_tcpport and allow the server to connect to that port on the client. This process is not needed for NFSv4.1 or higher, and the other ports for mountd, statd, and lockd are not required in a pure NFSv4 environment.

 

Troubleshooting NFS and rpcbind

 

[root@server1 Desktop]# rpcinfo -p

   program vers proto   port  service

    100000    4   tcp    111  portmapper

    100000    3   tcp    111  portmapper

    100000    2   tcp    111  portmapper

    100000    4   udp    111  portmapper

    100000    3   udp    111  portmapper

    100000    2   udp    111  portmapper

    100024    1   udp  45999  status

    100024    1   tcp  59207  status

    100011    1   udp    875  rquotad

    100011    2   udp    875  rquotad

    100011    1   tcp    875  rquotad

    100011    2   tcp    875  rquotad

    100003    2   tcp   2049  nfs

    100003    3   tcp   2049  nfs

    100003    4   tcp   2049  nfs

    100227    2   tcp   2049  nfs_acl

    100227    3   tcp   2049  nfs_acl

    100003    2   udp   2049  nfs

    100003    3   udp   2049  nfs

    100003    4   udp   2049  nfs

    100227    2   udp   2049  nfs_acl

    100227    3   udp   2049  nfs_acl

    100021    1   udp  56223  nlockmgr

    100021    3   udp  56223  nlockmgr

    100021    4   udp  56223  nlockmgr

    100021    1   tcp  58726  nlockmgr

    100021    3   tcp  58726  nlockmgr

    100021    4   tcp  58726  nlockmgr

    100005    1   udp  35175  mountd

    100005    1   tcp  45458  mountd

    100005    2   udp  37640  mountd

    100005    2   tcp  58572  mountd

    100005    3   udp  49202  mountd

    100005    3   tcp  36921  mountd

 

 

NFS with SELinux

SELinux Boolean settings

 

[root@server1 ~]# getsebool -a | grep nfs

allow_ftpd_use_nfs –> off

allow_nfsd_anon_write –> off

cobbler_use_nfs –> off

git_system_use_nfs –> off

httpd_use_nfs –> off

nfs_export_all_ro –> on

nfs_export_all_rw –> on

qemu_use_nfs –> on

samba_share_nfs –> off

use_nfs_home_dirs –> on

virt_use_nfs –> off

xen_use_nfs –> off

 

 

 

 

Semanage require package

[root@server1 ~]# yum install policycoreutils*

 

[root@server1 ~]# semanage boolean -l | grep nfs

xen_use_nfs                    -> off   Allow xen to manage nfs files

virt_use_nfs                   -> off   Allow virt to manage nfs files

use_nfs_home_dirs              -> on    Support NFS home directories

allow_ftpd_use_nfs             -> off   Allow ftp servers to use nfs used for public file transfer services.

git_system_use_nfs             -> off   Allow Git daemon system to access nfs file systems.

qemu_use_nfs                   -> on    Allow qemu to use nfs file systems

cdrecord_read_content          -> off   Allow cdrecord to read various content. nfs, samba, removable devices, user temp and untrusted content files

allow_nfsd_anon_write          -> off   Allow nfs servers to modify public files used for public file transfer services.  Files/Directories must be labeled public_content_rw_t.

cobbler_use_nfs                -> off   Allow Cobbler to access nfs file systems.

httpd_use_nfs                  -> off   Allow httpd to access nfs file systems

samba_share_nfs                -> off   Allow samba to export NFS volumes.

nfs_export_all_rw              -> on    Allow any files/directories to be exported read/write via NFS.

nfs_export_all_ro              -> on    Allow any files/directories to be exported read/only via NFS.

 

To show that SELinux is still able to block access even when Linux permissions are completely open, give the /share directory full Linux access rights for all users:

[root@server1 ~]# chmod 777 /share

 

[root@server1 ~]# setsebool -P nfs_export_all_rw on

 

SELinux file context label

 

By default, mounted NFS file systems on the client side are labeled with a default context defined by policy for NFS file systems. In common policies, this default context uses the nfs_t type.The following types are used with NFS. Different types allow you to configure flexible access:

 

var_lib_nfs_t

This type is used for existing and new files copied to or created in the /var/lib/nfs directory. This type should not need to be changed in normal operation. To restore changes to the default settings, run the restorecon -R -v /var/lib/nfs command as the root user.

 

nfsd_exec_t

The /usr/sbin/rpc.nfsd file is labeled with the nfsd_exec_t, as are other system executables and libraries related to NFS. Users should not label any files with this type. nfsd_exec_t will transition to nfsd_t.

 

[root@client1 ~]# ls -dZ /nfs

drwxrwxrwx. root root system_u:object_r:nfs_t:s0       /nfs

 

NFS Server and Client example configuration

 

Server1.example.com   –              192.168.1.100

Client1.example.com    –              192.168.1.101

 

Check the NFS installation default installation packages

[root@server1 ~]# rpm -qa nfs*

nfs4-acl-tools-0.3.3-5.el6.x86_64

nfs-utils-lib-1.1.5-4.el6.x86_64

nfs-utils-1.2.3-15.el6.x86_64

 

[root@server1 ~]# rpm -qa rpcbind*

rpcbind-0.2.0-8.el6.x86_64

 

[root@server1 ~]# rpm -qlc nfs-utils

/etc/nfsmount.conf

/etc/rc.d/init.d/nfs

/etc/rc.d/init.d/nfslock

/etc/rc.d/init.d/rpcgssd

/etc/rc.d/init.d/rpcidmapd

/etc/rc.d/init.d/rpcsvcgssd

/etc/sysconfig/nfs

/var/lib/nfs/etab

/var/lib/nfs/rmtab

/var/lib/nfs/state

/var/lib/nfs/xtab

 

Create a shared directory and give full permission

[root@server1 ~]# mkdir /share

 

[root@server1 ~]# chmod 777 /share

 

[root@server1 ~]# ll -dZ /share/

drwxrwxrwx. root root unconfined_u:object_r:default_t:s0 /share/

 

[root@server1 ~]# service nfs start

Starting NFS services:                                     [  OK  ]

Starting NFS quotas:                                       [  OK  ]

Starting NFS daemon:                                       [  OK  ]

Starting NFS mountd:                                       [  OK  ]

 

[root@server1 ~]# service rpcbind status

rpcbind (pid  2054) is running…

 

[root@server1 ~]# vim /etc/exports

/share   192.168.1.0/24(rw)

 

:wq!

 

[root@server1 ~]# showmount -e

Export list for server1.example.com:

/share 192.168.1.0/24

 

[root@server1 ~]# exportfs -ar

[root@server1 ~]# exportfs -v

/share                   192.168.1.0/24(rw,wdelay,root_squash,no_subtree_check)

 

[root@server1 ~]# getsebool -a | grep nfs

allow_ftpd_use_nfs –> off

allow_nfsd_anon_write –> off

cobbler_use_nfs –> off

git_system_use_nfs –> off

httpd_use_nfs –> off

nfs_export_all_ro –> on

nfs_export_all_rw –> on

qemu_use_nfs –> on

samba_share_nfs –> off

use_nfs_home_dirs –> on

virt_use_nfs –> off

xen_use_nfs –> off

 

Client side mountings steps

 

[root@client1 Desktop]# showmount -e server1.example.com

Export list for server1.example.com:

/share 192.168.1.0/24

 

[root@client1 Desktop]# mkdir /nfs

 

[root@client1 Desktop]# vim /etc/fstab

 

192.168.1.100:/share      /nfs                                        nfs          defaults               0 0

 

:wq!

 

[root@client1 Desktop]# mount –a

 

[root@client1 Desktop]# mount | grep nfs

sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)

192.168.1.100:/share on /nfs type nfs (rw,vers=4,addr=192.168.1.100,clientaddr=192.168.1.101)

 

[root@client1 Desktop]# ls -dZ /nfs

drwxrwxrwx. root root system_u:object_r:nfs_t:s0       /nfs

 

[root@client1 Desktop]# cd /nfs/

[root@client1 nfs]# touch a b c

[root@client1 nfs]# ll

total 0

-rw-r–r–. 1 nfsnobody nfsnobody 0 Nov 20 13:37 a

-rw-r–r–. 1 nfsnobody nfsnobody 0 Nov 20 13:37 b

-rw-r–r–. 1 nfsnobody nfsnobody 0 Nov 20 13:37 c

 

[root@client1 nfs]# rm -rf c

Advanced Practical:

To share the nfs server for different networks.

1)To assigne the virtual IP.
2)export the directory & assigne the permitions.
3)restart the service.
4)Try to connect from client side.

*To assigne the virtual IP.
#netconfig –device eth0:1
10.0.0.2 255.0.0.0

*Restart the service.
#service network restart

*To configure the export file.
#vim /etc/exports

/share 10.0.0.3/8(ro,sync)

/share 10.0.0.0/8(rw,sync)

/reliance 192.168.1.0/24(rw,sync)

*To create the directory.
#mkdir /reliance
#chmod 777 /reliance/

*To restart the service.
# service portmap restart
#service nfs restart

*To check.
#exportfs -rav

Client side configuretion:

*To check from clientside.
#showmount -e (server IP)
#showmount -e 10.0.0.2
*To create the directory.
#mkdir /mount

*To mount the export directory by server.
#mount 10.0.0.2:/reliance /mount

*Directory should be mount but that directory is a read-only.

Common NFS errors & solutions:

1.”Server Not Responding” Message
2.  “Access Denied” Message
3.”Permission Denied” Message
4.  “Device Busy” Message

Error 1: If You Receive an NFS “Server Not Responding” Message

ping the nfs server from client

1.ping “nfs serer name or ip”

2./usr/bin/rpcinfo -p servername

The rpcinfo command should display the following processes:

* portmap
* nfs
* mountd
* status
* nlockmgr
* llockmgr

If any of these processes is not running, follow the below steps:

a.Make sure the /etc/rc.config.d/nfsconf file on the NFS server contains the following lines:

NFS_SERVER=1
START_MOUNTD=1

b.Make sure that the /etc/inetd.conf file on the NFS server does not contain a line to start rpc.mountd.
If it does, make sure the START_MOUNTD variable in /etc/rc.config.d/nfsconf is set to 0.

c.Issue the following command on the NFS server to start all the necessary NFS processes:

#/sbin/init.d/nfs.server start

Error 2: If You Receive an “Access Denied” Message

a.check the FS is exported or not

#/usr/sbin/showmount -e server_name

(If it is not exported means u have to edit /etc/exports file in NFS server and put the necessary entry and
then run the command
/usr/sbin/exportfs -a)

Error 3 :If You Receive a “Permission Denied” Message

a.Check the mount options in the /etc/fstab file on the NFS client. A directory you are attempting to write to may have
been mounted read-only.

b.Issue the ls -l command to check the HP-UX permissions on the server directory and on the client directory
that is the mount point. You may not be allowed access to the directory.

c.Issue the following command on the NFS server:

/usr/sbin/exportfs

Or, issue the following command on the NFS client:

/usr/sbin/showmount -e server_name

d. Check the export permissions on the exported directory. The directory may have been exported read-only to your client.
The system administrator of the NFS server can use the remount mount
option to mount the directory read/write without unmounting it

Error 4 : If You Receive a “Device Busy” Message

a.If you received the “device busy” message while attempting to mount a directory, try to access the mounted directory.
If you can access it, then it is already mounted.

b.If you received the “device busy” message while attempting to unmount a directory, a user or process is currently using the directory. Wait until the process completes, or follow these steps:

1.Issue the following command to determine who is using the mounted directory:

/usr/sbin/fuser -cu local_mount_point

The fuser(1M) command will return a list of process IDs and user names that are currently using the directory
mounted under local_mount_point. This will help you decide whether to kill the processes or wait for them to complete.

2. To kill all processes using the mounted directory, issue the following command:

/usr/sbin/fuser -ck local_mount_point

3. Try again to unmount the directory.

TROUBLESHOOTING

Difference between /bin vs /sbin vs /usr/bin vs /usr/sbin

/bin This directory contains executable programs which are needed in
single user mode and to bring the system up or repair it.

/sbin Like /bin, this directory holds commands needed to boot the sys-
tem, but which are usually not executed by normal users.

/usr/bin
This is the primary directory for executable programs. Most
programs executed by normal users which are not needed for boot-
ing or for repairing the system and which are not installed
locally should be placed in this directory.

/usr/sbin
This directory contains program binaries for system administra-
tion which are not essential for the boot process, for mounting
/usr, or for system repair.

Install D-Link DWA 525 N 150 Wireless Over Linux or Fedora 14
After a long time spending over google I find some useful NOTES over how to install D-Link DWA 525 N 150 Wireless Drivers, which are here:

Run command “lspci |grep -i network”
Output will be like :
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 03)
06:02.0 Network controller: RaLink Device 3060

Go to http://www.ralinktech.com/support.php?s=2 and download RT3062PCI/mPCI/CB/PCIe(RT3060/RT3062/RT3562/RT3592)

This will ask for your Name and Mail ID, enter and when you click on Accept this will ask you for save or open. Save file to anywhere on your machine, lets say in /opt/

Go to /opt/ and run following command:
cd /opt
tar zxvf DPO_RT3562_3592_3062_LinuxSTA_V2.4.1.1_20101217.tgz
cd DPO_RT3562_3592_3062_LinuxSTA_V2.4.1.1_20101217

Change following in os/linux/config.mk file
vim os/linux/config.mk
HAS_WPA_SUPPLICANT = n -> HAS_WPA_SUPPLICANT = y
HAS_NATIVE_WPA_SUPPLICANT_SUPPORT = n -> HAS_NATIVE_WPA_SUPPLICANT_SUPPORT = y

After making above changes run following:
make
make install

After successfully completion of above command, run following:
insmod os/linux/rt3562sta.ko

Upgrade Fedora 7 to Fedora 8

Before upgrading your OS version we must take the backup of our system firstly. For upgrading to Fedora 8 from Fedora 7 follow the given below commands:

Update your packages:

yum update

Run following command to clear the yum cache:

yum clean all
Then run following command to install fedora 8 release packages:

rpm -Uvh ftp://ftp.uni-bayreuth.de/pub/redhat.com/fedora-archive/linux/releases/8/Everything/ppc64/os/Packages/fedora-release-8-3.noarch.rpm

rpm -Uvh ftp://ftp.uni-bayreuth.de/pub/redhat.com/fedora-archive/linux/releases/8/Everything/ppc64/os/Packages/fedora-release-notes-8.0.0-3.noarch.rpm

Now this is the time to run upgrade over the machine:

yum upgrade

If it stops with an error like this one:

—> Package orca.i386 0:2.20.0.1-1.fc8 set to be updated
–> Finished Dependency Resolution
Error: Missing Dependency: gecko-libs = 1.8.1.8 is needed by package yelp

simply uninstall the package that is causing the problem (in this case yelp) (I only had to do this with the yelp package which doesn’t seem to be overly important)…

yum remove yelp

Ref. : http://www.howtoforge.com/upgrading-fedora7-desktop-to-fedora8

For upgrade from Fedora8 to Fedora 9, use below given release RPMs and other are same as above

rpm -Uhv http://mirror.liberty.edu/pub/fedora/linux/releases/9/Fedora/i386/os/Packages/fedora-release-9-2.noarch.rpm http://mirror.liberty.edu/pub/fedora/linux/releases/9/Fedora/i386/os/Packages/fedora-release-notes-9.0.0-1.noarch.rpm

Upgrading from Fedora 9 to Fedora 10, follow below given URL:

Linux Security

—–>   Enable Authentication for Single-User Mode

Single-User Mode is used for a system recovery. However, by default, no authentication is used if single-user mode is selected. This can be used to bypassing security on the server and gaining root access. To enable authentication for single-user mode, open the /etc/inittab, file:

# vi /etc/inittab

Add the following line to the file:

~~:S:wait:/sbin/sulogin

 

—–> Disable Interactive Hotkey Startup at Boot

A few Linux distribution like Fedora, CentOS or RHEL allows the console user to perform an interactive system startup by pressing [I] key. Using interactive boot, attacker can disable the firewall and other system services. Open /etc/sysconfig/init file:

# vi /etc/sysconfig/init

Modify the setting as follows:

PROMPT=no

—–> Setup Time-out for Login Shells

 Go into the user’s home director:

# vi .bash_profile

TMOUT=300
readonly TMOUT
export TMOUT

In case of dealing with SSH, we need to define/enter the following:

To set an idle timeout interval, after this interval has passed, the idle user will be automatically logged out. Open /etc/ssh/sshd_config file, enter:

vi /etc/ssh/sshd_config

Find ClientAliveInterval and set to 300 (5 minutes) as follows:

ClientAliveInterval 300
ClientAliveCountMax 0

Save and close the file. Restart sshd:
# service sshd restart

Redhat Linux : Rollback RPMs

RPM Rollback for Redhat 5.x versions

1) Create a file /etc/rpm/macros and put following

cat >> /etc/rpm/macros
%_repackage_all_erasures 1

2) Add following at the end of /etc/yum.conf

echo “tsflags=repackage” >> /etc/yum.conf

After above entries, we can rollback rpms installed using yum

3) Now update system with single rpm or complete using

yum update

4) Lets say we had update rpms 1 hour, 2 month and 1 day ago and wants to remove all those then use following commands:

rpm –rollback “1 day ago”
rpm –rollback “1hour ago”
rpm –rollback “2 month ago”

Will be posting for Redhat 6.x version soon…….

Linux login issue – Can not login: Resource temporarily not available

Sometime we get following error while user login:

$su – username
Coud not login: Resource temporarily not available

Most of the times this is because of processes or number of files available to user is already used. So, could not arrange more files/processes to login, in this case we required to increase the limits for user in /etc/security/limits.conf (PAM module)

username        soft    nproc           3000
username        hard    nproc          4096
username        soft     nofile           6000
username        hard    nofile          8192

Set these values as per requirement else setting up these values higher may result in server inaccessible in case that particular uses all file descriptors, process and higher memory of server.

Linux Resize LUN Without Reboot

Try running following commands

Check OS using what devices for attached LUNs:

multipath -l

mpath5 (360060…………………..) dm-15

[size=100G][features=1 queue_if_no_path][hwhandler=1 emc][rw]

\_ round-robin 0 [prio=0][active]

\_ 1:0:0:14 sdb 66:192 [active][undef]

\_ 0:0:0:14 sdc  8:224  [active][undef]

\_ round-robin 0 [prio=0][enabled]

\_ 0:0:1:14 sdd 66:112 [active][undef]

\_ 1:0:1:14 sde 67:176 [active][undef]

Rescan all paths:

echo 1 > /sys/block/sdb/device/rescan

echo 1 > /sys/block/sdc/device/rescan

echo 1 > /sys/block/sdd/device/rescan

echo 1 > /sys/block/sde/device/rescan

Then run:
partprobe

multipathd -k
resize map mpath5

If LVM is used, also required following:

#pvscan

Check Disk Changes detected under LVM:

#pvs

#vgscan

Check VG Size is Increased:

#vgs

Now Extend the LV:

#lvextend -L +G

Finally Extend the File System

#resize2fs

Redhat Device Mapper Multipathing

REDHAT DEVICE MAPPER MULTIPATH

1) DM Software Installation

yum install device-mapper-multipath

2) Initialize /etc/multipath.conf file

mpathconf –enable

3) Start multipath service

service multipathd start

4) If you do not want to use user friendly name

mpathconf –enable –user_friendly_names n

5) Ignoring Local Disks when generating Multipath devices

multipath -v2 (shows local disk, /dev/sda, in the multipath map)

create: SIBM-ESXSST336732LC____F3ET0EP0Q000072428BX1 undef WINSYS,SF2372 size=33 GB features=”0″ hwhandler=”0″ wp=undef `-+- policy=’round-robin 0′ prio=1 status=undef
– 0:0:0:0 sda 8:0 [———

device-mapper ioctl cmd 9 failed: Invalid argument device-mapper ioctl cmd 14 failed: No such device or address

create: 3600a0b80001327d80000006d43621677 undef WINSYS,SF2372 size=12G features=’0′ hwhandler=’0′ wp=undef `-+- policy=’round-robin 0′ prio=1 status=undef
– 2:0:0:0 sdb 8:16 undef ready running `- 3:0:0:0 sdf 8:80 undef ready running

create: 3600a0b80001327510000009a436215ec undef WINSYS,SF2372 size=12G features=’0′ hwhandler=’0′ wp=undef `-+- policy=’round-robin 0′ prio=1 status=undef
– 2:0:0:1 sdc 8:32 undef ready running `- 3:0:0:1 sdg 8:96 undef ready running

In order to prevent the device mapper from mapping /dev/sda in its multipath maps, edit blacklist section in /etc/multipath.conf

blacklist {

wwid SIBM-ESXSST336732LC____F3ET0EP0Q000072428BX1


}

6) After updating file reload the changes

service multipathd reload

7) Run following command to remove multipath device

multipath -f SIBM-ESXSST336732LC____F3ET0EP0Q000072428BX1

8) Now check if device removed from multipath

multipath

create: 3600a0b80001327d80000006d43621677 undef WINSYS,SF2372 size=12G features=’0′ hwhandler=’0′ wp=undef `-+- policy=’round-robin 0′ prio=1 status=undef
– 2:0:0:0 sdb 8:16 undef ready running `- 3:0:0:0 sdf 8:80 undef ready running

create: 3600a0b80001327510000009a436215ec undef WINSYS,SF2372 size=12G features=’0′ hwhandler=’0′ wp=undef `-+- policy=’round-robin 0′ prio=1 status=undef
– 2:0:0:1 sdc 8:32 undef ready running `- 3:0:0:1 sdg 8:96 undef ready running

….

9) Add storage that is not supported by default as a know multipath device lets say “Vendor is HP, Product Open-V”

To add information about the HP Open-V series the entry looks like this, where %n is the device name. Add following in /etc/multipath.conf file

devices {


device {


vendor “HP”


product “OPEN-V.”


getuid_callout “/lib/udev/scsi_id –whitelisted –device=/dev/%n”

GRUB Image Files

GRUB consists of several images: a variety of bootstrap images for starting GRUB in various ways, a kernel image, and a set of modules which are combined with the kernel image to form a core image. Here is a short overview of them:

boot.img

On PC BIOS systems, this image is the first part of GRUB to start. It is written to a master boot record (MBR) or to the boot sector of a partition. Because a PC boot sector is 512 bytes, the size of this image is exactly 512 bytes.

The sole function of boot.img is to read the first sector of the core image from a local disk and jump to it. Because of the size restriction, boot.img cannot understand any file system structure, so grub-setuphardcodes the location of the first sector of the core image into boot.img when installing GRUB.

diskboot.img

This image is used as the first sector of the core image when booting from a hard disk. It reads the rest of the core image into memory and starts the kernel. Since file system handling is not yet available, it encodes the location of the core image using a block list format.

cdboot.img

This image is used as the first sector of the core image when booting from a CD-ROM drive. It performs a similar function to diskboot.img.

pxeboot.img

This image is used as the start of the core image when booting from the network using PXE. See Network.

lnxboot.img

This image may be placed at the start of the core image in order to make GRUB look enough like a Linux kernel that it can be booted by LILO using an ‘image=’ section.

kernel.img

This image contains GRUB’s basic run-time facilities: frameworks for device and file handling, environment variables, the rescue mode command-line parser, and so on. It is rarely used directly, but is built into all core images.

core.img

This is the core image of GRUB. It is built dynamically from the kernel image and an arbitrary list of modules by the grub-mkimage program. Usually, it contains enough modules to access /boot/grub, and loads everything else (including menu handling, the ability to load target operating systems, and so on) from the file system at run-time. The modular design allows the core image to be kept small, since the areas of disk where it must be installed are often as small as 32KB.

Initrd.img

initrd (initial ramdisk) is a scheme for loading a temporary file system into memory in the boot process of the Linux kernel. initrd and initramfs refer to slightly different methods of achieving this. Both are commonly used to make preparations before the real root file system can be mounted.

How to password protect GRUB?

There are only 3 steps to password protect users to edit grub properties while system booting:

1) Run following command to generate MD5 encrypted password:

root@localhost# grub-md5-crypt
Password:
Retype password:
$1$yAr5c0$ZYlcLULaS2rwOvry1B4gX/

2) Copy MD5 encrypted password of above command

3) Paste copied MD5 encrypted password in menu.list/grub.conf file :

default = 0
timeout=5
password –md5 $1$yAr5c0$ZYlcLULaS2rwOvry1B4gX/

Thats it!!!

Now whenever user’s try to run GRUB commands or try to change booting parameters at the time of BOOT, above entered text password will be required!!

Linux : How To Recover From Bad SuperBlock Corrupted Ext3 File System??

I was getting following error:
/dev/cciss/c0d0p1: Input/output error

mount: /dev/cciss/c0d0p1: can’t read superblock

In case you are also facing the same error with superblocks, you can follow below given steps to recover superblock:

#### dumpe2fs  /dev/cciss/c0d0p1|grep -i superblock

dumpe2fs 1.39 (29-May-2006)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery sparse_super
Primary superblock at 1, Group descriptors at 2-2
Backup superblock at 8193, Group descriptors at 8194-8194
Backup superblock at 24577, Group descriptors at 24578-24578
Backup superblock at 40961, Group descriptors at 40962-40962
Backup superblock at 57345, Group descriptors at 57346-57346
Backup superblock at 73729, Group descriptors at 73730-73730

Above command output showing back’d up superblock. Now we need to restore from these superblocks

#### fsck -b 8193 /dev/cciss/c0d0p1

If still showing any error continue to restore with next Backup superblock i.e;  24577, 40961 etc….

After successful completion of above command i.e; output will be like this

Free blocks count wrong for group #362 (32254, counted=32248).

Fix? yes

Free blocks count wrong for group #368 (32254, counted=27774).

Fix? yes

……….

/dev/cciss/c0d0p1: ***** FILE SYSTEM WAS MODIFIED *****

/dev/cciss/c0d0p1: 59586/30539776 files (0.6% non-contiguous), 3604682/61059048 blocks

Now mount your file system

##### mount  /dev/cciss/c0d0p1 /mnt

How To Access GNU Screen Session Over SSH??

We can attach a GNU SCREEN session remotely over SSH; in this example we’ll open a GNU screen session on host1, and connect to it from host2.

First open and then detach a screen session on host1, named testscreen:

host1 ~ $ screen -S testscreen

Then detach from your screen session with the keyboard combination Ctrl+a+d:

[detached from 3829.testscreen]

Do not “exit” from shell only use Ctrl+a+d to detach from that session. One of the main feature I like about screen is that we can trace whatever user was doing last time (in case of script command a typescript file is created which show the complete working of user)

You can verify that it’s still there with this command:

host1 ~ $ screen -ls

There is a screen on:
        3941.testscreen (03/18/2012 12:43:42 PM) (Detached)
1 Socket in /var/run/screen/S-host1.

Then re-attach to your screen session from host2 (because we just detached our session last time not exited, so this will start from the last point were we were detached from session):

host2 ~ $ ssh -t user@host1 screen -r testscreen

You don’t have to name the screen session if there is only one 🙂

Ref: http://www.itworld.com/it-managementstrategy/261500/16-ultimate-openssh-hacks

Redhat/CentOS/Fedora Linux: How to Setup Chroot SSH/SFTP

Find below given steps to setup chrooted SSH:

1) Create a group : groupadd sftpgroup

2) Create a user : useradd -g sftpgroup -d /home/mysftpuser -s /sbin/nologin mysftpuser

3) Open /etc/ssh/sshd_config file and comment following line

#Subsystem      sftp    /usr/libexec/openssh/sftp-server

4) Add following lines to /etc/ssh/sshd_config

Subsystem      sftp    internal-sftp
ChrootDirectory /home/%u

5) Save and exit from /etc/ssh/sshd_config file

6) Restart sshd service

7) Try to login from server/client machine

[nginx_test:main.LINUX5 ~]# sftp mysftp@127.0.0.1
Connecting to 127.0.0.1…
mysftp@127.0.0.1’s password:
sftp>

sftp> pwd
Remote working directory: /

What Are Unix/Linux Processes And Their Types…….

A process is a running instance of a program. In this article we used two terms ‘program’ and ‘running instance’. Suppose we run a program simultaneously 5 times, then corresponding to each instance there will be a process running in the system. So we say that a process is a “running instance” of a program.

As you already know, you can use ps command to view the processes running on your system. For effective use of the ps command, refer to 7 Practical PS Command Examples for Process Monitoring.

1. Peeping Inside a Process

Now, since we are clear with what exactly a process is, lets dig a bit deeper to see what a process consists of. A Unix process can be thought of as a container which contains:

Program Instructions

Program instructions are kept in text segments which are executed by CPU. Usually for programs like text editors which are executed frequently the text segment is shared. This segment has read only privileges which means that a program cannot modify its text segment.

Data

Mostly the data is kept in data segment. Data segment can be classified into initialized data segment and uninitialized data segment. As the name suggest, initialized data segment contains those global variables which are initialized before hand while uninitialized data segment (also known as ‘BSS’ segment) contains uninitialized global variables. Also, static variables are stored in data segment.

Local variables which are local to functions are stored on stack. Stack is particular to a function and besides containing the information about local variables it also contains information about the address where the flow will return once the execution of function is done. Stack also contains information about the callers environment, like some of the machine registers are also stored on stack. A function which is called allocates memory for its local variables and temporary variables on stack itself. In case of recursive function an independent stack for each function call exists.

Then there is data which is stored on heap. This memory for this data is allocated on runtime on heap segment. Heap segment is not local to a process but shared across processes. This is the reason why C programmers worry a lot about memory leaks which are caused on heap segment and may affect other processes on the system.

Command line arguments and environment variables

A process also contains room for storing environment variables and the command line arguments that we pass to the program. Usually the vector containing the command line information is stored here and then the address of this vector of information and number of elements in vector is copied to ‘argv’ and ‘argc’ (the two arguments to ‘main()’ function).

Besides the above information, a process also contains information like

  • State of its I/O
  • Its priority and other control information

One of the most important control information for a process is the privileges. A process directly inherits all the privileges of the user who has triggered this process. For example a process triggered by user who does not have superuser privileges cannot do stuff that require root privileges while a process triggered by root can do any thing that it is programmed to do. An exception to the above rule is where a process can acquire greater privileges than the user who triggered it if the setuid or setgid bit is set for that particular process. But we will not go into much detail about it here(refer to the man pages of setuid and setgid for more information on this).

2. Background and foreground processes

As we already discussed that we can start a process by its name in Unix. Like some standard programs ‘ls’, ‘ps’ etc can be started by just typing their name on the shell prompt. There are two ways in which we can start a process

  • Starting in foreground
  • Starting in background

Suppose there is a utility that consumes some time and does a count. Lets say the the name of the utility is ‘count’ Now to trigger and run the program in foreground, I run the following command (where ‘count’ is the name of the binary from the code above) :

$ ./count
Counting done

So we see that, after running the binary ‘./count’, it took almost 10 seconds before the output was displayed on stdout and until then the shell was occupied by this process only. ie You could not perform any other operation on the same shell. Now, to trigger a process in background, add ‘&’ at the end of the command:

$ ./count &
[1] 4120

$ # Do some work on shell while the above program is working in the background

$ Counting done

The ampersand ‘&’ sign indicates that this process needs to be run as a background process. By running a background process, we can have access to the shell for doing any further operations. Like, in the output above, after running the binary ‘count’ in background, I used a couple of more commands on the same shell and when the binary ‘count’ was done with its processing, the output was thrown back on the same shell(the last line). So we can conclude that by default every process runs in foreground, receives input(if any) from keyboard and returns output to the user. While a background process is one which gets disconnected from the keyboard and user can use the same shell to do more operations.

For more information on foreground and background processes refer to: How to Manage UNIX Background Jobs

3. Types of process

So we see that process is a concept that is fundamental to an operating system. Almost every activity on an OS takes form of a process to do some stuff. There are different types of processes running on a system, some of them are :

Child processes

A process that is created by some other process during run-time. Usually child processes are created to execute some binary from within an existing process. Child processes are created using fork() system call. Normally process are made to run through shell/terminal. In that case the shell becomes the parent and the executed process becomes the child process. On Unix/Linux each process has a parent except the init process(we will learn about this later).

Daemon Processes

These are special processes that run in background. They are system related process that have no associated terminal. These processes run will root permissions and usually provide services to processes. As we already know that a daemon process does not have an attached terminal, well to achieve this the process has to be detached from the terminal. The ideal way on Linux/Unix to do this is to run a process through terminal and from within this process create another process and then terminate the parent process. Since the parent is terminated so now the child will become independent of the terminal and would be taken over by init process and hence would become a daemon process. A typical example would be a mail daemon that waits for the arrival of e-mails and notify when a mail is received.

Orphan processes

Usually a process creates a child process (as described above) and when the child process terminates, a signal is issued to the parent so that parent can do all the stuff that it is required to do when one of the child gets terminated. But there are situations when parent gets killed. In that case the child processes become orphan and then taken under by the init process. Though the init process takes the ownership of the orphan process but still these process are called as orphan as their original parents no longer exists.

Zombie process

When a child process gets terminated or completes its execution, then its entry in the process table remains until the parent process fetches the status information of the terminated child. So, until then the terminated process enters zombie state and is known as zombie process.  When a process is terminated then all the memory and resources associated with the process are released but the entry of the process in process table exists. A signal SIGCHILD is send to the parent of the process (that just terminated). Typically, the handler of this signal in the parent executes a ‘wait’ call that fetches the exit status of the terminated process and then the entry of this zombie process from the process table is also removed.

4. The init process

As we discussed earlier, init process is the 5th stage in the 6 Stage of Linux Boot Process.

You would be cognizant of the famous ‘chicken and egg’ theory regarding who came first. In terms of processes, as each process has a parent process, the same question can be asked about parent or child process. Well, fortunately there is an answer here. The answer is the init process that is started as a first process during boot sequence. That means there is no parent of init process. Lets verify it, since PID of init is ’1′, we use the ps command :

So we see from the output that PPID is 0, which means that there is no parent for this process.

$ ps -l 1
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY        TIME CMD
4 S     0     1     0  0  80   0 -  5952 poll_s ?          0:00 /sbin/init

Shell Script To Add User, Password And Add User To Sudo

Here’s the Shell Script which required 2 parameters 1) UserName 2) Password…..

After setting up user name and password, script will ask you if you want to add user to Super User / Sudo or not….

#!/bin/bash

UCOM=”/usr/sbin/useradd”

PCOM=”/usr/bin/passwd”

DCOM=”/usr/sbin/userdel”

GCOM=”/bin/grep”

if [ “$#” != “2” ]

then

echo -e “33[33m Required 2 Parameters : User Name and Password…”

exit;

else

$UCOM $1

( echo $2; echo $2 ) | $PCOM $1

if [ “$?” != “0” ]

then

$DCOM -r $1

else

echo -e “33[35m User $1 Successfully Added To System”

echo -e “33[0m”

fi

fi

echo -e “33[33m Do You Want To Add User to Sudoers/Super User List (y/n)”

read choice

echo -e “33[0m”

if [ “$choice” == “y” -o “$choice” == “Y” ]

then

$GCOM $1 /etc/sudoers

if [ “$?” == “0” ]

then

echo -e “33[31m User $1 Already Added To Sudoers File”

echo -e “33[0m”

else

echo “$1   ALL=(ALL)       ALL” | cat >> /etc/sudoers

echo -e “33[35m User $1 Successfully Added To Sudoers!!!”

echo -e “33[0m”

fi

elif [ “$choice” == “n” -o “$choice” == “N” ]

then

echo -e “33[35m $1 User Not Added To Sudoers!!!”

echo -e “33[0m”

else

echo -e “33[37m Invalid Choice….User Not Added To Sudoers :-(”

echo -e “33[0m”

fi

Linux recover boot loader or filesystem corruption using Rescue Mode

Here are the steps to recover corrupted linux filesystem (with or without LVM) or boot loader:

1) Boot system using Linux OS (should be the same version which is installed or needs to recover) CD/USB

2) When prompted, type ”linux rescue”

3) This will ask You for some questions like need to enable network or not and mount system or not

In case of installation/repair or grub boot loader

4) Try to mount file system and use following command to install grub
grub-install /dev/sda (should be a first partition where MBR resides)
run exit to reboot into new installed and recovered grub boot loader

In case of filesystem repair (skip step 4)

5) Do not mount partition

6) run following command over shell
e2fsck -p /dev/sda{1,2,3….} Partition which required to recover
fsck -p /dev/sda{1,2,3} Partition which required to recover

If all goes well reboot your system 🙂

In case of LVM filesystem repair (skip step 4 & 6)

7) In case of rescue mode, LVMs are not in active state we require to activate them manually

8) To check and activate LVMs run following commands:

lvm pvscan (Scan for PVs available and show them)
lvm vgscan (Scan for VGs available and show them)
lvm vgchange VGName -a y (This will activate all VGs LVM volumes)
lvm lvscan (Scan LVMs available)

9) Now use Step 6 (change partition with LVMs partition number which is shown by ”lvm lvscan”)

Thats it!!! Plz correct if wrong somewhere 🙂

Difference between /bin vs /sbin vs /usr/bin vs /usr/sbin

/bin This directory contains executable programs which are needed in
single user mode and to bring the system up or repair it.

/sbin Like /bin, this directory holds commands needed to boot the sys-
tem, but which are usually not executed by normal users.

/usr/bin
This is the primary directory for executable programs. Most
programs executed by normal users which are not needed for boot-
ing or for repairing the system and which are not installed
locally should be placed in this directory.

/usr/sbin
This directory contains program binaries for system administra-
tion which are not essential for the boot process, for mounting
/usr, or for system repair.

Install D-Link DWA 525 N 150 Wireless Over Linux or Fedora 14

After a long time spending over google I find some useful NOTES over how to install D-Link DWA 525 N 150 Wireless Drivers, which are here:

Run command “lspci |grep -i network”
Output will be like :
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 03)
06:02.0 Network controller: RaLink Device 3060

Go to http://www.ralinktech.com/support.php?s=2 and download RT3062PCI/mPCI/CB/PCIe(RT3060/RT3062/RT3562/RT3592)

This will ask for your Name and Mail ID, enter and when you click on Accept this will ask you for save or open. Save file to anywhere on your machine, lets say in /opt/

Go to /opt/ and run following command:
cd /opt
tar zxvf DPO_RT3562_3592_3062_LinuxSTA_V2.4.1.1_20101217.tgz
cd DPO_RT3562_3592_3062_LinuxSTA_V2.4.1.1_20101217

Change following in os/linux/config.mk file
vim os/linux/config.mk
HAS_WPA_SUPPLICANT = n -> HAS_WPA_SUPPLICANT = y
HAS_NATIVE_WPA_SUPPLICANT_SUPPORT = n -> HAS_NATIVE_WPA_SUPPLICANT_SUPPORT = y

After making above changes run following:
make
make install

After successfully completion of above command, run following:
insmod os/linux/rt3562sta.ko

Thats it!!! Setup a wireless connection through Network Connection and Enjoy your wi-fi network 🙂

Implement System protection against DOS/DDOS

bash# vi /etc/sysctl.conf

add the below code:

# Enable IP spoofing protection, turn on Source Address Verification

net.ipv4.conf.all.rp_filter = 1

# Enable TCP SYN Cookie Protection

net.ipv4.tcp_syncookies = 1

Add the below code in /etc/rc.local and restart network
for f in /proc/sys/net/ipv4/conf/*/rp_filter;

do echo 1 > done

echo 1 > /proc/sys/net/ipv4/tcp_syncookies

Clean reboot of hung Linux server : Quick HOWTO

In day to day system administration job, you may come across the situation that your Linux server is hung or freeze and your system is not responding even  for Ctrl+Alt+Del in console itself and you must need to do a hard reboot by pressing reset button. As everyone know, the hard reboots is not good and can crash the File systems. so what to do now?

There is a way in Linux,
Hold down the Right Alt and SysRq keys and press this sequence:

  R E I S U B

This will cleanly unmount the drives, terminate the processes and nicely reboot your machine.

of course, To get this worked, you need to “enable” this feature on the running kernel first !
On 2.6 kernel

echo 1 > /proc/sys/kernel/sysrq

This will do the trick.
In Some distributions, you may have a way to enable this feature at boot time.

On Fedora and RHEL, edit the file /etc/sysctl.conf, and change the line kernel.sysrq = 0 to kernel.sysrq = 1

Automatic reboot after Kernel Panic in Linux

In Linux, By default after kernel panic, Linux waits for a system admin to restart or power cycle server.. We can change this behavior and set to reboot automatically when a kernel panic occurs.. For that, we have to change the value set on “kernel.panic” kernel parameter.

Now we have to check the current value on this kernel parameter in Linux server:

[root@myserver ~]# cat /proc/sys/kernel/panic
0
[root@myserver ~]# sysctl -a | grep kernel.panic
kernel.panic = 0

To make the Linux server automatically reboot after a kernel panic, we have to set a value greater than 0. The value should be the number of seconds to wait before automatic reboot of the server.

For example , if you set value 60 , then the server will wait for 60 seconds before automatic reboot after the kernel panic. To make this change permanent, edit /etc/sysctl.conf and set it there.

[root@myserver ~]# echo “10” > /proc/sys/kernel/panic
[root@myserver ~]# cat /etc/sysctl.conf |  grep kernel.panic 

kernel.panic = 10

Solution for UNIX Error: Terminal too wide

When you are working in an UNIX shell using Putty tool, you may get this error.

Problem:

When you are trying to open vi editor, you may get error message “Terminal too wide

How to Fix this??

Enter the below command in the shell and try to open vi editor again. It will work.

stty columns 120
Hope this will help on someone.

Solution: Error – “passwd: Sorry: less than 7 days since the last change.”

Problem:

When you trying to change password in solaris, you may get the below error:

ORACLE user1$ passwd oracle
Enter existing login password:
passwd: Sorry: less than 7 days since the last change.
Permission denied
Solution:

As root do the following:

# passwd -n 0 oracle
Now, Ask the oracle user to try again.

ORACLE user1$  passwd oracle
Now the Oracle user able to change their password.

Permenant fix:

Take a look at /etc/default/passwd file and check the MINWEEKS Parameter.

You can change it to NULL if you don’t want a minimum time between password changes.

Unmount filesystem when device is busy

When you unmount a filesystem, you may get “device is busy error” sometimes.  Using the following steps, you can unmount safely.

# umount  /testsrv1/rman
umount: /testsrv1/rman: device is busy
umount: /testsrv1/rman: device is busy

# fuser -m /testsrv1/rman
/testsrv1/rman:         31477c

# ps -eaf | grep 31477
oracle  31477 31448  0 09:52 pts/0    00:00:00 /bin/ksh

# df -h /testsrv1/rman
Filesystem            Size  Used Avail Use% Mounted on
testsrv1:/miszpool/mis
2.5T  1.9T  560G  78% /testsrv1/rman

# ps -eaf | grep 31477
oracle  31477 31448  0 09:52 pts/0    00:00:00 /bin/ksh

# ps -eaf | grep 31448
dbauser1 31448 31447  0 09:51 pts/0    00:00:00 -ksh
oracle  31477 31448  0 09:52 pts/0    00:00:00 /bin/ksh

# kill -9 31477
# ps -eaf | grep 31448
dbauser1 31448 31447  0 09:51 pts/0    00:00:00 -ksh

# umount -f /testsrv1/rman

# mount /testsrv1/rman

# df -h /testsrv1/rman
Filesystem            Size  Used Avail Use% Mounted on
testsrv1:/miszpool/mis
2.5T  1.9T  560G  78% /testsrv1/rman

Recover Bad Superblock in Linux Filesystem

If  you get a ¨Damaged Superblock¨ error message at filesystem (fsck) check in Linux Server, Usually fsck will not be able to repair the file system due to bad super block. In these situations, we can recover the damaged super block from the backup.

Solution:

There are backups of the Superblock located on several positions and we can restore them with a simple command in a Linux server

By default in Linux, the file system creates the backup of  super block in the following locations:

8193, 32768, 98304, 163840, 229376 and 294912.

Note: 8193 is only on older systems  in many cases. 32768 is the most current position for the first backup

When you get this “damaged superblock or bad superblock error” and if  you get a root-prompt in a recovery console, then issue the following command:

# e2fsck -b 32768 /dev/hda5

Now the System will check the filesystem with the information stored in that backup superblock and if the check was successful it will restore the backup to position 0.

If this is not successful, then try using the other copy of Superblock backup (Refer the backup location of superblock above)

Solution : Permission denied error while changing password in NIS

If you are getting a Error “Permission Denied” While changing the Passwords in NIS even if you are doing as root. the following steps solves this issue.

1. check whether the yppasswdd daemon is running. Type ps -ef|grep yp  to check this

2. if it is not running start the yppasswdd daemon with NIS Maps directory as parameter..

#  /usr/lib/netsvc/yp/rpc.yppasswdd -D /var/yp/src/

/var/yp/src/ directory contains the NIS Maps in Solaris

3. This will fix the  issue. Also check the permission and ownership of the passwd file on the NIS
Maps directory. it should be owned by root. This has been tested in Solaris and might work in
Linux as well

EXT2 to EXT3 and EXT3 to EXT4 Converting without data erase

Ext2 to ext3 file conversation

[root@server1 ~]# tune2fs -j /dev/sda5

Ext3 to ext4 file system conversation

[root@server1 ~]# tune2fs -O dir_index,uninit_bg,extents /dev/sda5

Ext2 to ext4 file system conversation

[root@server1 ~]# tune2fs -O dir_index,uninit_bg,has_journal /dev/sda5

Ext3 to ext2 file system back conversation

 # tune2fs -O ^has_journal /dev/sda5

Solving the “Control D” error…Linux:

Q:- What is the Meaning of Control D error?

A:- When the root user try to make any Permanent entry in fstab file & by mistake changes the path location of mounted file systems, it gives error while rebooting the system.

Control D Error:-

Steps to Rectify it:-….

1) Enter the bootable Cd/DvD of Rhel.
(The version you are using)

2) Read the control D error carefully.

3) Give the root password.

4) You will go to single usermod.

5) Try to access /etc/fstab file.

6) Will not allow you as will be in read only mode.

7) Enter this command:-
mount -o remount,rw /
(Will give read/write permission to /)

8) Will give u read/write permission to all
the files in /

9)Then again enter into /etc/fstab & rectify ur error.(vim /etc/fstab)

10)Give command reboot or init 5(As per ur wish)

Rectify it & Enjoy the Control D Error…..

Bash Shell Script Examples

For loop bash shell scripting examples

Method 1: bash “for” loop using “in” and list of values

Syntax:

for varname in list

do

command1

command2

…..

done

In the above examples

  • for, in, do and done are keywords
  • “list” contains list of values. The list can be a variable that contains several words separated by spaces. If list is missing in the for statement, then it takes the positional parameter that were passed into the shell.
  • Varname is any bash variable name.

Method2: bash “for” loop using C like syntax

The second form of the for loop is similar to the loop in “C” programming language, which has three expressions (initialization, condition and updation)

Syntax:

for (( expr1; expr2; expr3 ))

do

command1

command2

….

Done

In the above examples

  • Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop.
  • All the statement between do and done are executed repeatedly until the value of expr2 is TRUE.
  • After each iteration of the loop, expt3 is evaluated. This usually used to increment a loop counter.

Example 1

Static values for the list after “in” keyword

[root@server1 Desktop]# vim useradd-for1.sh

#!/bin/bash

i=1

for user in ayyappan arun ravi alex aswin

do

useradd $user

echo password | passwd –stdin $user

done

Output

[root@server1 Desktop]# ./useradd-for1.sh

Changing password for user ayyappan.

passwd: all authentication tokens updated successfully.

Changing password for user arun.

passwd: all authentication tokens updated successfully.

Changing password for user ravi.

passwd: all authentication tokens updated successfully.

Changing password for user alex.

passwd: all authentication tokens updated successfully.

Changing password for user aswin.

passwd: all authentication tokens updated successfully.

Example 2

Variable for the list after “in” keyword

[root@server1 Desktop]# vim useradd-for2.sh

#!/bin/bash

i=1

names=”ayyappan arun ravi alex aswin”

for userlist in $names

do

useradd $userlist

echo password | passwd –stdin $userlist

done

Example 3

Don’t specify the list; get it from the positional parameters

[root@server1 Desktop]# vim useradd-for3.sh

#!/bin/bash

i=1

for userlist

do

useradd $userlist

echo “password” | passwd –stdin $userlist

done

Output

[root@server1 Desktop]# ./useradd-for3.sh ayyappan arun ravi alex

Changing password for user ayyappan.

passwd: all authentication tokens updated successfully.

Changing password for user arun.

passwd: all authentication tokens updated successfully.

Changing password for user ravi.

passwd: all authentication tokens updated successfully.

Changing password for user alex.

passwd: all authentication tokens updated successfully.

Example 4

Command output as list values after “in” keyword

[root@server1 Desktop]# vim userlist

ayyappan

arun

alex

ravi

ragu

:wq!

[root@server1 Desktop]# vim user.sh

#!/bin/bash

i=1

for username in `awk -F: ‘{print $1}’ /root/Desktop/userlist`

do

useradd $username

echo “password” | passwd –stdin $username

done

Example 5

Loop through /home directory user name remove in a for loop

[root@server1 Desktop]# cat user-remove.sh

#!/bin/bash

i=1

cd /home

for remove in *

do

userdel -rf $remove

echo “sucessfully removed user $remove “

done

OUTPUT

[root@server1 Desktop]# vim user-remove.sh

[root@server1 Desktop]# ./user-remove.sh

sucessfully removed user arun

sucessfully removed user ravi

sucessfully removed user ayyappan

Example 6

Printer numbers

[root@server1 Desktop]# cat random.sh

#!/bin/bash

echo “Enter the number : “

read num

for (( i=1; i <= $num; i++ ))

do

echo “$i”

done

OUTPUT

[root@server1 Desktop]# ./random.sh

Enter the number :

4

1

2

3

4

[root@server1 Desktop]# vim random.sh

#!/bin/bash

for num in {1..10}

do

echo “$num”

done

[root@server1 Desktop]# ./random.sh

0

2

4

6

8

10

Print ODD number only

[root@server1 Desktop]# cat odd.sh

#!/bin/bash

echo “Enter the ODD number range : ”

read num

for ((i=1; i<=$num; i=i+2 ))

do

echo “$i”

done

Print Even number only

[root@server1 Desktop]# cat even.sh

#!/bin/bash

echo “Enter the EVEN number range : ”

read num

for ((i=0; i<=$num; i=i+2))

do

echo “$i”

done

Print ODD and EVEN number only

[root@server1 Desktop]# cat ./odd-even.sh

#!/bin/bash

echo “Enter number range : ”

read num

for ((e=0, o=1; e<=$num, o<=$num; e=e+2, o=o+2))

do

echo “ODD Number: $o  EVEN Number: $e”

done

OUTPUT

[root@server1 Desktop]# ./odd-even.sh

Enter number range :

5

ODD Number: 1  EVEN Number: 0

ODD Number: 3  EVEN Number: 2

ODD Number: 5  EVEN Number: 4

Print number

[root@server1 Desktop]# cat after-in.sh

#!/bin/bash

for num in {1..10}

do

echo “$num”

done

Print Even number

[root@server1 Desktop]# cat after-in.sh

#!/bin/bash

for num in {0..10..2}

do

echo “$num”

done

Print ODD number

[root@server1 Desktop]# cat after-in.sh

#!/bin/bash

for num in {1..10..2}

do

echo “$num”

done

Example 7

Print Infinitely number

[root@server1 Desktop]# cat sleep.sh

#!/bin/bash

i=1

for (( ; ; ))

do

sleep $i

echo “Number: $((i++))”

done

Note

“sleep” used for infinite number generate speed decreased.

“if” statement examples

1.      if – then – fi

2.      if – then – else – fi

3.      if – then – elif – else – fi

4.      if – then –else – if – then – fi – fi  (nested if)

1.      Bash if .. then .. fi statement

if [ conditional expression ]

then

            statement1

            statement2

fi

2.      if [ conditional expression ]

then

            statement1

            statement2

else

            statement3

            statement4

fi

3.      if [ conditional expression ]

then

            statement1

            statement2

elif [ conditional expression ]

then

            statement1

            statement2

else

            statement1

            statement2

fi

4.      if [ conditional expression ]

then

            statement1

            statement2

else

            if [ conditional expression ]

            then

                        statement1

                        statement2

            fi

fi

There are many different ways that an conditional statement can be used. These are summarized here:

String Comparison

Description

Str1 = Str2 Returns true if the strings are equal
Str1 != Str2 Returns true if the strings are not equal
-n Str1 Returns true if the string is not null
-z Str1 Returns true if the string is null

Numeric Comparison

Description

expr1 -eq expr2 Returns true if the expressions are equal
expr1 -ne expr2 Returns true if the expressions are not equal
expr1 -gt expr2 Returns true if expr1 is greater than expr2
expr1 -ge expr2 Returns true if expr1 is greater than or equal to expr2
expr1 -lt expr2 Returns true if expr1 is less than expr2
expr1 -le expr2 Returns true if expr1 is less than or equal to expr2
! expr1 Negates the result of the expression

File Conditionals

Description

-d file True if the file is a directory
-e file True if the file exists (note that this is not particularly portable, thus -f is generally used)
-f file True if the provided string is a file
-g file True if the group id is set on a file
-r file True if the file is readable
-s file True if the file has a non-zero size
-u True if the user id is set on a file
-w True if the file is writable
-x True if the file is an executable

The test command’s logical operators.

Command Meaning
! expr Returns True if expr is not true.
expr1 -a expr2 Returns True if expr1 and expr2 are true.
expr1 -o expr2 Returns True if expr1 or expr2 is true.

While loop format

Here is the basic format:

while [ condition ]

do

command1

command2

command3

done