Wednesday, February 27, 2008

Deleting a non-empty directory Linux Tips

To delete a directory that has files on it, do

#rm -rf dir "DIR NAME"

Tuesday, February 26, 2008

Disabling GUI on Linux How-to

To disable GUI on Linux, Edit the file /etc/inittab

Change the line

id:5:initdefault:

to

id:3:initdefault:


Default runlevel. The runlevels used by RHS are:
0 - halt (Do NOT set initdefault to this)
1 - Single user mode
2 - Multiuser, without NFS (The same as 3, if you do not have networking)
3 - Full multiuser mode
4 - unused
5 - X11
6 - reboot (Do NOT set initdefault to this)

Disallow direct root login via SSH How-to

To disallow direct root login via SSH, edit the "/etc/ssh/sshd_config" file with a text editor and find the following line:

#PermitRootLogin yes

Change the yes to no and remove the comment character at the beginning of the line:

PermitRootLogin no

Restart the sshd service.

#service sshd restart

Monday, February 25, 2008

Apache Virtual Hosting How-to


Virtual Hosting on Apache



Saturday, February 23, 2008

Linux How-to: VSFTPD

Thursday, February 21, 2008

Linux How-to: Apache Redirection

Apache Redirection from http to https:

RewriteEngine on
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^/(.*)$ https://my.domain.com/$1 [L,R]
RewriteLog "/var/log/httpd/rewrite.log"
RewriteLogLevel 4

Tuesday, February 19, 2008

Linux How-to: MySQL Database

Linux How-to: MySQL / PHP / Apache / SSL

Install the ff. applications:

1. Mysql

2. Php

3. Httpd

4. OpenSSL

To check package => rpm –qa |grep “package name”

To install package => yum install “package name”

Mysql Settings:

Start mysql service:

# service mysqld start

Add mysqladmin user:

# mysqladmin –u root password password

Access mysqladmin:

# mysql –u root –p

Enter Password: password

Create database:

> create database databasename;

Add privileges on user:

> grant all privileges on databasename.* to root@”%” identified by password;

Add other users:

> grant all privileges on databasename.* to user@”%” identified by J0shu@;

Apache settings:

Add line to httpd.conf:

AddType application/x-httpd-php .php

Install the ff. packages:

  • mod_ssl
  • openssl
  • openssl-devel

Enable SSL on Apache:

Edit or create an OpenSSL template:

Look inside the directory /usr/share/ssl/ for a file named openssl.cnf and open it in your favorite editor. You will need to look for and change the following values in the file:

countryName_default: put the name of your country

stateOrProvinceName_default: put the name of your state or province

localityName_default: put the name of your locality (street? region?)

organizationName_default: put the default organization name

organizationalUnitName_default: put your organization unit (OU) name

You don't actually need to do the above step, but it can be very useful later on, when you are generating your certificates, because you have already setup your defaults here.

Create a new CA certificate:

There is a supplied CA script inside the directory /usr/share/ssl/misc/ that you can use to generate your certificate. To begin generating your certificate, simply execute the following commands:

[root@localhost root]# cd /usr/share/ssl/misc
[root@localhost misc]# ./CA -newca

Press ENTER to create the new certificate and you will be prompted to key-in a passphrase. You will need to use this passphrase later, so you should remember what you keyed in here. Then you will be prompted for the particulars of your organization, etc. If you edited the openssl.cnf file properly in the previous step, you should be able to just hit ENTER for all the options except your server host name. A sample session is shown below. In this session, I am generating a CA certificate for my local Fedora Core 1 workstation:

[root@localhost misc]# ./CA -newca
CA certificate filename (or enter to create)
 
Making CA certificate ...
Generating a 1024 bit RSA private key
..++++++
............++++++
writing new private key to './demoCA/private/./cakey.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [SG]:
State or Province Name (full name) [Singapore]:
Locality Name (eg, city) [Singapore]:
Organization Name (eg, company) [Cymulacrum, Pte Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []: localhost.localdomain
Email Address []: someone@somedomain.com
 

Create a Certificate Signing Request (CSR):

To create a CSR, we will use the same CA script, but with a different switch.

[root@localhost misc]# ./CA -newreq
Generating a 1024 bit RSA private key
...++++++
................++++++
writing new private key to 'newreq.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [SG]:
State or Province Name (full name) [Singapore]:
Locality Name (eg, city) [Singapore]:
Organization Name (eg, company) [Cymulacrum, Pte Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []: localhost.localdomain
Email Address []: someone@somedomain.com

You see how useful creating or editing the template file is ? If you did not set the defaults, you'd have to key in the same information all over again.

You will be prompted for extra attributes, a challenge password and an optional company name. If you don't need any of this, you can safely ignore these messages and just hit ENTER.

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Request (and private key) is in newreq.pem

Note the last line, which states that your CSR has been created, and is called newreq.pem in the current directory.

Sign the CSR:

If you have gotten this far without any errors, you can now sign the CSR. To do that, we will use the CA script again, but, again, with a different switch.

[root@localhost misc]# ./CA -sign

You will be prompted for your passphrase, and then information about your certificate will spew out on the screen. You should see something like what is shown below. I have omitted some information that comes up after the particulars of your organization.

Using configuration from /usr/share/ssl/openssl.cnf
Enter pass phrase for ./demoCA/private/cakey.pem:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Feb  7 06:15:19 2004 GMT
            Not After : Feb  6 06:15:19 2005 GMT
        Subject:
            countryName               = SG
            stateOrProvinceName       = Singapore
            localityName              = Singapore
            organizationName          = Somewhere, Pte Ltd
            commonName                = localhost.localdomain
            emailAddress              = someone@somewhere.com

You will then be asked to sign the certificate and commit the changes.

Sign the certificate? [y/n]:y
 
1 out of 1 certificate requests certified, commit? [y/n]y

Information about your signed certificate will then be dumped to screen. Note the validity dates of the certificate.

At the end of the information dump, you will be told that the certificate filename is newcert.pem, and can be found in the current directory.

-----END CERTIFICATE-----
Signed certificate is in newcert.pem

Store certificates in a directory:

Finally, we will create a directory and copy the newly created certificates to the new directory.

[root@localhost var]# mkdir myCA
[root@localhost var]# cd myCA
[root@localhost myCA]# cp /usr/share/ssl/misc/demoCA/cacert.pem .
[root@localhost myCA]# cp /usr/share/ssl/misc/newcert.pem ./servercert.pem
[root@localhost myCA]# cp /usr/share/ssl/misc/newreq.pem ./serverkey.pem
[root@localhost myCA]# ls
cacert.pem  servercert.pem  serverkey.pem

We will now need to copy the certificates and keys to a directory where Apache can access it. For simplicity, we will overwrite the default certificates that come with the mod_ssl RPM package.

[root@localhost myCA]# cd /var/myCA
[root@localhost myCA]# cp servercert.pem /etc/httpd/conf/ssl.crt/server.crt 
cp: overwrite `/etc/httpd/conf/ssl.crt/server.crt'? y
[root@localhost myCA]# cp serverkey.pem /etc/httpd/conf/ssl.key/server.key
cp: overwrite `/etc/httpd/conf/ssl.key/server.key'? y

Edit ssl.conf (optional):

Now, we enable SSL operations for Apache. Open ssl.conf for editing and uncomment and edit the following directives:

· DocumentRoot

· ServerName

· ServerAdmin

You may want to change DocumentRoot to point to another directory, such as /var/www/ssl, and place your SSL files inside there instead.

To test your SSL configuration, create a simple HTML file, name it index.html and place it inside the DocumentRoot directory defined above.

Test SSL:

Finally, we are ready to test our new SSL_enabled Apache web server. Start Apache. You will be asked to key in your passphrase. Enter your passphrase and observe that Apache 2 starts up. Open a browser and try to go to the URL https://localhost or http://localhost:443. If you have already created an index.html inside your DocumentRoot for your SSL configuration, you should see that page open up, but not before you get a certificate warning in your browser. If you see the certificate warning, it means that you have successfully setup Apache for SSL operations. Congratulations!

Disabling the passphrase on startup (Optional):

Sometimes, the passphrase prompt can be inconvenient, especially when you want Apache to startup automatically on boot, without user intervention. We can disable the passphrase prompt by simply de-crypting the server key. To do this, we begin by making a copy of the server keyfile, then run the following command to decrypt it:

# cd /etc/httpd/conf/ssl.key
# cp server.key server.bak
#openssl rsa -in server.bak -out server.key

Monday, February 18, 2008

Apache Web Log-in Authentication (Password File) Part III

Using LDAP for Apache Authentication:

This method authenticates using Apache 2.0 and mod_auth_ldap on Linux (supplied by default with RHEL4, CentOS4, FC3 RPM package mod_auth_ldap) and an LDAP server. LDAP can be used to authenticate user accounts on Linux and other computer systems as well as web site logins. Also see YoLinux TUTORIAL: LDAP system authentication.

Try this out with your Apache server authenticating to our open LDAP server using our Three Stooges example.

Authenticate to an Open LDAP server. (No bind name/password required to access LDAP server)

File: httpd.conf (portion)

..
...


AuthType Basic
AuthName "Stooges Web Site: Login with email address"
AuthLDAPURL ldap://ldap.yo-linux.com:389/o=stooges?mail
require valid-user


...
..

or create the file /var/www/html/.htaccess

AuthName "Stooges Web Site: Login with email address"
AuthType Basic
AuthLDAPURL ldap://ldap.your-domain.com:389/o=stooges?mail
require valid-user

Point your browser to http://localhost/
Login with the user id "LFine@isp.com" and password "larrysecret".
You will be asked to use a user id (email address) and password to enter the site.

Bind with a bind DN: (password protected LDAP repository)

File: httpd.conf (portion)

..
...


AuthType Basic
AuthName "Stooges Web Site: Login with email address"
AuthLDAPEnabled on
AuthLDAPURL ldap://ldap.your-domain.com:389/o=stooges?mail
AuthLDAPBindDN "cn=StoogeAdmin,o=stooges"
AuthLDAPBindPassword secret1
require valid-user


...
..

Examples:

* require valid-user: Allow all users if authentication (password) is correct.
* require user greg phil bob: Allow only greg phil bob to login.
* require group accounting: Allow only users in group "accounting" to authenticate.

For this LDAP authentication example to work, configure your LDAP server with our YoLinux Three Stooges example and set the password in the /etc/openldap.slapd.conf file.

This example specified the use of the email address as a login id. If using user id's specify:

AuthLDAPURL ldap://ldap.your-domain.com:389/o=stooges?uid

Authenticating with Microsoft Active directory using Microsoft's "Unix services for Windows":

AuthLDAPURL ldap://ldap.your-domain.com:389/ou=Employees,ou=Accounts,dc=sos,dc=com?sAMAccountName?sub

Also note that encrypted connections will use the URL prefix "ldaps://" and the added directives:

* LDAPTrustedCA directory-path/filename
* LDAPTrustedCAType type
Where the "type" is one of:
o DER_FILE: file in binary DER format
o BASE64_FILE: file in Base64 format
o CERT7_DB_PATH: Netscape certificate database file

Restart Apache after editing the configuration file: service httpd restart for configuration changes to take effect.
See /var/log/httpd/error_log for configuration errors.

Other LDAP modules:

* Apache LDAP module auth_ldap - (Apache 1.3)
* Apache LDAP module mod_ldap - (Apache 1.3)
* Apache LDAP module mod_ldap_userdir (Apache 2.x)


Using a MySQL database for Apache Authentication:

Two Apache modules are available for database authentication:

  • MySQL: mod_auth_mysql (This tutorial)
    • Red Hat RPM package: mod_auth_mysql
    • SuSE RPM package: apache2-mod_auth_mysql
  • DBM database file: mod_auth_dbm
    (Fast even for 1000's of users.)
Apache Configuration:
  • Red Hat: /etc/httpd/conf/httpd.conf or /etc/httpd/conf.d/application.conf
  • SuSE: /etc/apache2/httpd.conf or /etc/apache2/conf.d/application.conf

..
...


AuthType Basic
AuthName "Add your login message here."
AuthMySQLHost localhost
AuthMySQLUser db_user
AuthMySQLPassword db_password
AuthMySQLDB database_name_used_for_authentication
AuthMysqlUserTable http_auth
AuthMySQLEnable on
require valid-user


...
..


Examples:
  • require valid-user: Allow all users if authentication (password) is correct.
  • require user greg phil bob: Allow only greg phil bob to login.
  • require group accounting: Allow only users in group "accounting" to authenticate.

Directives:

Directive Description
AuthMySQLEnable On If 'Off', MySQL authentication will pass on the authentication job to the other authentication modules i.e password files.
AuthMySQLHost host_name Name of MySQL Database hosr. i.e. 'localhost'
AuthMySQLPort TCP_Port_number Port number of MySQL Database. Default: 3306
AuthMySQLDB database_name Name of MySQL Database.
AuthMySQLUser user_id MySQL Database login id.
AuthMySQLPassword user_password MySQL Database login password. Plain text.
AuthMySQLUserTable user_table_name Name of MySQL Databse table in the database which holds the user name and passwords.
AuthMySQLGroupTable group_table_name Databse table holding group info.
AuthMySQLNameField user_field_name If not using default field name 'user_name', then specify. Not case sensitive id CHAR or VARCHAR.
AuthMySQLPasswordField password_field_name If not using default field name 'user_passwd', then specify. Passwords are case sensitive.
AuthMySQLGroupField group_field_name If not using default field name 'groups', then specify.
AuthMySQLNoPasswd Off Off: Passwords can be null ('').
On: password must be specified.
AuthMySQLPwEncryption none Options: none, crypt, scrambled (MySQL password encryption), md5, aes, sha.
AuthMySQLSaltField salt_string mysql_column_name Salt field to be used for crypt and aes.
AuthMySQLAuthoritative on Authenticate using other authentication modules after the user is successfully authenticated by the MySQL auth module. Default on: request is not passed on.
AuthMySQLKeepAlive Off Off: Close the MySQL link after each authentication request.

MySQL Admin:

  • mysqladmin -h localhost -u root -ppassword create http_auth
  • mysql -h localhost -u root -ppassword
  • mysql> use http_auth
  • mysql> create table mysql_auth ( user_name char(30) NOT NULL,user_passwd char(60) NOT NULL,user_group char(25),primary key (user_name) );
  • mysql> insert into mysql_auth values('Fred','supersecret','worker');

Login URL Tricks:

Here is a trick to incorporate a login and password into a URL. Typicall one would attempt to enter the password protected area of the web site and the user would be confronted with a login dialog box into which one would enter the user id and password. Another option is to enter a URL with the login and password embedded.

    http://login-id:password@UrlOfDomain.com/protectedPath/WebPage.html

Apache Web Log-in Authentication (Password File) Part II

Flexible password protection by group access permissions:

This example differs from the previous example in that it allows for greater control and flexibility by using groups.

Password files:

1. Create a file .htgroup in that directory that contains the groupname and list of users:

member-users: user1 user2 user3 ... etc


Where member-users is the name of the group.

2. Modify .htaccess in the membersonly directory so it looks something like:

AuthName "Add your login message here."
AuthType Basic
AuthUserFile /home/domain/public_html/membersonly/.htpasswd
AuthGroupFile /home/domain/public_html/membersonly/.htgroup
require group member-users


3. Create the password file .htpasswd using the program htpasswd for each user as above. You don't need the -c option if you are using the same .htpasswd file. (-c is only to create a new file)

htpasswd -c /home/domain/public_html/membersonly/.htpasswd user1
htpasswd /home/domain/public_html/membersonly/.htpasswd user2


Restrict access based on domain or IP address:

Allow specified domain to access site:

Order deny, allow
Deny from all
Allow from allowable-domain.com
Allow from XXX.XXX.XXX
Deny from bad-domain.com

Specify first three (or one, or two, ...) octets of IP address defining allowable domain.


Placing Authentication directives in httpd.conf exclusively instead of using .htaccess:

The purpose of using the "distributed configuration file" .htaccess is so that users may control authentication. It can also be set in the Apache configuration file httpd.conf WITHOUT using the .htaccess file. This can improve server performance as the server will not have to look for the .htaccess file in each subdirectory.

File: httpd.conf (portion)

..
...


AllowOverride AuthConfig
AuthName "Add your login message here."
AuthType Basic
AuthUserFile /home/domain/public_html/membersonly/.htpasswd
AuthGroupFile /dev/null
require user name-of-user


...
..


Sunday, February 17, 2008

Apache Web Log-in Authentication (Password File) Part I

Apache authentication can be configured to require web site visitors to login with a user id and password. This is different than adding a login form on a web page and creating your own authentication. This tutorial describes the various methods available for authentication with Apache and its' configuration. Login protection is applied to the web pages stored in a directory. The login dialog box which requests the user id and password is provided by the web browser at the request of Apache. Apache allows the configuration to be entered in its' configuration files (i.e. main configuration file /etc/httpd/conf/httpd.conf, supplementary configuration files /etc/httpd/conf.d/component.conf or in a file which resides within the directory to be password protected.

Apache password file authentication:

Directory protection using .htaccess and .htpasswd

This tutorial applies to Apache based web servers. It requires:

1. Editing the server configuration file (httpd.conf) to enable/allow a directory structure on the server to be password protected. Basically the default access permission statement need modification.
2. The creation and addition of two files specifying the actual logins and passwords. (.htaccess and .htpasswd)

Use this sparingly because Apache will have to check all directories and subdirectories specified in the configuration file for the existence of the .htaccess file adding to a servers latency.

When trying to access a file in a protected directory, the user will be presented with a window (dialog box) requesting a username and password. This protection applies to all sub-directories. Other .htaccess files in sub directories may respecify access rules.

Apache authentication uses the modules mod_auth and mod_access.

Apache configuration file:

File: /etc/httpd/conf/httpd.conf (older systems used access.conf)

Default: This disables the processing of .htaccess files for the system.


AllowOverride None


or for a specified directory:


AllowOverride None


Change to and/or specify directory to protect:


AllowOverride All


OR


AllowOverride AuthConfig


AllowOverride parameters: AuthConfig FileInfo Indexes Limits Options

The name of the "distributed" and user controlled configuration file .htaccess is defined with the directive: (default shown)

AccessFileName .htaccess


Password protection by a single login:

Password files:

1. Create the directory you want to password protect (example: membersonly)
2. Create a file /home/domain/public_html/membersonly/.htaccess in that director that looks something like this:

AuthName "Add your login message here."
AuthType Basic
AuthUserFile /home/domain/public_html/membersonly/.htpasswd
AuthGroupFile /dev/null
require user name-of-user

In this case the "name-of-user" is the login name you wish to use for accessing the web site.

The literature is full of examples of the next method but I never got it to work.

One can use Apache directives to specify access and restriction:

AuthName "Add your login message here."
AuthType Basic
AuthUserFile /home/domain/public_html/membersonly/.htpasswd
AuthGroupFile /dev/null

require user name-of-user


Also see: List of Apache directives. If an incorrect directive is used in the .htaccess file it will result in a server error. Check your log files: /var/log/httpd/error_log.
The name of the access file .htaccess is specified by the httpd.conf directive AccessFileName.

3. Create the password file /home/domain/public_html/membersonly/.htpasswd using the program htpasswd:

htpasswd -c .htpasswd name-of-user

Man page: htpasswd

Example file: .htpasswd

user1:KgvCSeExtS4kM
USER1:KgvCSeExtS4kM
User1:KgvCSeExtS4kM

Tuesday, February 12, 2008

Bind a multiple IP address on a single NIC card How-to

This how-to demonstrates how to bind multiple IP addresses to a single NIC. You can run a service under a specific IP while having another service under a different one (for example, have DNS on one and SMTP on another), or create a private LAN using a local IP and have the alias hold your Internet IP (such as NAT) by using multiple IP's.

The network scripts are located in /etc/sysconfig/network-scripts/. Go into that directory.

#cd /etc/sysconfig/network-scripts/






The file we're interested in is ifcfg-eth0, the interface for the Ethernet device. If you have a second Ethernet device then there would be an ifcfg-eth1 file and so on for each adapter you have installed. We need to create an alias file while ifcfg-eth0 maintains the primary IP address.

This is how we will setup the aliases to bind the IP addresses.

Adapter IP Address Type
-----------------------------------
eth0 192.168.2.1 Primary
eth0:0 192.168.2.2 Alias 1
eth0:1 192.168.2.3 Alias 2

The :X (where X is the interface number) is appended to the interface file name to create the alias. For each alias you create you assign a number sequentially. For this example we will create aliases for eth0. Make a copy of ifcfg-eth0 for the three aliases.

cp ifcfg-eth0 ifcfg-eth0:0
cp ifcfg-eth0 ifcfg-eth0:1


Take a look inside ifcfg-eth0 and review the contents.

#more ifcfg-eth0
DEVICE=eth0
ONBOOT=yes
BOOTPROTO=none
IPADDR=192.168.2.1
NETMASK=255.255.255.0
GATEWAY=192.168.2.254
TYPE=Ethernet
USERCTL=no
PEERDNS=yes
IPV6INIT=no

We're interested in only two lines (DEVICE and IPADDR). We'll rename the device in each file to its corresponding interface alias and change the IP's. We'll start with ifcfg-eth0:0. Open ifcfg-eth0:0 in vi and change the two lines so they have the new interface and IP address.

#vi ifcfg-eth0:0

DEVICE=eth0:0
IPADDR=192.168.2.2

Save ifcfg-eth0:0 and edit the other alias files (ifcfg-eth0:1) so they have the new interfaces and IP addresses set (follow the table from above). Once you save all your changes you can restart the network for the changes to take effect.

#service network restart

To verify all the aliases are up and running you can run ifconfig (depending on how many new IP's you set up, you can use ifconfig more to pause the output).

#ifconfig

You can also test the IP's by pinging them from a different machine. If everything is working then there should be a response back.

c:\>ping 192.168.2.2
c:\>ping 192.168.2.3

Wednesday, February 6, 2008

Unix/Linux Command Reference

File Commands

ls
– directory listing
ls -al – formatted listing with hidden files
cd dir - change directory to dir
cd – change to home
pwd – show current directory
mkdir dir – create a directory dir
rm file – delete file
rm -r dir – delete directory dir
rm -f file – force remove file
rm -rf dir – force remove directory dir *
cp file1 file2 – copy file1 to file2
cp -r dir1 dir2 – copy dir1 to dir2; create dir2 if it doesn't exist
mv file1 file2 – rename or move file1 to file2
if file2 is an existing directory, moves file1 into directory file2
ln -s file link – create symbolic link link to file
touch file – create or update file
cat > file – places standard input into file
more file – output the contents of file
head file – output the first 10 lines of file
tail file – output the last 10 lines of file
tail -f file – output the contents of file as it grows, starting with the last 10 lines


Process Management

ps
– display your currently active processes
top – display all running processes
kill pid – kill process id pid
killall proc – kill all processes named proc *
bg – lists stopped or background jobs; resume a stopped job in the background
fg – brings the most recent job to foreground
fg n – brings job n to the foreground

File Permissions

chmod octal file – change the permissions of file to octal, which can be found
separately for user, group, and world by adding:
● 4 – read (r)
● 2 – write (w)
● 1 – execute (x)
Examples:
chmod 777 – read, write, execute for all
chmod 755 – rwx for owner, rx for group and world
For more options, see man chmod.

SSH

ssh user@host – connect to host as user
ssh -p port user@host – connect to host on port port as user
ssh-copy-id user@host – add your key to host for user to enable a keyed or
passwordless login

Searching

grep pattern files – search for pattern in files
grep -r pattern dir – search recursively for pattern in dir
command grep pattern – search for pattern in the output of command
locate file – find all instances of file


System Info

date
– show the current date and time
cal – show this month's calendar
uptime – show current uptime
w – display who is online
whoami – who you are logged in as
finger user – display information about user
uname -a – show kernel information
cat /proc/cpuinfo – cpu information
cat /proc/meminfo – memory information
man command – show the manual for command
df – show disk usage
du – show directory space usage
free – show memory and swap usage
whereis app – show possible locations of app
which app – show which app will be run by default

Compression

tar cf file.tar files – create a tar named file.tar containing files
tar xf file.tar – extract the files from file.tar
tar czf file.tar.gz files – create a tar with Gzip compression
tar xzf file.tar.gz – extract a tar using Gzip
tar cjf file.tar.bz2 – create a tar with Bzip2 compression
tar xjf file.tar.bz2 – extract a tar using Bzip2
gzip file – compresses file and renames it to file.gz
gzip -d file.gz – decompresses file.gz back to file


Network

ping host
– ping host and output results
whois domain – get whois information for domain
dig domain – get DNS information for domain
dig -x host – reverse lookup host
wget file – download file
wget -c file – continue a stopped download

Installation

Install from source:
./configure
make
make install
dpkg -i pkg.deb – install a package (Debian)
rpm -Uvh pkg.rpm – install a package (RPM)


Shortcuts

Ctrl+C – halts the current command
Ctrl+Z – stops the current command, resume with
fg in the foreground or bg in the background
Ctrl+D – log out of current session, similar to exit
Ctrl+W – erases one word in the current line
Ctrl+U – erases the whole line
Ctrl+R – type to bring up a recent command
!! - repeats the last command
exit – log out of current session

Monday, February 4, 2008

Treeview command Linux How-to

Linux command:

ls -R | grep "DIR" | sed -e 's/"DIR"//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'

where DIR is the Directory Name

To see all the directory inside a folder in a tree view...


Linux Disk Quota How-to

"LINUX DISK QUOTA HOW-TO"

yum install quota

vi /etc/fstab
-add the following lines: ,usrquota,grpquota 1,2

touch /aquota.user /aquota.group
chmod 600 /aquota.*
mount -o remount /
quotacheck -avugm
quotaon -avug

To edit quota: edquota "user"

To copy quota: edquota -p "pattern" "user"

To get quota report: repquota "user" or "dir"

MRTG on Linux How-to

How to MRTG on Linux

Step # 1 : Make sure snmp server installed

Please note that snmpd configuration does not require using mrtg with remote network devices such as Routers and switches. If you just want mrtg graphs for router or switch then please refer to step # 4 (as all these devices comes preconfigured with snmpd software).

Run rpm commands query option to find out snmp server installed or not:

# rpm -qa | grep snmp

If snmp installed then please refer step # 2; otherwise snmp server and utils were not present and your need to install them using following steps (login as a root user):

(a) Visit rpmfind.net to get snmp server and utilities rpms. If you are fedora user then use yum command as follows to install it:

# yum install net-snmp-utils net-snmp

(b) If you are RHEL subscriber then use up2date command as follows to install:

#up2date -v -i net-snmp-utils net-snmp
 
 

Step # 2 : Determine if snmp server is running or not

Run 'ps' command to see if snmp server is running or not:

# ps -aux | grep snmp

Output:

root   5512  0.0  2.3  5872 3012 pts/0    S    22:04   0:00 /usr/sbin/snmpd

Alternatively, you can try any of the following two commands as well:

# lsof -i :199

Output:

COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME

snmpd
5512 root 4u IPv4 34432 TCP *:smux (LISTEN)

OR try out netstat command:

# netstat -natv | grep ':199'

Output:

tcp        0      0 0.0.0.0:199             0.0.0.0:*               LISTEN

If you found service is running or listing on port 199 then please see step #3; otherwise start service using following command:

# service snmpd start

Make sure snmpd service starts automatically, when linux comes us (add snmpd service):

# chkconfig --add snmpd
 

Step # 3 : Make sure snmp server configured properly

Run snmpwalk utility to request for tree of information about network entity. In simple words query snmp server for your IP address (assigned to eth0, eth1, lo etc):

# snmpwalk -v 1 -c public localhost IP-MIB::ipAdEntIfIndex
ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.127.0.0.1 = 1
ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.192.168.0.3 = 2

If you can see your IP address then please proceed to step 4; else it is a time to configure snmp server as follows (by default RHEL and RH 8/9 are not configured for snmp server for security reason):

Configure SNMP

(1) Edit file /etc/snmp/snmpd.conf using text editor:

# vi /etc/snmp/snmpd.conf

Change/Modify line(s) as follows:

Find following Line:

com2sec notConfigUser  default       public

Replace with (make sure you replace 192.168.0.0/24 replace with your network IPs) following lines:

com2sec local     localhost           public
com2sec mynetwork 192.168.0.0/24      public

Scroll down bit and change:

Find Lines:

group   notConfigGroup v1           notConfigUser
group   notConfigGroup v2c           notConfigUser

Replace with:

group MyRWGroup v1         local
group MyRWGroup v2c        local
group MyRWGroup usm        local
group MyROGroup v1         mynetwork
group MyROGroup v2c        mynetwork
group MyROGroup usm        mynetwork

Again scroll down bit and locate following line:

Find line:

view    systemview     included      system

Replace with:

view all    included  .1                               80

Again scroll down bit and change:

Find line:

access  notConfigGroup ""      any       noauth    exact  systemview none none

Replace with:

access MyROGroup ""      any       noauth    exact  all    none   none

access MyRWGroup ""
any noauth exact all all none

Scroll down bit and change:

Find lines:

syslocation Unknown (edit /etc/snmp/snmpd.conf)
syscontact Root  (configure /etc/snmp/snmp.local.conf)

Replace with (make sure you supply appropriate values):

syslocation Linux (RH3_UP2), Home Linux Router.

syscontact Vivek G Gite

For your convenient, here is my /etc/snmp/snmpd.conf file. Feel free to use this file. Make sure you make backup of your existing file if you use this file as it is.

Start your snmp server and test it:

(a) Make sure when linux comes up snmpd always starts:

 # chkconfig snmpd on

(b) Make sure service start whenever Linux comes up (after reboot):

 # service snmpd start

(c) Finally test your snmp server:

 # snmpwalk -v 1 -c public localhost IP-MIB::ipAdEntIfIndex

Step # 4 : Install mrtg if not installed

Mrtg software may install during initial installation; you can verify if MRTG installed or not with following RPM command:

rpm -qa | grep mrtg

If mrtg already installed please see step # 5; else use rpmfind.net to find MRTG rpm or up2date command to install MRTG software:

# up2date -v -i mrtg

Fedora Linux user can use yum command as follows to install MRTG:

# yum install mrtg
 

Step # 5 : Commands to Configure mrtg

(a) Create document root to store mrtg graphs/html pages:

# mkdir -p /var/www/html/mymrtg/

(b) Run any one of the following cfgmaker command to create mrtg configuration file:

#cfgmaker --global 'WorkDir: /var/www/html/mymrtg' --output /etc/mrtg/mymrtg.cfg public@localhost

OR (make sure your FQDN resolves, in following example i'm using rh9.test.com which is my router FQDN address)

# cfgmaker --global 'WorkDir: /var/www/html/mymrtg' --output /etc/mrtg/mymrtg1.cfg public@rh9.test.com

(c) Create default index page for your MRTG configuration:

# indexmaker --output=/var/www/html/mymrtg/index.html /etc/mrtg/mymrtg.cfg

(d) Copy all tiny png files to your mrtg path:

# cp -av /var/www/html/mrtg/*.png /var/www/html/mymrtg/

Step # 6 First test run of mrtg

(a) Run mrtg command from command line with your configuration file:

# mrtg /etc/mrtg/mymrtg.cfg

Note: You may get few warning message for first time; ignore them.

(b) Fire your favorite web browser (like FireFox :D ) and type url http://www.your.com/mymrtg/ or http://your-ip/mymrtg/

Step # 7 Create crontab entry so that mrtg graph / images get generated every 5 minutes

(a) Login as a root user or login as a mrtg user and type following command:

# crontab -e

(b) Add mrtg cron job entry to configuration file (append following line to it):

*/5 * * * * /usr/bin/mrtg /etc/mrtg/mymrtg.cfg --logging /var/log/mrtg.log

Save file and you are done with MRTG config issues :)

Step # 8 Block ports 161 & 162 at firewall

You do not want to give access to everyone to your snmp server for security reasons. SNMP server uses UDP 161, 162 ports for communication. Use Linux IPTABLES firewall to restrict access to SNMP server

(a) Allow outgoing SNMP server request from your Linux computer. This is useful when you query remote host/router (replace SERVER IO with your real IP):

SERVER="xxx.xxx.xxx.xxx"
iptables -A OUTPUT -p udp -s $SERVER --sport 1024:65535 -d 0/0 --dport 161:162 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p udp -s 0/0 --sport 161:162 -d $SERVER --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

(b )Allow incoming SNMP client request via iptables. This is useful when you wish to accept queries for rest of the world (replace SERVER IP with your real IP):

SERVER="xxx.xxx.xxx.xxx"
iptables -A INPUT -p udp -s 0/0 --sport 1024:65535 -d $SERVER --dport 161:162 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p udp -s $SERVER --sport 161:162 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

Pleae note that above two are just SNMP specific iptables rules. Please consult iptables(8) man page for complete information on iptables

Step # 9 Optional: Protect your MRTG graphs/html pages with password protected directory

Once again, you would like to restrict access to your MRTG reports. This can easily accomplished with Apache webserver's .htaccess file. If you are on webhosting server with control panel (such as ensim or plesk) then you can use control panel itself to create password-protected directory.

Below is process outlined to protect graphs using apache's .htaccess file and htpasswd command:

Step # 1: Create .htaccess file in /var/www/html/mymrtg/ directory (add text as follows):

vi /var/www/html/mymrtg/.htaccess

Add following text to file:

AuthName "MRTG Graphs/Html restricted access"
AuthType Basic
AuthUserFile /var/members/.htpasswd
require user mrtgadmin

Step # 2: Create a user and password name (-c assumes first time you are using .htpasswd file):

# htpasswd -c /var/members/.htpasswd mrtgadmin