Thursday, November 22, 2007

Tunneling TCP Services over HTTP(S)

HTTP Tunnel Definition
HTTP Tunneling is a technique by which communications performed using various network
protocols are encapsulated using the HTTP protocol, the network protocols in question usually belonging to the TCP/IP family of protocols. The HTTP protocol therefore acts as a wrapper for a covert channel that the network protocol being tunneled uses to communicate.The HTTP stream with its covert channel is termed a HTTP Tunnel.

HTTP Tunnel software consists of client-server HTTP Tunneling applications that integrate
with existing application software, permitting them to be used in conditions of restricted network connectivity including firewalled networks, networks behind proxy servers, and NATs.

An HTTP Tunnel is used most often as a means for communication from network locations with
restricted connectivity – most often behind NATs, firewalls, or proxy servers, and most often with applications that lack native support for communication in such conditions of restricted connectivity. Restricted connectivity in the form of blocked TCP/IP ports, blocking traffic initiated from outside the network, or blocking of all network protocols except a few is a commonly used method to lock down a network to secure it against internal and external threats.

This document explains how to set up an Apache server and SSH client to allow tunneling SSH over HTTP(S) as an example. This can be useful on restricted networks that either firewall everything except HTTP traffic (tcp/80,tcp/443) or require users to use a local (HTTP) proxy.

In this example our LAN is 192.168.0.0/24
The client 192.168.0.CC is behind the firewall.)
Gateway(Firewall) is 192.168.0.GW
HTTP Tunnel Server is 192.168.0.TT

Here SSH Service is tunneled as an example.You can tunnel telnet or any other TCP/IP
Service/PORT supported by Apache Proxy Module.

Apache Compilation in the HTTP Tunnel Server
So as to use Apache Server as a Tunnel for TCP/IP or other protocols,it should be
configured to run in Proxy Mode.
Run httpd -l to check whether the proxy modules are loaded or not.
If not load it if available under the Apache MODULES directory using the LoadModule
Directive.
eg : LoadModule mod_proxy modules/mod_proxy.so

Or you should recompile Apache to include the mod_proxy support
[root@tunnelserver] # ./configure --enable-proxy --enable-proxy-connect --enable-proxy-http --enable-proxy-ajp --enable-proxy-balancer --enable-proxy-ftp
[root@tunnelserver] # make
[root@tunnelserver] # make install

Then include the following in httpd.conf (Simple config .No security measures followed)
Listen 80
Listen 443

Order deny,allow
Deny from all
Allow from all

ProxyRequests On
AllowCONNECT 22
# You can specify a number of ports here
ProxyVia on


Now Apache is ready to act as a Tunnel listening on ports 80 and 443
Do a service restart.

Verification with SSH Tunnel Client software- ProxyTunnel
Download Proxytunnel from
SOURCEFORGE
Install it in the Client machine(s) behind the firewall,from which you want SSH through the HTTP Tunnel Server. Here I have a client 192.168.0.CC
[root@client]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
0.0.0.0 192.168.0.GW 0.0.0.0 UG 0 0 0 eth0

SSH to PUB.LIC.IP.ADD over port 22 is blocked by firewall in the Gateway Server

See the output of iptables -L of Gateway
[root@GATEWAY ~]# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
DROP tcp -- 192.168.0.CC PUB.LIC.IP.ADD.some-domain.com tcp dpt:22
Chain OUTPUT (policy ACCEPT)
target prot opt source destination


And lets try a Bare SSH from the client to a Remote Server outside the LAN
[root@client]# ssh PUB.LIC.IP.ADD -l root -p 22
ssh: connect to host PUB.LIC.IP.ADD port 22: Connection timed out


So it is clear that SSH to PUB.LIC.IP.ADD is filtered

Installed ProxyTunnel Software
[root@client src]# tar xzf proxytunnel-1.6.3.tgz
[root@client src]# cd proxytunnel-1.6.3
[root@client proxytunnel-1.6.3]#
# make
# make install


Then configure SSH to use proxytunnel for connections
Edit ~/.ssh/config and include the following
Host *
ProxyCommand proxytunnel -v -p 192.168.0.TT:80 -d %h:%p
ServerAliveInterval 30

Here Host Specifies the Destination * for all
-d %h:%d will be expanded on the Run to -d Destination_IP:Port

Now try SSH
[root@client]# ssh PUB.LIC.IP.ADD -l root -p 22
192.168.0.TT is 192.168.0.TT
Connected to 192.168.0.TT:80
Tunneling to PUB.LIC.IP.ADD:22 (destination)
Connect string sent to Proxy: 'CONNECT PUB.LIC.IP.ADD:22 HTTP/1.0
Proxy-Connection: Keep-Alive
'
DEBUG: recv: 'HTTP/1.0 200 Connection Established
'DEBUG: recv: 'Proxy-agent: Apache/2.2.6 (Unix)
'DEBUG: recv: '
'Starting tunnel
root@PUB.LIC.IP.ADD's password:
Last login: Fri Nov 23 14:22:48 2007 from some-domain.com
[root@RemoteServer root]#


Now replace
ProxyCommand proxytunnel -v -p 192.168.0.TT:80 -d %h:%p
with
ProxyCommand proxytunnel -v -p 192.168.0.TT:443 -d %h:%p
in ~/.ssh/config if you want to tunnel through Port 443 of HTTP Tunnel Server.

Then try SSH
[root@client]# ssh PUB.LIC.IP.ADD -l root -p 22
192.168.0.TT is 192.168.0.TT
Connected to 192.168.0.TT:443
Tunneling to PUB.LIC.IP.ADD:22 (destination)
Connect string sent to Proxy: 'CONNECT PUB.LIC.IP.ADD:22 HTTP/1.0
Proxy-Connection: Keep-Alive
'
DEBUG: recv: 'HTTP/1.0 200 Connection Established
'DEBUG: recv: 'Proxy-agent: Apache/2.2.6 (Unix)
'DEBUG: recv: '
'Starting tunnel
root@PUB.LIC.IP.ADD's password:
Last login: Fri Nov 23 14:26:44 2007 from some-domain.com
[root@RemoteServer root]#


References
APACHE Project Page
APACHE Project Page
Wikipedia
Dag Wieers

Friday, November 16, 2007

Bash Script for FTP

#!/bin/bash
USER=myusername
PASS=mypasswd
FTPSERVER=192.168.0.X
ftp -i -n $FTPSERVER << EOF
user $USER $PASS
mkdir test
cd test
put myfile
bye
>>

But FTP will allow transfer of files only,not the directory tree.
If you want to transfer the Directory structure through FTP you can use LFTP or similar FTP clients. A variety of GUI Based clients are available

LFTP

lftp has builtin mirror which can download or update a whole directory tree. There is also reverse mirror (mirror -R) which uploads or updates a directory tree on server. Mirror can also synchronize directories between two remote servers, using FXP if available.
It can be downloaded from http://lftp.yar.ru/get.html or http://rpm.pbone.net

Here is a sample BASH Script to automate the FTP Transfer

#!/bin/bash
USER=ftpuser
PASS=ftppasswd
FTPSERVER=192.168.0.X
LOCALDIR=/home/USER/LOCAL
REMDIR=REMOTE
lftp -u $USER,$PASS $FTPSERVER << EOF
mirror -R $LOCALDIR $REMDIR
quit
>>



Now see how to play with the data we have to upload.That is you can decide whatever folders or files have to be uploaded to the FTP Server.I use two scripts fro this.But we can consolidate it into a single one.

Script 1 - ftp_initiate.sh
#!/bin/sh
LIST=/root/scripts/datalist.txt
#echo Where is the Data List
#read LIST

count=`wc -l $LIST | cut -f1 -d" "`
n=1

while [ $n -le $count ]
do
{
data=`head -$n $LIST | tail -1`
sh /root/scripts/ftp_upload.sh $data
n=$[$n +1]
}
done

Script 2 - ftp_upload.sh
#!/bin/sh
USERNAME='username'
PASSWORD='password'
SERVER='192.168.0.X'

# local directory to pickup
SOURCE=/some/where/in/your/home

# remote server directory to upload backup
BACKUPDIR=/backup/folder/in/FTP/Server

data=$SOURCE/$1
lftp -u $USERNAME,$PASSWORD $SERVER << EOF
mirror -R $data $BACKUPDIR/
quit
>>
Here the if a deletion takes place at the SOURCE it won't affect the DESTINATION .Means the deleted contents never get deleted from the DESTINATION.
You can optionally delete those files in the DESTINATION also by specifying the --delete switch of the MIRROR command as below
mirror -R -e --delete $LOCALDIR $REMDIR
In some environment with Firewalls,Mix of OSs and FTP Services a few problems may arise in connectivity like SSL Communication,Proxy,etc
Here I have faced an issue with the SSL .By default SSL is enabled in LFTP
After connecting to the FTP Server I just tried to List the contents which turned into errors as below
lftp ftpuser@192.168.0.1:~> ls
'ls' at 0 [FEAT TLS negotiaition..]
'ls' at 0 [ Delaying before Reconnect 29..]
'ls' at 0 [Not Connected..]
lftp ftpuser@192.168.0.1:~>
It repeats
What I did was just disabled SSL
set -a will list all the variables and values for the FTP session
lftp ftpuser@192.168.0.1:~> set -a
SSL was enabled . I turned it to disabled state
lftp ftpuser@192.168.0.1:~> set ftp:ssl-allow no

Thereafter it worked
lftp ftpuser@192.168.0.1:~>ls
12-10-07 11:04PM DIR dir1
12-10-07 11:10PM DIR tesfile.txt
12-07-07 09:48AM DIR TestDir
12-09-07 11:05PM DIR mydata


The same can be applied to the BASH Script also
#!/bin/bash
USER=ftpuser
PASS=ftppasswd
FTPSERVER=192.168.0.X
LOCALDIR=/home/USER/LOCAL
REMDIR=REMOTE
lftp -u $USER,$PASS $FTPSERVER << EOF
set ftp:ssl-allow no
mirror -R $LOCALDIR $REMDIR
quit
>>
To know more about FTP-SSL See RFC2228
FXP Mirroring

server A -> server B
When mirroring is done between two remote servers the File eXchange Protocol is used. Obviously, both servers must support this protocol for this operation to succeed.
Technically, FXP is not a protocol but an extension of FTP. It is used to transfer data from one remote server to another without routing this data through the client. The client sends and receives control data to make everything work.
In an FXP session, the client maintains a standard FTP connection to both servers, and can direct either server to connect to the other to initiate a data transfer. The advantage of using FXP (server A -> server B) instead of (twice using) FTP (server A -> client -> server B) is evident when both servers are high-bandwidth but the client is low-bandwidth.
Enabling FXP support, however, can make a server vulnerable to a denial-of-service attack, known as the FTP bounce attack
In such a scenario, the "client" is a compromised machine that bombards server B.FXP is also frequently used for warez
trafficking.

Due to these considerations, FXP is often disabled by default on FTP servers.

Reference
lftp Man Page
PapaMike

Follow ups
Cert.org
LinuxForums

How to disable directory browsing in Apache

One of the "must do's" on setting a secure apache webserver environment is to disable directory browsing. As a default Apache will be compiled with this option enabled, but its always a good idea to get rid of this setting unless its really necessary.

If you are on an RPM installation of Apache you will find the apache configuration file probably here:

/etc/httpd/conf/httpd.conf

If you are using apache from the source tar balls probably you will find the configuration file here:

/usr/local/apache/conf/httpd.conf

Edit the httpd.conf file and scroll until you find a line like this:

Options All Indexes FollowSymLinks MultiViews

To disable directory browsing carefully remove the line that says: Indexes and leave the line like this:

Options All FollowSymLinks MultiViews

Restart your apache webserver and thats it

Reboot Linux box after a kernel panic

If you want the server to get rebooted automatically after kernel hit by a pain error message, try adding panic=N to /etc/sysctl.conf file.

It specify kernel behavior on panic. By default, the kernel will not reboot after a panic, but this option will cause a kernel reboot after N seconds. For example following boot parameter will force to reboot Linux after 10 seconds.
Open /etc/sysctl.conf file

# vi /etc/sysctl.conf
When kernel panic’s, reboot after 10 second delay

kernel.panic = 10

Save the file.

You can do this on the fly also,by editing the GRUB
While Grub loads edit and append the following to the KERNEL line
panic=10
Alternatively, you may want to enable and use magic system request keys (SysRq).

Linux kernel includes magic system request keys. It was originally developed for kernel hackers. However, you can use this hack to reboot, shutdown or halt computer safely (remember safe reboot/shutdown == flush filesystem buffers and unmount file system and then reboot so that data loss can be avoided).

This is quite useful when Linux based system is not available after boot or after a X server crashed ( svgalib program crashes) or no display on screen. Sysrq key combo forces the kernel to respond it regardless of whatever else it is doing, unless it is completely locked up (dead).

Using further extension to iptables called ipt_sysrq (new iptables target), which allows you to do the same as the magic sysrq key on a keyboard does, but over the network. So if your network server is not responding you can still reboot it. Please note that Magic SysRq support need to be compiled in your kernel. You need to say “yes” to ‘Magic SysRq key (CONFIG_MAGIC_SYSRQ)’ when configuring the kernel. I’m assuming that you have Magic SysRq key’ support is compiled in your kernel.

Enable sysrq keys

By default it is not enabled on many Linux distributions. Add or modify following line (as soon as new Linux system installed) /etc/systctl.conf:
kernel.sysrq=1

Save and close the file and reboot system to take effect
How do I use the magic SysRq keys in emergency?

You need to use following key combination in order to reboot/halt/sync file system etc:
ALT+SysRq+COMMAND-KEY

The ‘SysRq’ key is also known as the ‘Print Screen’ key. COMMAND-KEY can be any one of the following (all keys need to hit simultaneously) :
‘b’ : Will immediately reboot the system without syncing or unmounting your disks.
‘o’ : Will shutdown your system off (if configured and supported).
’s’: Will attempt to sync all mounted filesystems.
‘u’ : Will attempt to remount all mounted filesystems read-only.
‘e’ : Send a SIGTERM to all processes, except for init.
‘h’: Show help, indeed this the one you need to remember.

So whey you need to tell your Linux computer to reboot or when your X server is crashed or you don’t see anything going across the screen then just press:

ALT+SysRQ+s : (Press and hold down ALT, then SysRQ (Print Screen) key and press ’s’) -Will try to syn all mounted system

ALT+SysRQ+r : (Press and hold down ALT, then SysRQ (Print Screen) key and press ‘r’) -Will reboot the system.

If you wish to shutdown the system instead of reboot then press following key combination:
ALT+SysRQ+o

ipt_sysrq is a new iptables target that allows you to do the same as the magic sysrq key on a keyboard does, but over the network. Sometimes a remote server hangs and only responds to icmp echo request (ping). Every administrator of such machine is very unhappy because (s)he must go there and press the reset button. It takes a long time and it’s inconvenient. So use the Network Magic SysRq and you will be able to do more than just pressing a reset button. You can remotely sync disks, remount them read-only, then do a reboot. And everything comfortably and only in a few seconds.

IP Tables network magic SysRq function 0.4



What is it?

ipt_sysrq is a new iptables target that allows you to do the same as the magic sysrq key on a keyboard does, but over the network.

Why to use the remote sysrq?

Sometimes a remote server hangs and only responds to icmp echo request (ping). Every administrator of such machine is very unhappy because (s)he must go there and press the reset button. It takes a long time and it's inconvenient. So here is a solution. Use the Network Magic SysRq and you will be able to do more than just pressing a reset button. You can remotely sync disks, remount them read-only, then do a reboot. And everything comfortably and only in a few seconds. ;-)

Is it secure?


That depends. ;-) Let me explain: You can restrict who can do this by setting the iptables firewall. But unfortunately, for simplicity, the Network Magic SysRq is based on a single packet request. This packet is encrypted and password protected, but if somebody can sniff it (s)he will be able to repeat (but not to change) the query (so-called replay attack). The query is also protected by a timestamp. When the packet is generated, it is stamped by current date and time. Then on the server side that stamp is compared with the current time of the server and if it is within the tolerance the request is accepted. Together with some other information, the timestamp is protected by SHA1 hash. This means that the potential attacker has a limited time to repeat the sniffed packet. If anybody requires a better security than this, some secure encrypted tunnel can be used. (not depending on userspace, of course! ;-))

How to install it?

Just type 'make'.

When everything is compiled type 'make install' as root and after that run 'depmod -a'. Now you can load the kernel module by the command 'modprobe ipt_SYSRQ'.

You would also like to configure the server password and the tolerance. This can be set when installing the module into a kernel, by specifying the module parameters 'passwd' for password and 'tolerance' for tolerance in seconds. The default values are passwd="" and tolerance=43200.

Example:
modprobe ipt_SYSRQ passwd="my_very_secret_password" tolerance=3600

Module options can also be specified in file /etc/modules.conf.

Example:
options ipt_SYSRQ passwd="my_very_secret_password" tolerance=3600

What to do on a server?

After the module is loaded you are able to deploy it using the iptables command.

Some examples of usage:

iptables -I INPUT -p udp --dport 9 -j SYSRQ
or
iptables -I INPUT -i eth1 -s 192.168.1.2 -p udp --dport 9 -j SYSRQ

Note that UDP port 9 is used. This is the default port for send_sysrq program, which shouldn't do any harm, as it defaults to 'discard' service.


What to do on the remote machine?


Copy the executable binary 'send_sysrq' to the remote (client) machine. Alternatively, you can compile ipt_sysrq there yourselves. After uncompressing the source package, you just need to do a 'make send_sysrq'.

Now you can use the client program 'send_sysrq' to send the sysrq request.

Usage of send_sysrq:
send_sysrq [-p ]

where
is destination UDP port (9 by default).
is DNS name or IP address of the remote host.
is a string of letters such as:
s - for sync
i - for kill all processes
u - for umount (remount read-only) all filesystems
b - for reboot
o - for power off
and other characters same as with magic sysrq key

my favorite string is "sisub"

Important note: send_sysrq sends two copies of the request for each command character separately. It does this to deal with the potential packet loss, because send_sysrq has no feedback from the remote host. Delay between the requests is one second.

Requirements

Works on Linux 2.4.x and on 2.6.x too.

To successful compile you need to have installed:
GCC
Linux kernel sources of your running kernel
Header files of your iptables command


For more information read man page of sysctl, sysctl.conf.

Adding Extra Swap Space

There are situations where we have to expand the SWAP space after installation. For example, suppose you are upgrading RAM 512MB to 1 GB MB, but there is only 1 GB of swap space available which was created during installation. It might be an advantage to increase the amount of swap space to Double the RAM(2 GB) as per the UNIX/Linux guidance and will help you to perform memory eaters.

You have two options: add a swap partition or add a swap file. It is recommended to add a swap partition, but this is not possible if you don't have free Disk space available.

Option 1

Its better to reboot the server to SINGLE USER mode(if possible) before adding the extra SWAP Space
And you can do an optional "swapoff" command to turn off all the swap spaces.

Create the swap partition fdisk.

# fdisk /dev/hda (Assuming Hard drive is hda)
Type n ( for new partition)
Determine the size for the partition
then Toggle the partiotion label to Linux Swap.Its id is 82

Save the partition table,exit fdisk and do a "partprobe" to make it effective

# partprobe

Now you have the swap partition, use the command mkswap to setup the swap partition.
At a shell prompt as root, type the following:

# mkswap /dev/hdaX

To enable the swap partition immediately, type the following command:

# swapon /dev/hdaX

To enable it at boot time, edit /etc/fstab to include:

/dev/hdaX swap swap defaults 0 0

The next time the system boots, it will enable the new swap partition.

After adding the new swap partition and enabling it, make sure it is enabled by viewing the output of the command
# cat /proc/swaps

or
# free

Option 2

Determine the size of the new swap file and multiply it by 1024 to determine the block size. For example, the block size of a 64 MB swap file is 65536.

At a shell prompt as root, type the following command with count being equal to the desired block size:

# dd if=/dev/zero of=/swapfile bs=1024 count=65536

Make it a SWAP file

# mkswap /swapfile

To enable the swap file immediately

# swapon /swapfile

To enable it at boot time, edit /etc/fstab and insert the following

/swapfile swap swap defaults 0 0

PHP and Pear MDB2 Installation

Installation of Pear MDB2 (2.4.1) with Apache-2.2.6 PHP-5.2.3(with MySQL and MySQLI)

Backed up Existing PHP
[root@hareesh ~]# mv /usr/local/lib/php /usr/local/lib/php.bak
[root@hareesh ~]# mv /usr/local/bin/php /usr/local/bin/php.bak
[root@hareesh ~]# mv /usr/local/include/php /usr/local/include/php.bak

Installed PHP-5.2.3 with MySQL and MySQLI Support
[root@hareesh lib]# cd /usr/local/src/
[root@hareesh src]# tar xjf php-5.2.3.tar.bz2
[root@hareesh src]# cd php-5.2.3

[root@hareesh php-5.2.3]# ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-zlib --with-pear --with-mysql --with-mysql-sock=/tmp/mysql.sock --with-mysqli --with-mysqli-sock=/tmp/mysql.sock

[root@hareesh php-5.2.3]# make

Stopped Apache
[root@hareesh ~]# /usr/local/apache2/bin/apachectl stop
httpd: Could not reliably determine the server's fully qualified domain name, using 192.168.0.46 for ServerName

Then Installed PHP
[root@hareesh php-5.2.3]# make install

[root@hareesh php-5.2.3]# /usr/local/apache2/bin/apachectl start
[root@hareesh php-5.2.3]# opera localhost/phpinfo.php

It works



MySQL Connectivity
mysql_native_php.php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>


[root@hareesh php-5.2.3]# opera localhost/mysql_native_php.php

Success


MySQLi Connectivity
mysqli_native_php.php
$mysqli = new mysqli("localhost", "root", "", "mysql");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

printf("Host information: %s\n", $mysqli->host_info);

/* close connection */
$mysqli->close();
?>


[root@hareesh php-5.2.3]# opera localhost/mysqli_native_php.php

Success
Pear MDB2 Installation


Reference

[root@hareesh PEAR_MDB]# pear install MDB2
WARNING: channel "pear.php.net" has updated its protocols, use "channel-update pear.php.net" to update
downloading MDB2-2.4.1.tgz ...
Starting to download MDB2-2.4.1.tgz (119,790 bytes)
..........................done: 119,790 bytes
install ok: channel://pear.php.net/MDB2-2.4.1
MDB2: Optional feature fbsql available (Frontbase SQL driver for MDB2)
MDB2: Optional feature ibase available (Interbase/Firebird driver for MDB2)
MDB2: Optional feature mysql available (MySQL driver for MDB2)
MDB2: Optional feature mysqli available (MySQLi driver for MDB2)
MDB2: Optional feature mssql available (MS SQL Server driver for MDB2)
MDB2: Optional feature oci8 available (Oracle driver for MDB2)
MDB2: Optional feature pgsql available (PostgreSQL driver for MDB2)
MDB2: Optional feature querysim available (Querysim driver for MDB2)
MDB2: Optional feature sqlite available (SQLite2 driver for MDB2)
To install use "pear install pear/MDB2#featurename"

Installed PEAR-MDB2-mysql
[root@hareesh PEAR_MDB]# pear install MDB2#mysql
WARNING: channel "pear.php.net" has updated its protocols, use "channel-update pear.php.net" to update
Skipping package "pear/MDB2", already installed as version 2.4.1
downloading MDB2_Driver_mysql-1.4.1.tgz ...
Starting to download MDB2_Driver_mysql-1.4.1.tgz (36,481 bytes)
..........done: 36,481 bytes
install ok: channel://pear.php.net/MDB2_Driver_mysql-1.4.1
[root@hareesh PEAR_MDB]#


Installed PEAR-MDB2-mysqli
[root@hareesh PEAR_MDB]# pear install MDB2#mysqli
WARNING: channel "pear.php.net" has updated its protocols, use "channel-update pear.php.net" to update
Skipping package "pear/MDB2", already installed as version 2.4.1
downloading MDB2_Driver_mysqli-1.4.1.tgz ...
Starting to download MDB2_Driver_mysqli-1.4.1.tgz (38,064 bytes)
..........done: 38,064 bytes
install ok: channel://pear.php.net/MDB2_Driver_mysqli-1.4.1

MySQL Connectivity with MDB2
MDB2_mysql.php
// Create a valid MDB2 object named $mdb2
// at the beginning of your program...
require_once 'PEAR/MDB2.php';

$mdb2 =& MDB2::connect('mysql://root@localhost/myDB');
if (PEAR::isError($mdb2)) {
die($mdb2->getMessage());
}
// Proceed with getting some data...
$res =& $mdb2->query('SELECT * FROM a');
// Get each row of data on each iteration until
// there are no more rows
while (($row = $res->fetchRow())) {
// Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED
echo $row[0] . "\n";
}
// while (($one = $res->fetchOne())) {
// echo $one . "\n";
// }
?>


[root@hareesh php-5.2.3]# opera localhost/MDB2_mysql.php

Success

MySQLi Connectivity with MDB2
MDB2_mysqli.php
// Create a valid MDB2 object named $mdb2
// at the beginning of your program...
require_once 'PEAR/MDB2.php';

$mdb2 =& MDB2::connect('mysqli://root@localhost/myDB');
if (PEAR::isError($mdb2)) {
die($mdb2->getMessage());
}

// Proceed with getting some data...
$res =& $mdb2->query('SELECT * FROM a');

// Get each row of data on each iteration until
// there are no more rows
while (($row = $res->fetchRow())) {
// Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED
echo $row[0] . "\n";
}

// while (($one = $res->fetchOne())) {
// echo $one . "\n";
// }
?>

[root@hareesh php-5.2.3]# opera localhost/MDB2_mysqli.php

Success

Result
Working fine

Note : AFAIK MDB2 have no ODBC Driver
Reference

Tuesday, November 13, 2007

Cannot execute [Argument list too long]

Tried to remove some files like log files with /bin/rm -rf all at once, and you get this
Error message

# rm -rf /var/log/mail/*.old.log
bash: /bin/rm: /bin/rm: cannot execute [Argument list too long]


So, rm utility complains that the system-wide ARG_MAX value that is used to setup an input buffer size to process the entire list will overflow. Good security measure, but, doesn't help you out with the task at hand.

To get around, use a combination of find, UNIX pipe, and xargs utilities. The rewrite of the original command would look something like this:

# find . -name '*.old.log' -print0 | xargs -0 rm -f

find naturally finds the target file names, and feeds them one by one into the unnamed UNIX/Linux pipe. The -print0 argument instructs to print the full file name on the standard output which is going to the pipe, followed by a null character (instead of the newline character that
-print̢۪uses
). When pipe becomes full, find blocks waiting for more space in the pipe to become available.

On the other end of the pipe, xargs command reads the next filename from the pipe, and executes the command specified with the filename parameter as an argument. The -0 argument instructs xargs to input items as terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally).

getconf utility shows the system settings that most UNIX utilities rely on when allocating various resources including the memory buffers (such as ARG_MAX in this case).

# getconf ARG_MAX
131072


See http://home.comcast.net/~3rdshift/articles/linux_tips.html
for more

Saturday, November 10, 2007

Auto Logout of Inactive Users

How to force automatic logouts of users who forget to log out in case of inactivity detected ?

BASH have a TMOUT variable.We can set the TIMEOUT value here for sessions.


Add the TMOUT variable to your /etc/bashrc file:
# vi /etc/bashrc

Set TMOUT to 300 seconds (5 minuets):
TMOUT=300

This will automatically logout users after 300 seconds of inactivity.
This hack will only work with run level 2, 3 .It will not work with GUI sessions.

Friday, November 9, 2007

Simple Server Monitor

#!/bin/bash
# BASH Script to monitor Server uptime,Servies,Memory Usage,Disk Usage,Load Average,Last Login and Reboot Details and Take backup of configuration files.
DATE=`date +%d.%m.%Y`
TIME=`date +%H.%M.%S`
ADMIN=hareeshvv@gmail.com ## Mail ID of Admin
ADMIN1=hareeshvaliyaveettil@gmail.com ## Mail ID of Admin
FILES=(/etc/hosts /usr/local/apache/conf/httpd.conf /etc/php.ini /var/lib/pgsql/data/pg_hba.conf)
services=(http mysql smtp ftp postgresql) ## List of services to be checked
serviceports=(:80 :3306 :25 :21 :5432) ## List of services to be checked
#services=(http https smtp) ## List of services to be checked
#serviceports=(:80 :443 :25) ## List of services to be checked
title=0
## Definition of Functions
# chkuptime function
chkuptime () {
echo " " >> /tmp/$DATE.$TIME
echo "The Server `hostname` is up for `uptime | cut -f1 -d, | awk {'print $3'} ;uptime | cut -f1 -d, | awk {'print $4'}`" >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
}
# lastlogin function
lastlogin () {
echo "Last login Details" >> /tmp/$DATE.$TIME
echo "##################" >> /tmp/$DATE.$TIME
echo "Last login was by `last | head -1 | awk -F" " {'print $1'}` on `last | head -1 | awk -F" " {'print $2'}` at `last | head -1 | awk -F" " {'print $5'}` `last | head -1 | awk -F" " {'print $6'}` `last | head -1 | awk -F" " {'print $7'}` " >> /tmp/$DATE.$TIME
last | head -1 | awk -F" " {'print $2'} | cut -f1 -d/ > /dev/null 2> /dev/null
if [ $? = 0 ]
then
echo "from `last | head -1 | awk -F" " {'print $3'}`" >> /tmp/$DATE.$TIME
fi
`w`
if [ $? = 0 ]
then
echo Details of currently logged users >> /tmp/$DATE.$TIME
`w` >> /tmp/$DATE.$TIME

fi
echo " " >> /tmp/$DATE.$TIME
}
# lastreboot function
lastreboot () {
echo "Last Reboot Details" >> /tmp/$DATE.$TIME
echo "###################" >> /tmp/$DATE.$TIME
echo "Last reboot was at `last | grep "system boot" | head -1 | awk -F" " {'print $5'}` `last | grep "system boot" | head -1 | awk -F" " {'print $6'}` `last | grep "system boot" | head -1 | awk -F" " {'print $7'}` `last | grep "system boot" | head -1 | awk -F" " {'print $8'}`" >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
}
# Services function
services () {
# Check the Service Status of Server and Write them into a text file

# Function Watch()
Watch () {
#Server=192.168.0.254 ## IP of the remote Server to be monitored
#nmap $Server | grep "${serviceports[$i]/"} > /dev/null 2> /dev/null ## Use this one for Remote Server which is not behind any firewall that may block NMAP
netstat -ntpl | grep "${serviceports[$i]} " ## Use this locally .
# The SPACEBAR in "${serviceports[$i]} " is for exactness
if [ $? != 0 ]
then
if [ $title = 0 ] ## Do this once if any of the services is down
then
echo Failed Services >> /tmp/$DATE.$TIME
echo "###############" >> /tmp/$DATE.$TIME
title=1
fi
echo ${services[$i]} is DOWN >> /tmp/$DATE.$TIME
fi

}
###### Watch () Ends here
echo "Services undergone CHECK are" >> /tmp/$DATE.$TIME
echo "#######################" >> /tmp/$DATE.$TIME
for (( i = 0 ; i < ${#services[@]} ; i++ ))
do
echo ${services[$i]} >> /tmp/$DATE.$TIME
done
echo " " >> /tmp/$DATE.$TIME
## Now call the Watch() function
for (( i = 0 ; i < ${#services[@]} ; i++ ))
do
Watch ${services[$i]}
done
grep Failed /tmp/$DATE.$TIME # > /dev/null 2> /dev/null
if [ $? != 0 ]
then
# {
# echo grep failed output is $? >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
echo "All Services are UP.Congratulations" >> /tmp/$DATE.$TIME
# }
fi
grep DOWN /tmp/$DATE.$TIME ## Warn if all the services are down
if [ $? = 0 ]
then
count=`grep DOWN /tmp/$DATE.$TIME | wc -l`
if [ ${#services[@]} = $count ]
then
echo " " >> /tmp/$DATE.$TIME
echo "*** IMPORTANT NOTICE ***" >> /tmp/$DATE.$TIME
echo "All Services are down !!!!!" >> /tmp/$DATE.$TIME
fi
fi
echo " " >> /tmp/$DATE.$TIME
}
loadavg () {
echo Load Average >> /tmp/$DATE.$TIME
echo "############" >> /tmp/$DATE.$TIME
echo Load average is `uptime | cut -f3 -d, | cut -f2 -d:` `uptime | cut -f4 -d,` `uptime | cut -f5 -d,` >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
}
## loadavg() ends here
disk () {

ALERT=90 # Alert level for Used Percentage of Disk Partitions
df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
used=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
mountpoint=`mount | grep $partition | cut -f3 -d" "`
if [ $used -ge $ALERT ]; then
echo "Disk Usage" >> /tmp/$DATE.$TIME
echo "##########" >> /tmp/$DATE.$TIME
echo "Running out of space \"$partition ($used%) mounted on $mountpoint\" on $(hostname) as on $(date)" >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
fi
done
}
## disk() ends here
memory () {
echo "Memory and SWAP Usage" >> /tmp/$DATE.$TIME
echo "#####################" >> /tmp/$DATE.$TIME
MEM=`free -m | grep Mem | awk -F" " {'print $2'}`
USEDMEM=`free -m | grep Mem | awk -F" " {'print $3'}`
SWAP=`free -m | grep Swap | awk -F" " {'print $2'}`
USEDSWAP=`free -m | grep Swap | awk -F" " {'print $3'}`
echo "Total Memory - $MEM" >> /tmp/$DATE.$TIME
echo "Used - $USEDMEM" >> /tmp/$DATE.$TIME
echo "Total Swap - $SWAP" >> /tmp/$DATE.$TIME
echo "Used Swap - $USEDSWAP" >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
}
### memory() ends here
backup () {
for (( i = 0 ; i < ${#FILES[@]} ; i++ ))
do
cat ${FILES[$i]} > ${FILES[$i]}.$DATE.$TIME
done
echo " " >> /tmp/$DATE.$TIME
}
logchk () {
echo "System Logs" >> /tmp/$DATE.$TIME
echo "###########" >> /tmp/$DATE.$TIME
grep "error" /var/log/messages >> /tmp/$DATE.$TIME
grep "warn" /var/log/messages >> /tmp/$DATE.$TIME
echo " " >> /tmp/$DATE.$TIME
}
Sendmail () {
mail -s "Server Status" $ADMIN < /tmp/$DATE.$TIME
mail -s "Server Status" $ADMIN < /tmp/$DATE.$TIME
}
## End of Function definitions
exec > /dev/null 2> /dev/null
# Call to functions
chkuptime
lastlogin
lastreboot
services
loadavg
disk
memory
### backup
echo "on $(hostname) as on $(date)" >> /tmp/$DATE.$TIME
Sendmail
cd -
rm -rf /tmp/$DATE.$TIME
exit

Installation of PHP-Screw 1.5 with Apache 2.2.6 and PHP-5.2.3

Apache 2.2.6 Installation
[root@myserver src]# pwd
/usr/local/src
[root@myserver src]# cd httpd-2.2.6
[root@myserver httpd-2.2.6]#

[root@myserver httpd-2.2.6]# ./configure --enable-so --prefix=/usr/local/apache2
[root@myserver httpd-2.2.6]# make
[root@myserver httpd-2.2.6]# make install

PHP-5.2.3 installation
[root@myserver src]# pwd
/usr/local/src
[root@myserver src]# cd php-5.2.3
[root@myserver php-5.2.3]#

[root@myserver php-5.2.3]# ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-zlib
[root@myserver php-5.2.3]# make
[root@myserver php-5.2.3]# make install

Configured Apache for PHP 5
# vi /usr/local/apache2/conf/httpd.conf
Added the following 3 lines

LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php .phtml
AddType application/x-httpd-php-source .phps


PHP Screw Installation
[root@myserver src]# pwd
/usr/local/src
[root@myserver src]# cd php_screw-1.5
[root@myserver php_screw-1.5]# phpize
[root@myserver php_screw-1.5]# ./configure
[root@myserver php_screw-1.5]# vi my_screw.h

Replaced
“pm9screw_mycryptkey” with “pm9screw_myownkey” . This is the encryption key that will be used by Screw for encryption

[root@myserver php_screw-1.5]# # make
/bin/sh /usr/local/src/php_screw-1.5/libtool --mode=compile gcc -I. -I/usr/local/src/php_screw-1.5 -DPHP_ATOM_INC -I/usr/local/src/php_screw-1.5/include -I/usr/local/src/php_screw-1.5/main -I/usr/local/src/php_screw-1.5 -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /usr/local/src/php_screw-1.5/php_screw.c -o php_screw.lo
mkdir .libs
gcc -I. -I/usr/local/src/php_screw-1.5 -DPHP_ATOM_INC -I/usr/local/src/php_screw-1.5/include -I/usr/local/src/php_screw-1.5/main -I/usr/local/src/php_screw-1.5 -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /usr/local/src/php_screw-1.5/php_screw.c -fPIC -DPIC -o .libs/php_screw.o
/usr/local/src/php_screw-1.5/php_screw.c: In function `pm9screw_ext_fopen':
/usr/local/src/php_screw-1.5/php_screw.c:30: error: `pm9screw_mycryptkey' undeclared (first use in this function)
/usr/local/src/php_screw-1.5/php_screw.c:30: error: (Each undeclared identifier is reported only once
/usr/local/src/php_screw-1.5/php_screw.c:30: error: for each function it appears in.)
make: *** [php_screw.lo] Error 1

Replaced the same “key” in php_screw.c
[root@myserver php_screw-1.5]# sed 's/pm9screw_mycryptkey/ pm9screw_myownkey/g' php_scre.c > php_screw.c.new
[root@myserver php_screw-1.5]# cat php_screw.c.new > php_screw.c

[root@myserver php_screw-1.5]# make
...
.....
Build complete.
Don't forget to run 'make test'.
Success

Copied the Screw Module to Apache modules directory
[root@myserver php_screw-1.5]# cp modules/php_screw.so /usr/local/apache2/modules/

[root@myserver php_screw-1.5]# vi /usr/local/lib/php.ini
extension=php_screw.so

Restarted Apache
[root@myserver php_screw-1.5]# /usr/local/apache2/bin/apachectl restart

Compilation of the encryption tool
[root@myserver php_screw-1.5]# cd tools/
[root@myserver tools]# make
gcc -o screw screw.c zencode.c -lz
screw.c: In function `main':
screw.c:16: error: `' undeclared (first use in this function)
screw.c:16: error: (Each undeclared identifier is reported only once
screw.c:16: error: for each function it appears in.)
make: *** [screw] Error 1

Replacement of encryption key
[root@myserver tools]# vi screw.c
replaced
pm9screw_mycryptkey
with
pm9screw_myownkey

[root@myserver tools]# make
gcc -o screw screw.c zencode.c -lz
[root@myserver tools]#

Success

[root@myserver tools]# ls
Makefile screw screw.c zencode.c

This "screw" is the encryptor

Copied it to a System PATH
[root@myserver tools]# cp screw /usr/local/bin/

Encrypting a PHP script
Please execute the following command.
screw "Path to the PHP script to be encrypted"
The above line creates the script file enciphered by the same name.
Moreover, a backup is created in the same directory by the name of script
file name .screw.

Executing a PHP script.
If the installation of php_screw.so went OK, encrypted PHP scripts can now
be copied to an appropriate directory and executed as if it was
unencrypted. That is: The encryption is transparent for the
user.


Encryption
[root@myserver tools]# screw /usr/local/apache2/htdocs/phpinfo.php
Success Crypting(/usr/local/apache2/htdocs/phpinfo.php)

Tested the page
# opera localhost/phpinfo.php

Failure. It displays encrypted page.

Solution
Replaced
extension_dir = "./"
with

extension_dir = "/usr/local/apache2/modules"
in /usr/local/lib/php.ini

Restarted Apache
# /usr/local/bin/apachectl restart

Checked from browser
# opera localhost/phpinfo.php
It woks.fine
Opened a normal PHP file also
# opera localhost/pure_php.php
Works

Wednesday, November 7, 2007

postfix/smtp connect to gmail.com[64.233.171.83]: Connection timed out (port 25) server dropped connection without sending the initial SMTP greeting

Postfix has been configured fine.
The mail is working in the local Domain - mydomain.com


But when I try to send mails to outer domains,it produces the following "TIMEOUT" errors in /var/log/mail/info




Nov 5 23:02:43 mydomain postfix/pickup[30923]: 419941C678: uid=555 from=
Nov 5 23:02:43 mydomain postfix/cleanup[31536]: 419941C678: message-id=<20071106050243.419941C678@mydomain.com>
Nov 5 23:02:43 mydomain postfix/qmgr[22926]: 419941C678: from=, size=330, nrcpt=1 (queue active)
Nov 5 23:03:13 mydomain postfix/smtp[31538]: connect to yahoo.com[66.94.234.13]: Connection timed out (port 25)
Nov 5 23:03:13 mydomain postfix/smtp[31538]: connect to yahoo.com[216.109.112.135]: server dropped connection without sending the initial SMTP greeting (port 25)
Nov 5 23:03:13 mydomain postfix/smtp[31538]: 419941C678: to=, relay=none, delay=30, status=deferred (connect to yahoo.com[216.109.112.135]: server dropped connection without sending the initial SMTP greeting)
Nov 5 23:03:51 mydomain postfix/qmgr[22926]: 419941C678: from=, size=330, nrcpt=1 (queue active)
Nov 5 23:03:51 mydomain postfix/qmgr[22926]: 7C14E1C672: from=, size=533, nrcpt=1 (queue active)
Nov 5 23:03:51 mydomain postfix/qmgr[22926]: CD7961C73C: from=, size=527, nrcpt=1 (queue active)
Nov 5 23:03:51 mydomain postfix/smtp[31538]: connect to yahoo.com[216.109.112.135]: server dropped connection without sending the initial SMTP greeting (port 25)
Nov 5 23:04:21 mydomain postfix/smtp[31546]: connect to gmail.com[64.233.171.83]: Connection timed out (port 25)
Nov 5 23:04:21 mydomain postfix/smtp[31547]: connect to gmail.com[72.14.253.83]: Connection timed out (port 25)
Nov 5 23:04:21 mydomain postfix/smtp[31538]: connect to yahoo.com[66.94.234.13]: Connection timed out (port 25)


Nov 6 23:25:30 mydomain postfix/qmgr[11674]: B5DCA1C693: from=,
size=507, nrcpt=1 (queue active) Nov 6 23:26:00 mydomain postfix/smtp[13277]: connect to hotmail.com[64.4.33.7]: Connection timed out (port 25)
Nov 6 23:26:00 mydomain postfix/smtp[13278]: connect to gmail.com[64.233.171.83]: Connection timed out (port 25)
Nov 6 23:26:30 mydomain postfix/smtp[13277]: connect to hotmail.com[64.4.32.7]: Connection timed out (port 25) Nov 6 23:26:30 mydomain postfix/smtp[13277]: 07D5B1C678: to=, relay=none, delay=83207, status=deferred (connect to hotmail.com[64.4.32.7]: Connection timed out)
Nov 6 23:26:30 mydomain postfix/smtp[13278]: connect to gmail.com[64.233.161.83]: Connection timed out (port 25)
Nov 6 23:27:00 mydomain postfix/smtp[13278]: connect to gmail.com[72.14.253.83]: Connection timed out (port 25)



I messed up with it a lot .

It got solved by replacing

disable_dns_lookups = yes

with

disable_dns_lookups = no

in /etc/postfix/main.cf


And apart from this the the folowing may cause this issue ( I am not sure ).

1. The Server is under Firewall
2. Your Server IP may be listed in some SPAM list
3. Improperly configured "relayhost=" entry
4. The faulty main.cf

etcetera.........

Monday, November 5, 2007

QMAIL port 25 and 110 are closed

Qmail installation went fine .But I was unable to connect to port 25 and 110.They were in closed state.When I tried to connect with telnet I got the “Connection refused” message.



# qmailctl stat
/service/qmail-send: up (pid 2219) 37 seconds
/service/qmail-send/log: up (pid 2311) 37 seconds
/service/qmail-smtpd: up (pid 2917) 1 seconds
/service/qmail-smtpd/log: up (pid 2723) 37 seconds
/service/qmail-pop3d: up (pid 2724) 1 seconds
/service/qmail-pop3d/log: up (pid 2989) 37 seconds
messages in queue: 0
messages in queue but not yet preprocessed: 0

Looks good but when I try to connect on the mail server I got the connection problem.

]# telnet localhost 110
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused


# telnet localhost 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused



I have checked the logs for qmail-smtpd and qmail-pop3d and contains a lots of error lines like the following:
tcpserver: fatal: temporarily unable to figure out IP address for 0.0.0.0: file does not exist

I tried nmap

# nmap localhost

Starting nmap 3.70 ( http://www.insecure.org/nmap/ ) at 2007-11-05 10:47 IST
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1655 ports scanned but not shown below are in state: closed)
PORT STATE SERVICE
80/tcp open http
111/tcp open rpcbind
143/tcp open imap
443/tcp open https
877/tcp open unknown
3306/tcp open mysql

Nmap run completed -- 1 IP address (1 host up) scanned in 0.224 seconds

Here the ports 25 and 110 are closed


# qmailctl stop
Stopping qmail...

qmail-smtpd
qmail-send
qmail-pop3d

# qmailctl start
Starting qmail...

Starting qmail-send
Starting qmail-smtpd
Starting qmail-pop3d


# qmailctl stat
/service/qmail-send: up (pid 2921) 37 seconds
/service/qmail-send/log: up (pid 2926) 37 seconds
/service/qmail-smtpd: up (pid 3144) 1 seconds
/service/qmail-smtpd/log: up (pid 2934) 37 seconds
/service/qmail-pop3d: up (pid 3149) 1 seconds
/service/qmail-pop3d/log: up (pid 2938) 37 seconds
messages in queue: 0
messages in queue but not yet preprocessed: 0


# nmap localhost

Starting nmap 3.70 ( http://www.insecure.org/nmap/ ) at 2007-11-05 10:47 IST
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1655 ports scanned but not shown below are in state: closed)
PORT STATE SERVICE
80/tcp open http
111/tcp open rpcbind
143/tcp open imap
443/tcp open https
877/tcp open unknown
3306/tcp open mysql

Nmap run completed -- 1 IP address (1 host up) scanned in 0.224 seconds

Finally I've got the solution from
QmailRocks

For the can't find IP address, fix this by "touch /etc/dnsrewrite"

I did the same "touch /etc/dnsrewrite" and a QMAIL RESTART.


# touch /etc/dnsrewrite
# qmailctl restart


It worked. Great.


# nmap localhost

Starting nmap 3.70 ( http://www.insecure.org/nmap/ ) at 2007-11-05 10:47 IST
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1655 ports scanned but not shown below are in state: closed)
PORT STATE SERVICE
25/tcp open smtp
80/tcp open http
110/tcp open pop3
111/tcp open rpcbind
143/tcp open imap
443/tcp open https
877/tcp open unknown
3306/tcp open mysql

Nmap run completed -- 1 IP address (1 host up) scanned in 0.224 seconds

Saturday, November 3, 2007

BASH Script to Generate files from existing ones with a partial change in filename

#!/bin/bash
# BASH Script to generate $EXTENSION files like FILE_fr.$EXTENSION,FILE_sp.$EXTENSION from existing FILE_$SEARCHSTRING.$EXTENSION without causing any kind of overwrite.
DIR=/tmp/html
EXTENSION=extension
SEARCHSTRING=en
cd $DIR > /dev/null 2> /dev/null
count=`find *$SEARCHSTRING.$EXTENSION | wc -l`
n=1
echo $count \"*$SEARCHSTRING.$EXTENSION\" files found
while [ $n -le $count ]
do
{
filename=`find *$SEARCHSTRING.$EXTENSION | head -$n | tail -1`
echo $filename
language=(fr sp po)
for (( i = 0 ; i < ${#language[@]} ; i++ ))
do

value=`ls $filename | awk -F "$SEARCHSTRING.$EXTENSION" {'print $1'}`
find "$value""${language[$i]}".$EXTENSION > /dev/null 2> /dev/null
if [ $? != 0 ]
then
{
cp "$value"$SEARCHSTRING.$EXTENSION "$value""${language[$i]}".$EXTENSION
}
fi
done
n=$[$n + 1]
}
done
cd - > /dev/null 2> /dev/null
exit

A Simple Service Monitor

#!/bin/bash
# Check the Service Status of Server and send notification mail if anyone is DOWN.
Server=192.168.0.35 ## IP of the remote Server to be monitored
ADMIN=hareeshvv@gmail.com ## Mail ID of Admin
Subject=Server-Status
DATE=`date +%d.%m.%Y`
TIME=`date +%H.%M.%S`

mkdir /tmp/$DATE.$TIME
cd /tmp/$DATE.$TIME
services=(http https mysql smtp pop imap imaps ssh) ## List of services to be checked

Watch () {
#nmap $Server | grep ${services[$i]} > /dev/null 2> /dev/null ## Use this one for Remote Server which is not behind any firewall
netstat -ntpl | grep ${services[$i]} > /dev/null 2> /dev/null ## Use this locally
if [ $? != 0 ]
then
echo ${services[$i]} is DOWN >> result
fi
}

for (( i = 0 ; i < ${#services[@]} ; i++ ))
do
Watch ${services[$i]}
done


grep DOWN result > /dev/null 2> /dev/null
if [ $? = 0 ]
then
count=`grep DOWN result | wc -l`
if [ ${#services[@]} = $count ]
then
echo "All Services are down" >> result
echo "Even the Server may be down" >> result
fi
mail -s $Subject $ADMIN < result
fi
rm -rf result
cd - > /dev/null
exit

How to Create Custom Hot key to Launch Applications in GNOME

1. Open Applications -> System -> Configuration Editor from the GUI

OR

Open a terminal, type gconf-editor

2. Go to "apps" -> "metacity" -> "keybinding_commands"
3. Double-click on an unused element e.g. "command_10"
4. Type in the name of the application you want to launch, for e.g. "firefox" or
"gnome-terminal"
5. Then go to "apps" -> "metacity" -> "global_keybindings"
6. Double-click on the command name that we have edited in "keybinding_commands" Section.
Here for me it is "run_command_10"
7. Then enter the Keyboard shortcut you would like to launch the application
I entered
"<"Alt">"t
here (without the quotes) for gnome-terminal.

Thats all

Go to Desktop and type Alt+t a GNOME terminal should open. It will depend on the active Windows also since some other applications may be having the same HotKey.

Simple Disk and Memory Monitor

#!/bin/sh
# Shell script to monitor the disk space,Memory,SWAP Usage and send an email to $ADMIN, if the free avilable percentage of space is >= $ALERT

ADMIN="hareeshvv@gmail.com"
ADMIN1="admin1@mycompany.com"
ADMIN2="admin2@mycompany.com"


# Alert Level Percentage of Disk Usage . Default is 90%
ALERT=90
df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
used=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
mountpoint=`mount | grep $partition | cut -f3 -d" "`

if [ $used -ge $ALERT ]; then
echo "Running out of space \"$partition ($used%) mounted on $mountpoint\" on $(hostname) as on $(date)" |
mail -s "Alert: Almost out of disk space $used" -c $ADMIN1,$ADMIN2 $ADMIN
fi
done

# Alert on RAM and SWAP Usage

MEM=`free -m | grep Mem | awk -F" " {'print $2'}`
USEDMEM=`free -m | grep Mem | awk -F" " {'print $3'}`
SWAP=`free -m | grep Swap | awk -F" " {'print $2'}`
USEDSWAP=`free -m | grep Swap | awk -F" " {'print $3'}`
echo "Total Memory - $MEM" > /tmp/memorystatus
echo "Used - $USEDMEM" >> /tmp/memorystatus
echo "Total Swap - $SWAP" >> /tmp/memorystatus
echo "Used Swap - $USEDSWAP" >> /tmp/memorystatus
echo "on $(hostname) as on $(date)" >> /tmp/memorystatus

mail -s "Memeory Usage" -c $ADMIN1,$ADMIN2 $ADMIN < /tmp/memorystatus

AT&T USA | Internet not working | Fix by custom APN

If the AT&T Mobile internet is not working on your cellphone, it can be fixed easily by adding an APN configuration. You can read this a...