Archive by Author | ayyappan

Device eth0 does not seem to be present

After cloning a Centos machine from Oracle Virtualbox or from VMware template, I got following error message when networking service was restarted
device eth0 does not seem to be present
Initially, I thought the issue might be with the network adapter but was not sure exactly which network adapter settings should be kept..
On further investigation, I came with a solution with following solution.
Basically, the problem occurs due to old NIC record does not getting erased even though new NIC record is assigned.
1) Open following file which holds record of the NIC templates
vi /etc/udev/rules.d/70-persistent-net.rules
The above file should contain similar records as below:
# PCI device 0x15ad:0x07b0 (e1000)
SUBSYSTEM==”net”, ACTION==”add”, DRIVERS==”?*”,
ATTR{address}==”00:27:3e:ae:00:1a”,
ATTR{type}==”1″, KERNEL==”eth*”, NAME=”eth0″

# PCI device 0x15ad:0x07b0 (e1000)
SUBSYSTEM==”net”, ACTION==”add”, DRIVERS==”?*”,
ATTR{address}==”00:27:3e:ae:00:1b”,
ATTR{type}==”1″, KERNEL==”eth*”, NAME=”eth1″
2) Remove previous eth entries and change the last entry NAME to eth0
# PCI device 0x15ad:0x07b0 (e1000)
SUBSYSTEM==”net”, ACTION==”add”, DRIVERS==”?*”,
ATTR{address}==”00:27:3e:ae:00:1b”,
ATTR{type}==”1″, KERNEL==”eth*”, NAME=”eth0″
3) Save the file.
4) Open following file and modify the mac address

vi /etc/sysconfig/network-scripts/ifcfg-eth0
5) Save the file.
6) Reload udev configuration for the changes we made to reflect
start_udev
7) Restart network service
service network restart
or
/etc/init.d/network restart
8) Check the available ip using ifconfig command and update /etc/resolv.conf file with correct nameservers.

 

BASIC LINUX COMMANDS

alias    Create an alias
awk      Find and Replace text, database sort/validate/index
break    Exit from a loop
builtin  Run a shell builtin

cal      Display a calendar
case     Conditionally perform a command
cat      Display the contents of a file
cd       Change Directory
cfdisk   Partition table manipulator for Linux
chgrp    Change group ownership
chmod    Change access permissions
chown    Change file owner and group
chroot   Run a command with a different root directory
cksum    Print CRC checksum and byte counts
clear    Clear terminal screen
cmp      Compare two files
comm     Compare two sorted files line by line
command  Run a command - ignoring shell functions
continue Resume the next iteration of a loop
cp       Copy one or more files to another location
cron     Daemon to execute scheduled commands
crontab  Schedule a command to run at a later time
csplit   Split a file into context-determined pieces
cut      Divide a file into several parts

date     Display or change the date & time
dc       Desk Calculator
dd       Data Dump - Convert and copy a file
declare  Declare variables and give them attributes
df       Display free disk space
diff     Display the differences between two files
diff3    Show differences among three files
dir      Briefly list directory contents
dircolors Colour setup for `ls'
dirname  Convert a full pathname to just a path
dirs     Display list of remembered directories
du       Estimate file space usage

echo     Display message on screen
ed       A line-oriented text editor (edlin)
egrep    Search file(s) for lines that match an extended expression
eject    Eject CD-ROM
enable   Enable and disable builtin shell commands
env      Display, set, or remove environment variables
eval     Evaluate several commands/arguments
exec     Execute a command
exit     Exit the shell
expand   Convert tabs to spaces
export   Set an environment variable
expr     Evaluate expressions

factor   Print prime factors
false    Do nothing, unsuccessfully
fdformat Low-level format a floppy disk
fdisk    Partition table manipulator for Linux
fgrep    Search file(s) for lines that match a fixed string
find     Search for files that meet a desired criteria
fmt      Reformat paragraph text
fold     Wrap text to fit a specified width.
for      Expand words, and execute commands
format   Format disks or tapes
free     Display memory usage
fsck     Filesystem consistency check and repair.
function Define Function Macros

gawk     Find and Replace text within file(s)
getopts  Parse positional parameters
grep     Search file(s) for lines that match a given pattern
groups   Print group names a user is in
gzip     Compress or decompress named file(s)

hash     Remember the full pathname of a name argument
head     Output the first part of file(s)
history  Command History
hostname Print or set system name

id       Print user and group id's
if       Conditionally perform a command
import   Capture an X server screen and save the image to file
info     Help info
install  Copy files and set attributes

join     Join lines on a common field

kill     Stop a process from running

less     Display output one screen at a time
let      Perform arithmetic on shell variables
ln       Make links between files
local    Create variables
locate   Find files
logname  Print current login name
logout   Exit a login shell
lpc      Line printer control program
lpr      Off line print
lprint   Print a file
lprintd  Abort a print job
lprintq  List the print queue
lprm     Remove jobs from the print queue
ls       List information about file(s)

m4       Macro processor
man      Help manual
mkdir    Create new folder(s)
mkfifo   Make FIFOs (named pipes)
mknod    Make block or character special files
more     Display output one screen at a time
mount    Mount a file system
mtools   Manipulate MS-DOS files
mv       Move or rename files or directories

nice     Set the priority of a command or job
nl       Number lines and write files
nohup    Run a command immune to hangups

passwd   Modify a user password
paste    Merge lines of files
pathchk  Check file name portability
popd     Restore the previous value of the current directory
pr       Convert text files for printing
printcap Printer capability database
printenv Print environment variables
printf   Format and print data
ps       Process status
pushd    Save and then change the current directory
pwd      Print Working Directory

quota    Display disk usage and limits
quotacheck Scan a file system for disk usage
quotactl Set disk quotas

ram      ram disk device
rcp      Copy files between two machines.
read     read a line from standard input
readonly Mark variables/functions as readonly
remsync  Synchronize remote files via email
return   Exit a shell function
rm       Remove files
rmdir    Remove folder(s)
rpm      Remote Package Manager
rsync    Remote file copy (Synchronize file trees)

screen   Terminal window manager
sdiff    Merge two files interactively
sed      Stream Editor
select   Accept keyboard input
seq      Print numeric sequences
set      Manipulate shell variables and functions
shift    Shift positional parameters
shopt    Shell Options
shutdown Shutdown or restart linux
sleep    Delay for a specified time
sort     Sort text files
source   Run commands from a file `.'
split    Split a file into fixed-size pieces
su       Substitute user identity
sum      Print a checksum for a file
symlink  Make a new name for a file
sync     Synchronize data on disk with memory

tac      Concatenate and write files in reverse
tail     Output the last part of files
tar      Tape ARchiver
tee      Redirect output to multiple files
test     Evaluate a conditional expression
time     Measure Program Resource Use
times    User and system times
touch    Change file timestamps
top      List processes running on the system
traceroute Trace Route to Host
trap     Run a command when a signal is set(bourne)
tr       Translate, squeeze, and/or delete characters
true     Do nothing, successfully
tsort    Topological sort
tty      Print filename of terminal on stdin
type     Describe a command

ulimit   Limit user resources
umask    Users file creation mask
umount   Unmount a device
unalias  Remove an alias
uname    Print system information
unexpand Convert spaces to tabs
uniq     Uniquify files
units    Convert units from one scale to another
unset    Remove variable or function names
unshar   Unpack shell archive scripts
until    Execute commands (until error)
useradd  Create new user account
usermod  Modify user account
users    List users currently logged in
uuencode Encode a binary file
uudecode Decode a file created by uuencode

v        Verbosely list directory contents (`ls -l -b')
vdir     Verbosely list directory contents (`ls -l -b')

watch    Execute/display a program periodically
wc       Print byte, word, and line counts
whereis  Report all known instances of a command   
which    Locate a program file in the user's path.
while    Execute commands
who      Print all usernames currently logged in
whoami   Print the current user id and name (`id -un')

xargs    Execute utility, passing constructed argument list(s)
yes      Print a string until interrupted

File Transfer Protocol(FTP)

Introduction

 

The File Transfer Protocol (FTP) is used as one of the most common means of copying files between servers over the Internet. Most web based download sites use the built in FTP capabilities of web browsers and therefore most server oriented operating systems usually include an FTP server application as part of the software suite. Linux is no exception.

This chapter will show you how to convert your Linux box into an FTP server using the default Very Secure FTP Daemon (VSFTPD) package included in RHEL 6.

FTP Overview

FTP relies on a pair of TCP ports to get the job done. It operates in two connection channels as I’ll explain:

FTP Control Channel, TCP Port 21: All commands you send and the ftp server’s responses to those commands will go over the control connection, but any data sent back (such as “ls” directory lists or actual file data in either direction) will go over the data connection.

FTP Data Channel, TCP Port 20: This port is used for all subsequent data transfers between the client and server.

In addition to these channels, there are several varieties of FTP.

Types of FTP

From a networking perspective, the two main types of FTP are active and passive. In active FTP, the FTP server initiates a data transfer connection back to the client. For passive FTP, the connection is initiated from the FTP client. These are illustrated in Figure

Active And Passive FTP Illustrated

From a user management perspective there are also two types of FTP: regular FTP in which files are transferred using the username and password of a regular user FTP server, and anonymous FTP in which general access is provided to the FTP server using a well known universal login method.

Active FTP

The sequence of events for active FTP is:

  1. Your client connects to the FTP server by establishing an FTP control connection to port 21 of the server. Your commands such as ‘ls’ and ‘get’ are sent over this connection.
  2. Whenever the client requests data over the control connection, the server initiates data transfer connections back to the client. The source port of these data transfer connections is always port 20 on the server, and the destination port is a high port (greater than 1024) on the client.
  3. Thus the ls listing that you asked for comes back over the port 20 to high port connection, not the port 21 control connection.

FTP active mode therefore transfers data in a counter intuitive way to the TCP standard, as it selects port 20 as it’s source port (not a random high port that’s greater than 1024) and connects back to the client on a random high port that has been pre-negotiated on the port 21 control connection.

Active FTP may fail in cases where the client is protected from the Internet via many to one NAT (masquerading). This is because the firewall will not know which of the many servers behind it should receive the return connection.

Passive FTP

Passive FTP works differently:

  1. Your client connects to the FTP server by establishing an FTP control connection to port 21 of the server. Your commands such as ls and get are sent over that connection.
  2. Whenever the client requests data over the control connection, the client initiates the data transfer connections to the server. The source port of these data transfer connections is always a high port on the client with a destination port of a high port on the server.

Passive FTP should be viewed as the server never making an active attempt to connect to the client for FTP data transfers. Because client always initiates the required connections, passive FTP works better for clients protected by a firewall.

Note:

 

Windows defaults to   –           Active FTP

Linux defaults to         –           Passive FTP

 

How This Affects Load Balancer Add-On Routing

 

IPVS packet forwarding only allows connections in and out of the cluster based on it recognizing its port number or its firewall mark. If a client from outside the cluster attempts to open a port IPVS is not configured to handle, it drops the connection. Similarly, if the real server attempts to open a connection back out to the Internet on a port IPVS does not know about, it drops the connection. This means all connections from FTP clients on the Internet must have the same firewall mark assigned to them and all connections from the FTP server must be properly forwarded to the Internet using network packet filtering rules.

Note

In order to enable passive FTP connections, ensure that you have the ip_vs_ftp kernel module loaded, which you can do by running the command modprobe ip_vs_ftp as an administrative user at a shell prompt.

Server side required package

[root@server1 Desktop]# rpm -qa vsftpd

vsftpd-2.2.2-6.el6_0.1.x86_64

 

Version check

[root@server1 Desktop]# vsftpd -v

vsftpd: version 2.2.2

 

Configuration file

[root@server1 Desktop]# rpm -ql vsftpd

/etc/logrotate.d/vsftpd                                                –              logrotate

/etc/pam.d/vsftpd

/etc/rc.d/init.d/vsftpd                                   –              service start | stop |restart | reload

/etc/vsftpd

/etc/vsftpd/ftpusers                                      –              ftp users deny

/etc/vsftpd/user_list                                     –              ftp users list deny or allow

/etc/vsftpd/vsftpd.conf                                               –              ftp configuration file

/etc/vsftpd/vsftpd_conf_migrate.sh      –              ftp migration

/usr/sbin/vsftpd                                              –             

/usr/share/doc/                                                               –              vsftpd documents

/usr/share/man/man5/vsftpd.conf.5.gz               –              man vsftpd.conf

/usr/share/man/man8/vsftpd.8.gz          –              man vsftpd

/var/ftp                                                                                –              ftp primary share directory

/var/ftp/pub                                                      –              ftp secondary share directory

 

Server side required services

service vsftpd {start|stop|restart|try-restart|force-reload|status}

 

chkconfig vsftpd –list | on | off

 

Client side required package

[root@client1 Desktop]# rpm -qa ftp

ftp-0.17-51.1.el6.x86_64

 

[root@server1 Desktop]# rpm -ql ftp

/usr/bin/ftp

/usr/bin/pftp

/usr/share/man/man1/ftp.1.gz

/usr/share/man/man1/pftp.1.gz

/usr/share/man/man5/netrc.5.gz

 

Help Documentation

man vsftpd         or            man vsftpd.conf

 

 

VSFTPD default configuration

Syntax

=

 

[root@server1 Desktop]# cat -n /etc/vsftpd/vsftpd.conf

     1   # Example config file /etc/vsftpd/vsftpd.conf

     2   #

     3   # The default compiled in settings are fairly paranoid. This sample file

     4   # loosens things up a bit, to make the ftp daemon more usable.

     5   # Please see vsftpd.conf.5 for all compiled in defaults.

     6   #

     7   # READ THIS: This example file is NOT an exhaustive list of vsftpd options.

     8   # Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd’s

     9   # capabilities.

    10   #

    11   # Allow anonymous FTP? (Beware – allowed by default if you comment this out).

    12   anonymous_enable=YES

    13   #

    14   # Uncomment this to allow local users to log in.

    15   local_enable=YES

    16   #

    17   # Uncomment this to enable any form of FTP write command.

    18   write_enable=YES

    19   #

    20   # Default umask for local users is 077. You may wish to change this to 022,

    21   # if your users expect that (022 is used by most other ftpd’s)

    22   local_umask=022

    23   #

    24   # Uncomment this to allow the anonymous FTP user to upload files. This only

    25   # has an effect if the above global write enable is activated. Also, you will

    26   # obviously need to create a directory writable by the FTP user.

    27   #anon_upload_enable=YES

    28   #

    29   # Uncomment this if you want the anonymous FTP user to be able to create

    30   # new directories.

    31   #anon_mkdir_write_enable=YES

    32   #

    33   # Activate directory messages – messages given to remote users when they

    34   # go into a certain directory.

    35   dirmessage_enable=YES

    36   #

    37   # Activate logging of uploads/downloads.

    38   xferlog_enable=YES

    39   #

    40   # Make sure PORT transfer connections originate from port 20 (ftp-data).

    41   connect_from_port_20=YES

    42   #

    43   # If you want, you can arrange for uploaded anonymous files to be owned by

    44   # a different user. Note! Using “root” for uploaded files is not

    45   # recommended!

    46   #chown_uploads=YES

    47   #chown_username=whoever

    48   #

    49   # You may override where the log file goes if you like. The default is shown

    50   # below.

    51   #xferlog_file=/var/log/vsftpd.log

    52   #

    53   # If you want, you can have your log file in standard ftpd xferlog format.

    54   # Note that the default log file location is /var/log/xferlog in this case.

    55   xferlog_std_format=YES

    56   #

    57   # You may change the default value for timing out an idle session.

    58   #idle_session_timeout=600

    59   #

    60   # You may change the default value for timing out a data connection.

    61   #data_connection_timeout=120

    62   #

    63   # It is recommended that you define on your system a unique user which the

    64   # ftp server can use as a totally isolated and unprivileged user.

    65   #nopriv_user=ftpsecure

    66   #

    67   # Enable this and the server will recognise asynchronous ABOR requests. Not

    68   # recommended for security (the code is non-trivial). Not enabling it,

    69   # however, may confuse older FTP clients.

    70   #async_abor_enable=YES

    71   #

    72   # By default the server will pretend to allow ASCII mode but in fact ignore

    73   # the request. Turn on the below options to have the server actually do ASCII

    74   # mangling on files when in ASCII mode.

    75   # Beware that on some FTP servers, ASCII support allows a denial of service

    76   # attack (DoS) via the command “SIZE /big/file” in ASCII mode. vsftpd

    77   # predicted this attack and has always been safe, reporting the size of the

    78   # raw file.

    79   # ASCII mangling is a horrible feature of the protocol.

    80   #ascii_upload_enable=YES

    81   #ascii_download_enable=YES

    82   #

    83   # You may fully customise the login banner string:

    84   #ftpd_banner=Welcome to blah FTP service.

    85   #

    86   # You may specify a file of disallowed anonymous e-mail addresses. Apparently

    87   # useful for combatting certain DoS attacks.

    88   #deny_email_enable=YES

    89   # (default follows)

    90   #banned_email_file=/etc/vsftpd/banned_emails

    91   #

    92   # You may specify an explicit list of local users to chroot() to their home

    93   # directory. If chroot_local_user is YES, then this list becomes a list of

    94   # users to NOT chroot().

    95   #chroot_local_user=YES

    96   #chroot_list_enable=YES

    97   # (default follows)

    98   #chroot_list_file=/etc/vsftpd/chroot_list

    99   #

   100   # You may activate the “-R” option to the builtin ls. This is disabled by

   101   # default to avoid remote users being able to cause excessive I/O on large

   102   # sites. However, some broken FTP clients such as “ncftp” and “mirror” assume

   103   # the presence of the “-R” option, so there is a strong case for enabling it.

   104   #ls_recurse_enable=YES

   105   #

   106   # When “listen” directive is enabled, vsftpd runs in standalone mode and

   107   # listens on IPv4 sockets. This directive cannot be used in conjunction

   108   # with the listen_ipv6 directive.

   109   listen=YES

   110   #

   111   # This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6

   112   # sockets, you must run two copies of vsftpd with two configuration files.

   113   # Make sure, that one of the listen options is commented !!

   114   #listen_ipv6=YES

   115  

   116   pam_service_name=vsftpd

   117   userlist_enable=YES

   118   tcp_wrappers=YES

[root@server1 Desktop]#

 

Default vsftpd.conf file configuration

[root@server1 Desktop]# grep -v ‘#’ /etc/vsftpd/vsftpd.conf

anonymous_enable=YES

local_enable=YES

write_enable=YES

local_umask=022

dirmessage_enable=YES

xferlog_enable=YES

connect_from_port_20=YES

xferlog_std_format=YES

listen=YES

 

pam_service_name=vsftpd

userlist_enable=YES

tcp_wrappers=YES

 

 

 

 

 

 

 

 

Types of Vsftpd.conf configuration options

1.  Daemon options

2.  Login options and access controls

3.  Anonymous user options

4.  Local user options

5.  Directory options

6.  File transfer options

7.  Logging options

8.  Network options

 

1.  Daemon options

 

listen

When enabled, vsftpd runs in stand-alone mode. Red Hat Enterprise Linux sets this value to YES. This directive cannot be used in conjunction with the listen_ipv6 directive.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

listen_ipv6

When enabled, vsftpd runs in stand-alone mode, but listens only to IPv6 sockets. This directive cannot be used in conjunction with the listen directive.

The default value is NO.

 

session_support

When enabled, vsftpd attempts to maintain login sessions for each user through Pluggable Authentication Modules (PAM). For more information, refer to the Using Pluggable Authentication Modules (PAM) chapter of the Red Hat Enterprise Linux 6 Managing Single Sign-On and Smart Cards and the PAM man pages. If session logging is not necessary, disabling this option allows vsftpd to run with less processes and lower privileges.

The default value is YES.

 

2.      Login options and access controls

 

anonymous_enable

When enabled, anonymous users are allowed to log in. The usernames anonymous and ftp are accepted.

The default value is YES.

Refer to “Anonymous User Options” for a list of directives affecting anonymous users.

 

banned_email_file

If the deny_email_enable directive is set to YES, this directive specifies the file containing a list of anonymous email passwords which are not permitted access to the server.

The default value is /etc/vsftpd/banned_emails.

 

banner_file

Specifies the file containing text displayed when a connection is established to the server. This option overrides any text specified in the ftpd_banner directive.

There is no default value for this directive.

 

cmds_allowed

Specifies a comma-delimited list of FTP commands allowed by the server. All other commands are rejected.

There is no default value for this directive.

 

deny_email_enable

When enabled, any anonymous user utilizing email passwords specified in the /etc/vsftpd/banned_emails are denied access to the server. The name of the file referenced by this directive can be specified using the banned_email_file directive.

The default value is NO.

 

 

 

ftpd_banner

When enabled, the string specified within this directive is displayed when a connection is established to the server. This option can be overridden by the banner_file directive.

By default vsftpd displays its standard banner.

 

local_enable

When enabled, local users are allowed to log into the system.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

Refer to  “Local User Options” for a list of directives affecting local users.

 

pam_service_name

Specifies the PAM service name for vsftpd.

The default value is ftp. On Red Hat Enterprise Linux 6, this option is set to vsftpd in the configuration file.

 

tcp_wrappers

When enabled, TCP wrappers are used to grant access to the server. If the FTP server is configured on multiple IP addresses, the VSFTPD_LOAD_CONF environment variable can be used to load different configuration files based on the IP address being requested by the client.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

userlist_deny

When used in conjunction with the userlist_enable directive and set to NO, all local users are denied access unless the username is listed in the file specified by the userlist_file directive. Because access is denied before the client is asked for a password, setting this directive to NO prevents local users from submitting unencrypted passwords over the network.

The default value is YES.

 

userlist_enable

When enabled, the users listed in the file specified by the userlist_file directive are denied access. Because access is denied before the client is asked for a password, users are prevented from submitting unencrypted passwords over the network.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

userlist_file

Specifies the file referenced by vsftpd when the userlist_enable directive is enabled.

The default value is /etc/vsftpd/user_list, which is created during installation.

 

3.      Anonymous user options

 

anon_mkdir_write_enable

When enabled in conjunction with the write_enable directive, anonymous users are allowed to create new directories within a parent directory which has write permissions.

The default value is NO.

 

anon_root

Specifies the directory vsftpd changes to after an anonymous user logs in.

There is no default value for this directive.

 

anon_upload_enable

When enabled in conjunction with the write_enable directive, anonymous users are allowed to upload files within a parent directory which has write permissions.

The default value is NO.

 

anon_world_readable_only

When enabled, anonymous users are only allowed to download world-readable files.

The default value is YES.

 

 

ftp_username

Specifies the local user account (listed in /etc/passwd) used for the anonymous FTP user. The home directory specified in /etc/passwd for the user is the root directory of the anonymous FTP user.

The default value is ftp.

 

no_anon_password

When enabled, the anonymous user is not asked for a password.

The default value is NO.

 

secure_email_list_enable

When enabled, only a specified list of email passwords for anonymous logins are accepted. This is a convenient way to offer limited security to public content without the need for virtual users.

Anonymous logins are prevented unless the password provided is listed in /etc/vsftpd/email_passwords. The file format is one password per line, with no trailing white spaces.

The default value is NO.

 

4.      Local user options

 

chmod_enable

When enabled, the FTP command SITE CHMOD is allowed for local users. This command allows the users to change the permissions on files.

The default value is YES.

 

chroot_list_enable

When enabled, the local users listed in the file specified in the chroot_list_file directive are placed in a chroot jail upon log in.

If enabled in conjunction with the chroot_local_user directive, the local users listed in the file specified in the chroot_list_file directive are not placed in a chroot jail upon log in.

The default value is NO.

 

chroot_list_file

Specifies the file containing a list of local users referenced when the chroot_list_enable directive is set to YES.

The default value is /etc/vsftpd/chroot_list.

 

chroot_local_user

When enabled, local users are change-rooted to their home directories after logging in.

The default value is NO.

Avoid enabling the chroot_local_user option

Enabling chroot_local_user opens up a number of security issues, especially for users with upload privileges. For this reason, it is not recommended.

 

guest_enable

When enabled, all non-anonymous users are logged in as the user guest, which is the local user specified in the guest_username directive.

The default value is NO.

 

guest_username

Specifies the username the guest user is mapped to.

The default value is ftp.

 

local_root

Specifies the directory vsftpd changes to after a local user logs in.

There is no default value for this directive.

 

local_umask

Specifies the umask value for file creation. Note that the default value is in octal form (a numerical system with a base of eight), which includes a “0” prefix. Otherwise the value is treated as a base-10 integer.

The default value is 077. On Red Hat Enterprise Linux 6, this option is set to 022 in the configuration file.

passwd_chroot_enable

When enabled in conjunction with the chroot_local_user directive, vsftpd change-roots local users based on the occurrence of the /./ in the home directory field within /etc/passwd.

The default value is NO.

 

user_config_dir

Specifies the path to a directory containing configuration files bearing the name of local system users that contain specific setting for that user. Any directive in the user’s configuration file overrides those found in /etc/vsftpd/vsftpd.conf.

There is no default value for this directive.

 

5.       Directory options

 

dirlist_enable

When enabled, users are allowed to view directory lists.

The default value is YES.

 

dirmessage_enable

When enabled, a message is displayed whenever a user enters a directory with a message file. This message resides within the current directory. The name of this file is specified in the message_file directive and is .message by default.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

force_dot_files

When enabled, files beginning with a dot ( .) are listed in directory listings, with the exception of the . and .. files.

The default value is NO.

 

hide_ids

When enabled, all directory listings show ftp as the user and group for each file.

The default value is NO.

 

message_file

Specifies the name of the message file when using the dirmessage_enable directive.

The default value is .message.

 

text_userdb_names

When enabled, text usernames and group names are used in place of UID and GID entries. Enabling this option may slow performance of the server.

The default value is NO.

 

use_localtime

When enabled, directory listings reveal the local time for the computer instead of GMT.

The default value is NO.

 

6.       File transfer options

 

download_enable

When enabled, file downloads are permitted.

The default value is YES.

 

chown_uploads

When enabled, all files uploaded by anonymous users are owned by the user specified in the chown_username directive.

The default value is NO.

 

chown_username

Specifies the ownership of anonymously uploaded files if the chown_uploads directive is enabled.

The default value is root.

 

write_enable

When enabled, FTP commands which can change the file system are allowed, such as DELE, RNFR, and STOR.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

7.      Logging options

 

dual_log_enable

When enabled in conjunction with xferlog_enable, vsftpd writes two files simultaneously: a wu-ftpd-compatible log to the file specified in the xferlog_file directive ( /var/log/xferlog by default) and a standard vsftpd log file specified in the vsftpd_log_file directive ( /var/log/vsftpd.log by default).

The default value is NO.

 

log_ftp_protocol

When enabled in conjunction with xferlog_enable and with xferlog_std_format set to NO, all FTP commands and responses are logged. This directive is useful for debugging.

The default value is NO.

 

syslog_enable

When enabled in conjunction with xferlog_enable, all logging normally written to the standard vsftpd log file specified in the vsftpd_log_file directive ( /var/log/vsftpd.log by default) is sent to the system logger instead under the FTPD facility.

The default value is NO.

 

vsftpd_log_file

Specifies the vsftpd log file. For this file to be used, xferlog_enable must be enabled and xferlog_std_format must either be set to NO or, if xferlog_std_format is set to YES, dual_log_enable must be enabled. It is important to note that if syslog_enable is set to YES, the system log is used instead of the file specified in this directive.

The default value is /var/log/vsftpd.log.

 

xferlog_enable

When enabled, vsftpd logs connections ( vsftpd format only) and file transfer information to the log file specified in the vsftpd_log_file directive ( /var/log/vsftpd.log by default). If xferlog_std_format is set to YES, file transfer information is logged but connections are not, and the log file specified in xferlog_file ( /var/log/xferlog by default) is used instead. It is important to note that both log files and log formats are used if dual_log_enable is set to YES.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

xferlog_file

Specifies the wu-ftpd-compatible log file. For this file to be used, xferlog_enable must be enabled and xferlog_std_format must be set to YES. It is also used if dual_log_enable is set to YES.

The default value is /var/log/xferlog.

 

xferlog_std_format

When enabled in conjunction with xferlog_enable, only a wu-ftpd-compatible file transfer log is written to the file specified in the xferlog_file directive ( /var/log/xferlog by default). It is important to note that this file only logs file transfers and does not log connections to the server.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

Maintaining compatibility with older log file formats

To maintain compatibility with log files written by the older wu-ftpd FTP server, the xferlog_std_format directive is set to YES under Red Hat Enterprise Linux. However, this setting means that connections to the server are not logged.

To both log connections in vsftpd format and maintain a wu-ftpd-compatible file transfer log, set dual_log_enable to YES.

If maintaining a wu-ftpd-compatible file transfer log is not important, either set xferlog_std_format to NO, comment the line with a hash sign ( #), or delete the line entirely.

 

8.      Network options

 

accept_timeout

Specifies the amount of time for a client using passive mode to establish a connection.

The default value is 60.

 

anon_max_rate

Specifies the maximum data transfer rate for anonymous users in bytes per second.

The default value is 0, which does not limit the transfer rate.

connect_from_port_20

When enabled, vsftpd runs with enough privileges to open port 20 on the server during active mode data transfers. Disabling this option allows vsftpd to run with less privileges, but may be incompatible with some FTP clients.

The default value is NO. On Red Hat Enterprise Linux 6, this option is set to YES in the configuration file.

 

connect_timeout

Specifies the maximum amount of time a client using active mode has to respond to a data connection, in seconds.

The default value is 60.

 

data_connection_timeout

Specifies maximum amount of time data transfers are allowed to stall, in seconds. Once triggered, the connection to the remote client is closed.

The default value is 300.

 

ftp_data_port

Specifies the port used for active data connections when connect_from_port_20 is set to YES.

The default value is 20.

 

idle_session_timeout

Specifies the maximum amount of time between commands from a remote client. Once triggered, the connection to the remote client is closed.

The default value is 300.

 

listen_address

Specifies the IP address on which vsftpd listens for network connections.

There is no default value for this directive.

Running multiple copies of vsftpd

If running multiple copies of vsftpd serving different IP addresses, the configuration file for each copy of the vsftpd daemon must have a different value for this directive. Refer to Section 17.2.4.1, “Starting Multiple Copies of vsftpd for more information about multihomed FTP servers.

 

listen_address6

Specifies the IPv6 address on which vsftpd listens for network connections when listen_ipv6 is set to YES.

There is no default value for this directive.

Running multiple copies of vsftpd

If running multiple copies of vsftpd serving different IP addresses, the configuration file for each copy of the vsftpd daemon must have a different value for this directive. Refer to Section 17.2.4.1, “Starting Multiple Copies of vsftpd for more information about multihomed FTP servers.

 

listen_port

Specifies the port on which vsftpd listens for network connections.

The default value is 21.

 

local_max_rate

Specifies the maximum rate data is transferred for local users logged into the server in bytes per second.

The default value is 0, which does not limit the transfer rate.

 

max_clients

Specifies the maximum number of simultaneous clients allowed to connect to the server when it is running in standalone mode. Any additional client connections would result in an error message.

The default value is 0, which does not limit connections.

 

max_per_ip

Specifies the maximum of clients allowed to connected from the same source IP address.

The default value is 0, which does not limit connections.

 

pasv_address

Specifies the IP address for the public facing IP address of the server for servers behind Network Address Translation (NAT) firewalls. This enables vsftpd to hand out the correct return address for passive mode connections.

There is no default value for this directive.

pasv_enable

When enabled, passive mode connects are allowed.

The default value is YES.

 

pasv_max_port

Specifies the highest possible port sent to the FTP clients for passive mode connections. This setting is used to limit the port range so that firewall rules are easier to create.

The default value is 0, which does not limit the highest passive port range. The value must not exceed 65535.

 

pasv_min_port

Specifies the lowest possible port sent to the FTP clients for passive mode connections. This setting is used to limit the port range so that firewall rules are easier to create.

The default value is 0, which does not limit the lowest passive port range. The value must not be lower 1024.

 

pasv_promiscuous

When enabled, data connections are not checked to make sure they are originating from the same IP address. This setting is only useful for certain types of tunneling.

 

Avoid enabling the pasv_promiscuous option

Do not enable this option unless absolutely necessary as it disables an important security feature which verifies that passive mode connections originate from the same IP address as the control connection that initiates the data transfer.

The default value is NO.

 

port_enable

When enabled, active mode connects are allowed.

The default value is YES.

 

 

FTP with SELinux

 

FTP SELinux Boolean settings

 

[root@server1 Desktop]# getsebool -a | grep ftp

allow_ftpd_anon_write –> off

allow_ftpd_full_access –> off

allow_ftpd_use_cifs –> off

allow_ftpd_use_nfs –> off

ftp_home_dir –> off

ftpd_connect_db –> off

httpd_enable_ftp_server –> off

tftp_anon_write –> off

 

[root@server1 Desktop]# semanage boolean -l | grep ftp

ftp_home_dir                   -> off   Allow ftp to read and write files in the user home directories

 

tftp_anon_write               -> off   Allow tftp to modify public files used for public file transfer services.

 

allow_ftpd_full_access   -> off   Allow ftp servers to login to local users and read/write all files on the system, governed by DAC.

 

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

 

allow_ftpd_anon_write   -> off   Allow ftp servers to upload files,  used for public file transfer services. Directories must be labeled public_content_rw_t.

 

allow_ftpd_use_cifs        -> off   Allow ftp servers to use cifs used for public file transfer services.

 

ftpd_connect_db              -> off   Allow ftp servers to use connect to mysql database

 

httpd_enable_ftp_server  -> off   Allow httpd to act as a FTP server by listening on the ftp port.

 

[root@server1 Desktop]# setsebool allow_ftpd_anon_write on

 

[root@server1 Desktop]# getsebool -a | grep ftp

allow_ftpd_anon_write –> on

allow_ftpd_full_access –> off

allow_ftpd_use_cifs –> off

allow_ftpd_use_nfs –> off

ftp_home_dir –> off

ftpd_connect_db –> off

httpd_enable_ftp_server –> off

tftp_anon_write –> off

 

FTP SELinux file context

 

Use one of the following types to share files through FTP:

 

public_content_t

Label files and directories you have created with the public_content_t type to share them read- public_content_t only through vsftpd. Other services, such as Apache HTTP Server, Samba, and NFS, also have access to files labeled with this type. Files labeled with the type can not be written to, even if Linux permissions allow write access. If you require write access, use the public_content_rw_t type.

 

public_content_rw_t

Label files and directories you have created with the public_content_rw_t type to share them with read and write permissions through vsftpd. Other services, such as Apache HTTP Server, Samba, and NFS, also have access to files labeled with this type. Remember that Booleans for each service must be turned on before they can write to files labeled with this type.

 

Vsftpd Example configurations

 

1.       Only allow the anonymous upload and can’t be access vsftpd login users

 

Configure client1.example.com     –               192.168.1.101

 

[root@client1 Desktop]# yum install -y vsftpd ftp

 

[root@client1 Desktop]# service vsftpd start

[root@client1 Desktop]# chkconfig vsftpd on

 

[root@server1 Desktop]# useradd ayyappan

[root@server1 Desktop]# passwd ayyappan

 

[root@client1 Desktop]# vim /etc/vsftpd/vsftpd.conf

12           anonymous_enable=YES

15           local_enable=NO                                 change default option YES

27           anon_upload_enable=YES                               uncomment the # and the default options is YES

 

:wq!

 

[root@client1 Desktop]# service vsftpd restart

 

[root@client1 Desktop]# getsebool -a | grep ftp

allow_ftpd_anon_write –> off

 

[root@client1 Desktop]# setsebool -P allow_ftpd_anon_write on

 

[root@client1 Desktop]# getsebool -a | grep ftp

allow_ftpd_anon_write –> on

 

[root@client1 Desktop]# ls -dZ /var/ftp/pub/

drwxr-xr-x. root root system_u:object_r:public_content_t:s0 /var/ftp/pub/

 

[root@client1 Desktop]# chcon -Rt public_content_rw_t /var/ftp/pub/

 

[root@client1 Desktop]# touch /var/ftp/pub/a

[root@client1 Desktop]# touch /var/ftp/pub/b

[root@client1 Desktop]# touch /var/ftp/pub/c

 

[root@client1 Desktop]# chmod 777 /var/ftp/pub/

 

Check the ftp login from client2.example.com          –               192.168.1.102

 

[root@client2 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): anonymous

331 Please specify the password.

Password:

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> pwd

257 “/”

ftp> dir

227 Entering Passive Mode (192,168,1,101,213,228).

150 Here comes the directory listing.

drwxrwxrwx    2 0        0            4096 Nov 16 01:11 pub

226 Directory send OK.

ftp> cd pub

250 Directory successfully changed.

ftp> put d

local: d remote: d

227 Entering Passive Mode (192,168,1,101,71,161).

150 Ok to send data.

226 Transfer complete.

ftp> put e

local: e remote: e

227 Entering Passive Mode (192,168,1,101,230,240).

150 Ok to send data.

226 Transfer complete.

ftp> put f

local: f remote: f

227 Entering Passive Mode (192,168,1,101,27,252).

150 Ok to send data.

226 Transfer complete.

ftp> get a

local: a remote: a

227 Entering Passive Mode (192,168,1,101,203,37).

150 Opening BINARY mode data connection for a (0 bytes).

226 Transfer complete.

ftp> get b

local: b remote: b

227 Entering Passive Mode (192,168,1,101,131,238).

150 Opening BINARY mode data connection for b (0 bytes).

226 Transfer complete.

ftp> get c

local: c remote: c

227 Entering Passive Mode (192,168,1,101,96,94).

150 Opening BINARY mode data connection for c (0 bytes).

226 Transfer complete.

ftp> dir

227 Entering Passive Mode (192,168,1,101,199,179).

150 Here comes the directory listing.

-rw-r–r–    1 0        0               0 Nov 16 01:10 a

-rw-r–r–    1 0        0               0 Nov 16 01:10 b

-rw-r–r–    1 0        0               0 Nov 16 01:11 c

-rw——-    1 14       50              0 Nov 16 01:12 d

-rw——-    1 14       50              0 Nov 16 01:13 e

-rw——-    1 14       50              0 Nov 16 01:13 f

226 Directory send OK.

ftp> delete a

550 Permission denied.

ftp> delete d

550 Permission denied.

ftp> bye

221 Goodbye.

 

Now test user login

[root@client1 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): ayyappan

530 This FTP server is anonymous only.

Login failed.

ftp> bye

221 Goodbye.

 

 

2.       How disable the anonymous userlogin password required options

 

[root@client1 Desktop]# vim /etc/vsftpd/vsftpd.conf

no_anon_password=YES

 

:wq!

 

[root@client2 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): anonymous

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> bye

221 Goodbye.

[root@client2 Desktop]#

 

3.       ftp user based configuration

a.       Create a user name ayyappan, arun, ravi and kumar

b.       All user no login in the shell prompt except kumar

c.        All password has 123

d.       Create group name ftpadmin

e.        The user ayyappan add has primary group in ftpadmin

f.        Ther user arun and ravi secondary group in ftpadmin

g.       Kumar don’t have any group

h.       Make a directory ftp and change ownership name ayyappan and group name ftpadmin

i.         The admin user only full permission and group user read only permission other user no access.

j.         Disable the anonymous user

 

[root@client1 Desktop]# yum install -y vsftpd ftp finger

 

[root@client1 Desktop]# service vsftpd status

vsftpd is stopped

 

[root@client1 Desktop]# service vsftpd start

Starting vsftpd for vsftpd:                                [  OK  ]

 

[root@client1 Desktop]# chkconfig vsftpd on

 

[root@client1 Desktop]# iptables –F

 

[root@client1 Desktop]# service iptables save

iptables: Saving firewall rules to /etc/sysconfig/iptables:[  OK  ]

 

[root@client1 Desktop]# service iptables restart

iptables: Flushing firewall rules:                         [  OK  ]

iptables: Setting chains to policy ACCEPT: filter          [  OK  ]

iptables: Unloading modules:                               [  OK  ]

iptables: Applying firewall rules:                         [  OK  ]

iptables: Loading additional modules: nf_conntrack_ftp     [  OK  ]

 

User add without home directory creating

 

[root@client1 ~]# useradd -M ayyappan

[root@client1 ~]# useradd -M arun

[root@client1 ~]# useradd -M ravi

 

User add with home directory

 

[root@client1 ~]# useradd kumar

 

User password settings

 

[root@client1 home]# passwd ayyappan

[root@client1 home]# passwd arun

[root@client1 home]# passwd ravi

[root@client1 home]# passwd kumar

 

Create group name

 

[root@client1 Desktop]# groupadd ftpadmin

 

The user ayyappan added as a primary group in ftpadmin

 

[root@client1 Desktop]# usermod -g ftpadmin ayyappan

 

The user arun and ravi secondary group in ftpadmin

 

[root@client1 Desktop]# usermod -G ftpadmin arun

[root@client1 Desktop]# usermod -G ftpadmin ravi

 

Change shell login user ayyappan, arun, and ravi

 

[root@client1 Desktop]# chsh -s /sbin/nologin ayyappan

Changing shell for ayyappan.

Shell changed.

[root@client1 Desktop]# chsh -s /sbin/nologin arun

Changing shell for arun.

Shell changed.

[root@client1 Desktop]# chsh -s /sbin/nologin ravi

Changing shell for ravi.

Shell changed.

 

Make a ftp share directory

[root@client1 Desktop]# mkdir /ftp

 

[root@client1 Desktop]# ll -dZ /ftp/

drwxr-xr-x. root root unconfined_u:object_r:default_t:s0 /ftp/

 

[root@client1 Desktop]# chmod -R 750 /ftp

 

[root@client1 Desktop]# chcon –reference /home/kumar/ /ftp

 

[root@client1 Desktop]# chown ayyappan:ftpadmin /ftp/

 

[root@client1 Desktop]# ll -dZ /ftp/

drwxr-x—. ayyappan ftpadmin unconfined_u:object_r:user_home_dir_t:s0 /ftp/

 

Create the ftp user home directory

 

[root@client1 Desktop]# usermod -d /ftp/ ayyappan

[root@client1 Desktop]# usermod -d /ftp/ arun

[root@client1 Desktop]# usermod -d /ftp/ ravi

 

SELinux boolean security enable ftp home directory

[root@client1 Desktop]# getsebool -a | grep ftp

ftp_home_dir –> off

 

 

[root@client1 Desktop]# setsebool -P ftp_home_dir on

 

[root@client1 Desktop]# getsebool -a | grep ftp

ftp_home_dir –> on

 

Vsftpd configuration

 

[root@client1 Desktop]# vim /etc/vsftpd/vsftpd.conf

anonymous_enable=NO

local_enable=YES

write_enable=YES

local_umask=022

dirmessage_enable=YES

xferlog_enable=YES

connect_from_port_20=YES

xferlog_std_format=YES

listen=YES

 

pam_service_name=vsftpd

userlist_enable=YES

tcp_wrappers=YES

 

:wq!

 

Deny access ftp particular user

 

[root@client1 Desktop]# vim /etc/vsftpd/ftpusers

kumar

 

:wq!

 

[root@client2 Desktop]# touch a b c

 

Check ftp admin user ayyappan upload, download, delete and make directory

 

[root@client2 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): ayyappan

331 Please specify the password.

Password:

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> put a

local: a remote: a

227 Entering Passive Mode (192,168,1,101,238,226).

150 Ok to send data.

226 Transfer complete.

ftp> put b

local: b remote: b

227 Entering Passive Mode (192,168,1,101,193,116).

150 Ok to send data.

226 Transfer complete.

ftp> get a

local: a remote: a

227 Entering Passive Mode (192,168,1,101,135,44).

150 Opening BINARY mode data connection for a (0 bytes).

226 Transfer complete.

ftp> mkdir test

257 “/ftp/test” created

ftp> mkdir test1

257 “/ftp/test1” created

ftp> bye

 

[root@client2 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): ayyappan

331 Please specify the password.

Password:

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> dir

227 Entering Passive Mode (192,168,1,101,223,180).

150 Here comes the directory listing.

-rw-r–r–    1 500      504             0 Nov 17 08:39 a

-rw-r–r–    1 500      504             0 Nov 17 08:39 b

drwxr-xr-x    2 500      504          4096 Nov 17 08:39 test

drwxr-xr-x    2 500      504          4096 Nov 17 08:39 test1

226 Directory send OK.

ftp> rmdir test1

250 Remove directory operation successful.

ftp> delete a

250 Delete operation successful.

ftp> bye

221 Goodbye.

 

Check ftp group user arun

 

[root@client2 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): arun

331 Please specify the password.

Password:

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> dir

227 Entering Passive Mode (192,168,1,101,24,109).

150 Here comes the directory listing.

-rw-r–r–    1 500      504             0 Nov 17 08:39 b

drwxr-xr-x    2 500      504          4096 Nov 17 08:39 test

226 Directory send OK.

ftp> get b

local: b remote: b

227 Entering Passive Mode (192,168,1,101,102,42).

150 Opening BINARY mode data connection for b (0 bytes).

226 Transfer complete.

ftp> put c

local: c remote: c

227 Entering Passive Mode (192,168,1,101,73,194).

553 Could not create file.

ftp> mkdir group

550 Create directory operation failed.

ftp> bye

221 Goodbye.

 

Check ftp deny user

[root@client2 Desktop]# ftp client1.example.com

Connected to client1.example.com (192.168.1.101).

220 (vsFTPd 2.2.2)

Name (client1.example.com:root): kumar

331 Please specify the password.

Password:

530 Login incorrect.

Login failed.

ftp> bye

221 Goodbye.

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

User and Group Disk Quota on UNIX / Linux

User and Group Disk Quota on UNIX / Linux

On Linux, you can setup disk quota using one of the following methods:

File system base disk quota allocation

User or group based disk quota allocation

disk-quota-300x213

On the user or group based quota, following are three important factors to consider:

Hard limit – For example, if you specify 2GB as hard limit, user will not be able to create new files after 2GB

Soft limit – For example, if you specify 1GB as soft limit, user will get a warning message “disk quota exceeded”, once they reach 1GB limit. But, they’ll still be able to create new files until they reach the hard limit

Grace Period – For example, if you specify 10 days as a grace period, after user reach their hard limit, they would be allowed additional 10 days to create new files. In that time period, they should try to get back to the quota limit.

Required Package:

quota-devel-3.17-20.el6.i686

quota-3.17-20.el6.i686

/etc/quotagrpadmins

/etc/quotatab

/etc/sysconfig/quota_nld

/etc/warnquota.confonfiguration

/etc/fstab

Commands:

quota – display disk usage and limits

rquota – implement quotas on remote machines

fstab – static information about the filesystems

edquota – edit user quotas

setquota – set disk quotas (Command line editor)

quotacheck – scan a filesystem for disk usage, create, check and repair quota files

quotaon – turn filesystem quotas on

quotaoff – turn filesystem quotas off

repquota – produce a summary of quota information for a file system

convertquota – convert quota from old file format to new one. Convert quota.user to aquota.user

quotactl – manipulate disk quotas (C programmer interface)

Enter Single-User Mode

As you’ll need to remount the /home filesystem, you make sure that no other users or processes are using it by first entering single-user mode from the console. If you are certain that you’re the only user on the system, you might be able to skip this step. Entering single-user mode automatically logs off all users and stops cron jobs, so wait until after hours to do in a business environment. The procedure is quick:

1) Use the who command to see which users are logged in. If there are any, besides yourself, send a message stating that the system is about to shutdown with the wall command:

[root@bigboy tmp]# who

root     pts/0        Nov  6 14:46 (192-168-1-242.my-site.com)

bob      pts/0        Nov  6 12:01 (192-168-1-248.my-site.com)

bunny    pts/0        Nov  6 16:25 (192-168-1-250.my-site.com)

[root@bigboy tmp]# wall The system is shutting down now!

Broadcast message from root (pts/0) (Sun Nov  7 15:04:27 2004):

The system is shutting down now!

[root@bigboy tmp]#

2) Log into the VGA console and enter single user mode.

[root@bigboy tmp]# init 1

1. Enable quota check on filesystem

First, you should specify which filesystem are allowed for quota check.

Modify the /etc/fstab, and add the keyword usrquota and grpquota to the corresponding filesystem that you would like to monitor.

The following example indicates that both user and group quota check is enabled on /home filesystem

# cat /etc/fstab

LABEL=/home    /home   ext2   defaults,usrquota,grpquota  1 2

Reboot the server after the above change.

2. Initial quota check on Linux filesystem using quotacheck

Once you’ve enabled disk quota check on the filesystem, collect all quota information initially as shown below.

# quotacheck -avug

quotacheck: Scanning /dev/sda3 [/home] done

quotacheck: Checked 5182 directories and 31566 files

quotacheck: Old file not found.

quotacheck: Old file not found.

In the above command:

a: Check all quota-enabled filesystem

v: Verbose mode

u: Check for user disk quota

g: Check for group disk quota

The above command will create a aquota file for user and group under the filesystem directory as shown below.

# ls -l /home/

-rw——-    1 root     root        11264 Jun 21 14:49 aquota.user

-rw——-    1 root     root        11264 Jun 21 14:49 aquota.group

3. Assign disk quota to a user using edquota command

Use the edquota command as shown below, to edit the quota information for a specific user.

For example, to change the disk quota for user ‘ramesh’, use edquota command, which will open the soft, hard limit values in an editor as shown below.

# edquota ramesh

Disk quotas for user ramesh (uid 500):

Filesystem           blocks       soft       hard     inodes     soft     hard

/dev/sda3           1419352          0          0       1686        0        0

Once the edquota command opens the quota settings for the specific user in a editor, you can set the following limits:

soft and hard limit for disk quota size for the particular user.

soft and hard limit for the total number of inodes that are allowed for the particular user.

4. Report the disk quota usage for users and group using repquota

Use the repquota command as shown below to report the disk quota usage for the users and groups.

# repquota /home

*** Report for user quotas on device /dev/sda3

Block grace time: 7days; Inode grace time: 7days

Block limits                File limits

User            used    soft    hard  grace    used  soft  hard  grace

———————————————————————-

root      —  566488       0       0           5401     0     0

nobody    —    1448       0       0             30     0     0

ramesh    — 1419352       0       0           1686     0     0

john      —   26604       0       0            172     0     0

5. Add quotacheck to daily cron job

Add the quotacheck to the daily cron job. Create a quotacheck file as shown below under the /etc/cron.daily directory, that will run the quotacheck command everyday. This will send the output of the quotacheck command to root email address.

# cat /etc/cron.daily/quotacheck

quotacheck –avug

RPM (REDHAT Package Management)

RPM has five basic modes of operation (not including package building)

1.      Installing                      –           i

2.      Upgrading                    –           U

3.      Freshening                   –           F

4.      Uninstalling                 –           e

5.      Querying                      –           q

6.      Verifying                     –           V

7.      Check signature                       –           K

Installing

rpm –i

v                      –           Verbose

h                      –           The package archive is unpacked

–force             –           force

–test                –           install simulate

–nodeps          –           don’t check dependency

Upgrading

rpm –Uvh

–force

–replacepkgs

–replacefiles

–oldpackage

Freshening

rpm –Fvh

Unistalling

rpm –ev

–force

–nodeps

Querying

rpm –q[options]

a        –           query all installed packages

c        –           List only configuration files (-l)

f         –           Query package owning file

d        –           List only documents file (-l)

g        –           Query packages with the group of GROUP

p        –           Package file (to specify the package name

l         –           List

i         –           Display packages information

s         –           Display the states of files (normal, not installed, replaced)

R        –           Requires

–last  –           listing by install time such

–whatprovides

Verifying

rpm –V

a        –           all

p        –           Specify the package

f         –           Specify the file

Check the signature

rpm –Kv

Examples

1.      How to install the rpm package

[root@linux Packages]# rpm -ivh firefox-3.6.24-3.el6_1.x86_64.rpm

warning: firefox-3.6.24-3.el6_1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

Preparing…                ########################################### [100%]

1:firefox                ########################################### [100%]

2.      How uninstall the rpm package

[root@linux yum.repos.d]# rpm -ev firefox

3.      How to check the last installed rpm package with time and date

[root@linux Packages]# rpm -qa –last | head

firefox-3.6.24-3.el6_1                        Sun 16 Sep 2012 07:48:07 PM IST

ftp-0.17-51.1.el6                             Sat 15 Sep 2012 09:21:23 AM IST

ypserv-2.19-22.el6                            Sat 15 Sep 2012 08:16:55 AM IST

tree-1.5.3-2.el6                              Sat 15 Sep 2012 08:11:46 AM IST

words-3.0-17.el6                              Fri 20 Jul 2012 03:02:11 AM IST

man-pages-3.22-17.el6                         Fri 20 Jul 2012 03:02:11 AM IST

zd1211-firmware-1.4-4.el6                     Fri 20 Jul 2012 03:02:06 AM IST

xorg-x11-drv-ati-firmware-6.14.2-7.el6        Fri 20 Jul 2012 03:02:06 AM IST

rt73usb-firmware-1.8-7.el6                    Fri 20 Jul 2012 03:02:06 AM IST

rt61pci-firmware-1.2-7.el6                    Fri 20 Jul 2012 03:02:06 AM IST

4.      How to reinstall the package

[root@linux Packages]# rpm -Uvh firefox-3.6.24-3.el6_1.x86_64.rpm

warning: firefox-3.6.24-3.el6_1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

Preparing…                ########################################### [100%]

package firefox-3.6.24-3.el6_1.x86_64 is already installed

[root@linux Packages]# rpm -Uvh –replacepkgs firefox-3.6.24-3.el6_1.x86_64.rpm

warning: firefox-3.6.24-3.el6_1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

Preparing…                ########################################### [100%]

1:firefox                ########################################### [100%]

5.      Which rpm package does file belong to?

[root@linux Packages]# rpm -qf /etc/vsftpd/vsftpd.conf

vsftpd-2.2.2-6.el6_0.1.x86_64

6.      Locate documentation of a package that owns file using rpm –qdf and rpm -qdp

[root@linux Packages]# rpm -qdp firefox-3.6.24-3.el6_1.x86_64.rpm

warning: firefox-3.6.24-3.el6_1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

/usr/lib64/firefox-3.6/LICENSE

/usr/lib64/firefox-3.6/README.txt

/usr/share/man/man1/firefox.1.gz

[root@linux Packages]# rpm -qdf /usr/bin/createrepo

/usr/share/doc/createrepo-0.9.8/COPYING

/usr/share/doc/createrepo-0.9.8/ChangeLog

/usr/share/doc/createrepo-0.9.8/README

/usr/share/man/man1/mergerepo.1.gz

/usr/share/man/man1/modifyrepo.1.gz

/usr/share/man/man8/createrepo.8.gz

7.       How to check the configuration files

[root@linux Packages]# rpm -Kv vsftpd-2.2.2-6.el6_0.1.x86_64.rpm

vsftpd-2.2.2-6.el6_0.1.x86_64.rpm:

Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

Header SHA1 digest: OK (8005076799a57ab5c13045b5dd0c2aa890c8ac03)

V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

MD5 digest: OK (25e1511c9e217d9d345dd2fb5f92503d)

8.      Information about installed RPM package using rpm –qi, rpm –qip, rpm –qfi

[root@linux ~]# rpm -qi vsftpd

Name        : vsftpd                       Relocations: (not relocatable)

Version     : 2.2.2                             Vendor: Red Hat, Inc.

Release     : 6.el6_0.1                     Build Date: Fri 04 Mar 2011 03:35:10 PM IST

Install Date: Thu 19 Jul 2012 09:58:04 PM IST      Build Host: hs20-bc2-3.build.redhat.com

Group       : System Environment/Daemons    Source RPM: vsftpd-2.2.2-6.el6_0.1.src.rpm

Size        : 338480                           License: GPLv2 with exceptions

Signature   : RSA/8, Wed 09 Mar 2011 07:39:28 PM IST, Key ID 199e2f91fd431d51

Packager    : Red Hat, Inc.

URL         : http://vsftpd.beasts.org/

Summary     : Very Secure Ftp Daemon

Description :

vsftpd is a Very Secure FTP daemon. It was written completely from

scratch.

[root@linux ~]# cd /var/ftp/pub/rhel6.2/Packages/

[root@linux Packages]# rpm -qip vsftpd-2.2.2-6.el6_0.1.x86_64.rpm

warning: vsftpd-2.2.2-6.el6_0.1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

Name        : vsftpd                       Relocations: (not relocatable)

Version     : 2.2.2                             Vendor: Red Hat, Inc.

Release     : 6.el6_0.1                     Build Date: Fri 04 Mar 2011 03:35:10 PM IST

Install Date: (not installed)               Build Host: hs20-bc2-3.build.redhat.com

Group       : System Environment/Daemons    Source RPM: vsftpd-2.2.2-6.el6_0.1.src.rpm

Size        : 338480                           License: GPLv2 with exceptions

Signature   : RSA/8, Wed 09 Mar 2011 07:39:28 PM IST, Key ID 199e2f91fd431d51

Packager    : Red Hat, Inc.

URL         : http://vsftpd.beasts.org/

Summary     : Very Secure Ftp Daemon

Description :

vsftpd is a Very Secure FTP daemon. It was written completely from

scratch.

9.      Verify a particular RPM package using rpm –Vp

[root@linux Packages]# rpm -Vp firefox-3.6.24-3.el6_1.x86_64.rpm

warning: firefox-3.6.24-3.el6_1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

10.  How to check the signature

[root@linux Packages]# rpm -Kv vsftpd-2.2.2-6.el6_0.1.x86_64.rpm

vsftpd-2.2.2-6.el6_0.1.x86_64.rpm:

Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

Header SHA1 digest: OK (8005076799a57ab5c13045b5dd0c2aa890c8ac03)

V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

MD5 digest: OK (25e1511c9e217d9d345dd2fb5f92503d)

11.  How to check the dependency rpm

[root@linux Packages]# rpm -qRp createrepo-0.9.8-4.el6.noarch.rpm

warning: createrepo-0.9.8-4.el6.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY

/bin/sh

/usr/bin/env

/usr/bin/python

deltarpm

libxml2-python

python >= 2.1

python(abi) = 2.6

python-deltarpm

rpm >= 4.1.1

rpm-python

rpmlib(CompressedFileNames) <= 3.0.4-1

rpmlib(FileDigests) <= 4.6.0-1

rpmlib(PartialHardlinkSets) <= 4.0.4-1

rpmlib(PayloadFilesHavePrefix) <= 4.0-1

yum >= 3.2.23-10

yum-metadata-parser

rpmlib(PayloadIsXz) <= 5.2-1

Review Questions

1. What two commands are used for package management?

2. What are the three modes in which the rpm command can operate?

3. What option would you use to query an installed package using the rpm

command?

4. How would you install a group of packages all at a single time?

5. What options with the yum command would you use to remove a package?

6. Where are Yum repository config files located?

7. What command can you use to create your own repositories?

8. What command is used to create an RPM package?

9. What are the five required directories when building RPMS?

10. If a package is built on an RHEL6 system and deployed to a custom RHEL5

repository, are RHEL5 systems able to use it?

Answers to Review Questions

1. The yum and rpm commands are used for package management.

2. The rpm command can operate in install, query, or verify modes.

3. You can use the -q option to query an installed package. Combining grep and

the -qa options, you can search among all installed packages on the system.

4. Use the yum groupinstall command to install multiple packages in a single

group at once.

5. You can use the remove or erase options with yum to remove a package.

6. Yum repository config files (.repo files) are located in the /etc/yum.repos.d directory.

You can also make direct entries into the main /etc/yum.conf file.

7. createrepo

8. rpmbuild

9. The five directories are BUILD, RPMS, SOURCES, SPECS, and SRPMS.

10. No. Red Hat Enterprise Linux 6 uses a different key to sign its packages.

YUM Server and Client Configuration in RHEL 6

Server configuration steps
 
Yum server IP = 192.168.1.100
Yum server hostname = linux.example.com
Should be flush the iptables and restart the network service

iptables -L

iptables -F

service iptables save

service iptables restart

service network restart

Step 1: Insert the RHEL 6 CD

[root@server Desktop]# cd /media/RHEL_6.1\ x86_64\ Disc\ 1/Packages/

Yum server required packages

 

[root@server Packages]# rpm -ivh vsftpd*

[root@server Packages]# rpm -ivh deltarpm-3.5-0.5.20090913git.el6.x86_64.rpm

[root@server Packages]# rpm -ivh python-deltarpm-3.5-0.5.20090913git.el6.x86_64.rpm

[root@server Packages]# rpm -ivh createrepo-0.9.8-4.el6.noarch.rpm

Step 2: Check the installed packages

[root@server1 Desktop]# rpm -qa vsftp*
vsftpd-2.2.2-6.el6_0.1.x86_64
[root@server1 Desktop]# rpm -qa deltarpm*
deltarpm-3.5-0.5.20090913git.el6.x86_64
[root@server1 Desktop]# rpm -qa python-deltarpm*
python-deltarpm-3.5-0.5.20090913git.el6.x86_64
[root@server1 Desktop]# rpm -qa createrepo*
createrepo-0.9.8-4.el6.noarch

Step 3 : FTP service start

 

[root@server Packages]# service vsftpd status

[root@server Packages]# service vsftpd start

[root@server Packages]# service vsftpd status

[root@server Packages]# chkconfig vsftpd on

Step 4: Copy the rhel6 dvd content

[root@server Packages]# cd

[root@server ~]# cp -rf /media/RHEL_6.1\ x86_64\ Disc\ 1/       /var/ftp/pub/

[root@server ~]# cd /var/ftp/pub/

[root@server pub]# ls

RHEL_6.1 x86_64 Disc 1

[root@server pub]# mv RHEL_6.1\ x86_64\ Disc\ 1/ rhel6.1

[root@server pub]# ls

rhel6.1

Step 5: Single mode installation createrepo

[root@server ~]# createrepo -v /var/ftp/pub/

[root@server ~]# cd /var/ftp/pub/

[root@server pub]# ls

repodata  rhel6.1

Step 6: Group installation createrepo

[root@server repodata]# cp –rf /var/ftp/pub/rhel6.1/repodata/5819e9580b5a81a9eec9e2c6e91fc9992a7ccadaa3bcd5ecb2e87a8669eefcec-comps-rhel6-Server.xml      /var/ftp/pub/repodata/

[root@server ~]# createrepo -g /var/ftp/pub/repodata/5819e9580b5a81a9eec9e2c6e91fc9992a7ccadaa3bcd5ecb2e87a8669eefcec-comps-rhel6-Server.xml /var/ftp/pub/

The above command creates the support files necessary for our yum repository and all supported files will be placed into repodata subdirectory. The createrepo command will create following files:

1.      repod.xml: This file keeps information about timestamps and checksum values for below three files

2.      primary.xml.gz: This file keeps list of the all the RPMs in the repository and dependency information.

3.      filelists.xml.gz: This file keeps a list of all the files in all the RPMs.

4.      other.xml.gz: This file contains additional information, including the changes logs for the RPMs.

5.      comps*.xml: This file keeps information about packages groups. This allows group installation.

If we add new rpms to the database, we will need to repeat the above command and this will create rpms group database with createrepo command.

Before, we re-run createrepo command to update the yum database, we need to create backup of comps*.xml file. This file can be backed up anywhere on the system, however, in this case We are backing up this file in /tmp folder. That can be done with following:

#cd   /var/ftp/pub/Packages/repodata

#cp   *comps*   /tmp/

Now, the file has been backed up, we will start updating the database. We will rebuild the yum repository with createrepo command. And then, we will update comps*.xml file for package group database.

#createrepo    /var/ftp/pub/Packages/

#createrepo -g  /tmp/*comps*   /var/ftp/pub/Packages/

 

Step 7 : Create the repo file.

[root@server ~]# vim /etc/yum.repos.d/server.repo

[server]

name=rhel6.1 yum server 64bit

baseurl=file:///var/ftp/pub

enabled=1

gpgcheck=0

gpgcheck This field tells yum server to check for packages signatures for its originality. 1 for “Yes” and 0 for “No”.

gpgkey  if you choose 1 or “Yes” for gpgcheck then you need to specify key to check signatures of the packages.

enabled Either ‘1’ or ‘0’. This tells YUM whether or not to use this repository.

[root@server ~]# yum clean all

[root@server ~]# yum makecache

[root@server ~]# yum list all

[root@server ~]# yum grouplist

—————————————————————————————————————————-

Yum client repo configuring

Yum client IP = 192.168.1.101

Yum client hostname = client1.example.com

[root@client~]# vim /etc/yum.repos.d/client.repo

[client]

name=rhel6.1 yum client 64bit

baseurl=ftp://192.168.1.100/pub

enabled=1

gpgcheck=0

 

[root@client~]# yum clean all

[root@server ~]# yum makecahe

[root@client~]# yum list all

[root@server ~]# yum grouplist