Showing posts with label Linux How-to's. Show all posts
Showing posts with label Linux How-to's. Show all posts

Thursday, April 16, 2009

Adding Repositories on CentOS

Adding DAG Repo:

#cd /etc/yum.repos.d
#vi dag.repo


Fill-in the following lines and save it.

[dag]
name=Dag RPM Repository for Red Hat Enterprise Linux baseurl=http://apt.sw.be/redhat/el$releasever/en/$basearch/dag
gpgcheck=1
enabled=1


Issue this ;

# rpm –import http://dag.wieers.com/rpm/packages/RPM-GPG-KEY.dag.txt


Try to install using yum.

Neat huh...

Tuesday, June 10, 2008

Install XWindows and Gnome on CentOS with YUM

To install XWindows and Gnome on CentOS using YUM;

# yum groupinstall “X Window System” “GNOME Desktop Environment”

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

Tuesday, February 19, 2008

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

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