ABHIONLINUX
Site useful for linux administration and web hosting

2009/11/16

Mysql database connection testing

Please put the following code in a php file in the server and access it through a browser to view the result.

Change the username of database user from "root" to your "database-user", followed by the password of the database user from "testuser" to your "database-access-password".

If the connection was successful the page will display Success. Other wise it will display Could not select DB.

Code:

php
$con=mysql_connect("localhost","root","testuser") or die("Could not connect");
$db=mysql_select_db("test",$con) or die("Could not select DB");
echo "Success";

Reset password for mysql

Error:
--------------
connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost' (using password: YES)'
mysql has failed, please contact the sysadmin (result was "mysql has failed").

Please follow the steps to reseset password for mysql.

Try the below steps :-
1) Set the passwd for mysql in /root/.my.cnf
2) killall mysqld
3) Restart mysqld with the --skip-grant-tables option as below :-
/usr/bin/safe_mysqld --skip-grant-tables &
4) Connect to Mysql :- Just type 'mysql' at the prompt without those quotes.
5) Update passwd for root user with the below command :-
> update user set Password = Password('pass') where User ='root';
6) exit

How to create the MySQL database and CREATE and GRANT Privileges.

HOW TO CREATE THE MySQL DATABASE

This step is only necessary if you don't already have a database set-up . In the following examples, 'username' is an example MySQL user which has the CREATE and GRANT privileges. Use the appropriate user name for your system.

First, you must create a new database for your site (here, 'databasename' is the name of the new database):

mysqladmin -u username -p create databasename

MySQL will prompt for the 'username' database password and then create the initial database files. Next you must login and set the access database rights:

mysql -u username -p

Again, you will be asked for the 'username' database password. At the MySQL prompt, enter following command:

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES
ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';

where

'databasename' is the name of your database
'username@localhost' is the username of your MySQL account
'password' is the password required for that username

Note: Unless your database user has all of the privileges listed above, you will not be able to run site on that database.

If successful, MySQL will reply with:

Query OK, 0 rows affected

To activate the new permissions, enter the following command:

FLUSH PRIVILEGES;

How to connect mysql from remote server

mysql -u root -p -h

where remote server = remote server ip address
To enable MySQL to listen to remote connections, you must find your my.cnf file.

find / -name 'my.cnf'

(the global 'my.cnf is' likely to be /etc but it may be found in other places)

Open the file, and put a # in front of skip-networking or bind-address=127.0.0.1

Example of end result:

1. skip-networking

or

1. bind-address = 127.0.0.1


Also check for any firewall stopping port 3306

Restart MySQL and everything should work fine.

Don't forget to grant users access from remote hosts.

How to install yum in fedora

Try the following steps,

wget http://linux.duke.edu/projects/yum/download/2.0/yum-2.0.7.tar.gz
tar -xvzf yum-2.0.7.tar.gz
cd yum-2.0.7

./configure
make
make install


MAKE SURE TO DOWNLOAD THE CORRECT YUM VERSION:

* yum 3.0.1 - Stable Release, Python 2.4+ and rpm 4.3+ systems only. Requires repomd repositories. Works under FC5, FC6 and rawhide.
* yum-metadata-parser 1.0.2 - C-based metadata parser to quickly parse xml metadata into sqlite databases.
* yum 2.6.X - Stable Release, Python 2.3+ and rpm 4.1.1+ systems requires repomd repositories: 2.6.1 latest known to work with some FC3, FC4, FC5, RHEL4 and compatible distributions
* yum 2.4.X - Stable Release, Python 2.3+ and rpm 4.1.1+ systems requires repomd repositories: 2.4.2 latest known to work with: FC3, FC4, RHEL4 and compatible distributions
* yum 2.0.X - for python 2.1+ and rpm 4.1.1-4.3.1 systems: 2.0.8 latest
* yum 1.0.X - for python 1.5.2+ and rpm 4.0.4 systems: 1.0.3 latest - considered obsolete

if you are not sure what version of python you have installed, send the following command to see your installed phython version:

python

2009/11/14

How to add apache status in http.conf

Include this in httpd.conf


SetHandler server-status
Order deny,allow
Deny from all
Allow from 127.0.0.1


then check command:
lynx http://localhost//whm-server-status
lynx http://localhost//whm-server-status grep uptime to see the apache uptime

How to open ports using iptables

# iptables -I INPUT -p tcp --dport 32 -j ACCEPT

To open a range of ports

iptables -A INPUT -p tcp --destination-port 6881:6999 -j ACCEPT
iptables -A OUTPUT -p tcp --source-port 6881:6999 -j ACCEPT

2009/11/12

phpmail()

$to = "test@test.com";
$from = "stest@test.com";
$sub = "Test Email";
$msg = "Please ignore this";
mail($to, $sub, $msg, "From: $from");


php
$to = "test@test.com";
$subject = "test mail from support";
$body = "Please ignroe this mail";
if (mail($to, $subject, $body)) {
echo("


Message successfully sent!

");
} else {
echo("

Message delivery failed...

");
}

How to get custom php.ini working on php-cgi

1, Copy the servers default php.ini to your home directory

2, Make the following directory in home and chown to user:user
cgi-bin

3, Create a file php.cgi in cgi-bin with the following content
#!/bin/sh
exec /usr/local/cpanel/cgi-sys/php5 -c /home/user/public_html/

4, Chmod +x php.cgi and chown the file to user:user.

5, Add the following in the .htaccess.

Action application/x-httpd-php5 /cgi-bin/php.cgi

2009/11/01

Linux Interview Questions

How to change the modification time of a file use the following command:
touch -m

What is the default link count for files and directories in Linux?
The default link count:
files - 1
directory - 2

How to find only the number of lines in a files?
$ cat > f1

$ wc -l f1
4 f1

What is the difference between echo "$SHELL" and echo '$SHELL'?

$ echo "$SHELL"
/bin/bash


Code:
$ echo '$SHELL'
$SHELL

To check/list the attribute set for a file use the " lsattr " command.
# chattr +i my-file
# lsattr my-file
----i-------- my-file

How to set an append only attribute to a file in linux?
#chattr +a

How to lock the password for a user in linux?
# passwd -l
Password changed.


How to check the kernel version in linux?
$ uname -r
2.6.27-7-generic


How to check the used and free memory in linux?
$ free -m
total used free shared buffers cached
Mem: 1769 757 1011 0 20 302
-/+ buffers/cache: 434 1334
Swap: 7632 0 7632

How to set an immutable attribute to a file in linux?
#chattr +i

How to compare 2 files in linux?
Code:
#cmp

The -l option gives the detailed list of byte number.
Code:
#cmp -l


How to sort a file?
The command "sort" is used for alphabetically or numerically sort a file.

For eg: see the content of the file test
$ cat test
z
a
w
l
c

Inorder to sort the file we can use he sort command

$ sort test
a
c
l
w
z

One more ex: for a file containing numbers:

$ cat num
9
3
6
4

$ sort num
3
4
6
9
_________________



How to read the contents of a zip file without unzipping it?

Code:
zcat < file.gz >


How to suspend a running job and place it in the background?

Key combination " ctrl + z " will suspend a job and put it in the background.

Code:
ctrl+z


How to determine which shell you are using?

The name and path to the shell you are using is saved to the SHELL environment variable. You can then use the echo command to print out the value of any variable by preceding the variable's name with $. Therefore, typing echo $SHELL will display the name of your shell.

Code:
echo $SHELL


What are the process states in Linux?

As a process executes it changes state according to its circumstances.
Linux processes have the following states:

Running : The process is either running or it is ready to run .
Waiting : The process is waiting for an event or for a resource.
Stopped : The process has been stopped, usually by receiving a signal.
Zombie : The process is dead but have not been removed from the process table.



Which command is used to check and repair the file system?

fsck is used to check the file system and repair damaged files.

Code:
# /etc/fsck /dev/file-system



What is LILO?

LILO - Linux Loader

Definition:
The first- and second-stage boot loaders combined are called Linux Loader (LILO). It loads the kernel into the memory and helps the system to boot.


What is a PID?

PID - Process Indentification number

Definition:
It is a number used by Unix/Linux kernels to identify a process.

Use ps command to see PID.


What is a zombie process?

Zombies are dead processes. You cannot kill the Zombie process as they are already dead. A process state becomes zombie when the child process dies before the parent process. The only way to remove all the zombie process is by killing its parent process.


How to list/display the last 5 lines of a file " myfile.txt "?

Lets create a file " myfile.txt "

Example:
Code:
:~/test$ cat > myfile.txt
1
2
3
4
5
6
7
8
9
Ctrl+d

To list the last 5 lines, use the following command.
tail -5 myfile.txt

The tail utility displays the end of a file. The -5 option tells the tail command to display the last 5 lines.

Example:
Code:
:~/test$ tail -5 myfile.txt
5
6
7
8
9



How to delete a file which starts with " - "? Eg: -foo

Let try creating a new file " -foo ".

Example:
Code:
:~/test$ echo "Testing" > -foo
:~/test$ ls -l
-rw-r--r-- 1 telson telson 8 2009-05-21 22:28 -foo


In the above example we create a new file " -foo ".
Now lets try deleting it.

Code:
:~/test$ rm -foo
rm: invalid option -- 'o'
Try `rm --help' for more information.


It seems we are unable to remove the file " -foo ", with the above given command.

How to remove the file " -foo "?

There is 2 ways to remove this file.

rm ./-foo
rm -- -foo

You may use any of the above commands.

Example:
Code:
:~/test$ rm -- -foo
:~/test$ ls -l
total 0


What is the difference between Hard Link and Soft Link in Linux?

Hard Link is a mirror copy of the original file. Hard links share the same inode.
Any changes made to the original or Hard linked file will reflect the other.
Even if you delete any one of the files, nothing will happen to the other.
Hard links can't cross file systems.

Soft Link is a symbolic link to the original file. Soft Links will have a different Inode value.
A soft link points to the original file. If you delete the original file, the soft link fails. If you delete the soft link, nothing will happen.
Soft links can cross file systems.



What is the difference between Telnet and SSH?

Both Telnet and SSH is used for remote Log-In and to trasnfer data.

Telnet -> Telecommunication network
It is not secure and anyone can use it. It uses ASCII format.
Information sent and received can be easily read by anyone (Hackers) in that network.

SSH -> Secure Shell
It is highly secure.
Information passed accross the network is encrypted.
Hackers will not be able to read your data.

So its highly recommended to use SSH to transafer data's securly.



What is Raid? What are the different Raid types and different Raid Levels?

RAID stands for Redundant Array of Independent (or Inexpensive) Disks. It is a set of Technology standards to improve Performence and Fault tolerance.
There are two types of raid :
Software Raid
Hardware Raid

Hardware Raid is most commenly used.

Raid Levels:
Raid 0 - stripping
Raid 1 - Mirroring
Raid 2 - Stripping and Mirroring
Raid 3 - Officially Not Defined
Raid 4 - Striping with Differential Parity
Raid 5 - Striping with Distributional Parity
Raid 10 - A mix of RAID 1 and RAID 0

2009/10/31

Mysql repair (Innodb and MyIsam)

Below is 7 ways to fix your MySQL database when a simple restart doesn't do the trick, or when you have corrupt tables.

Simple MySQL restart:

/usr/local/mysql/bin/mysqladmin -uUSERNAME -pPASSWORD shutdown
/usr/local/mysql/bin/mysqld_safe &

1. Corrupt MyISAM tables

MySQL database allows you to define a different MySQL storage engine for different tables. The storage engine is the engine used to store and retrieve data. Most popular storage engines are MyISAM and InnoDB.

MyISAM tables -will- get corrupted eventually. This is a fact of life.

Luckily, in most cases, MyISAM table corruption is easy to fix.

To fix a single table, connect to your MySQL database and issue a:

repair TABLENAME

To fix everything, go with:

/usr/local/mysql/bin/mysqlcheck --all-databases -uUSERNAME -pPASSWORD -r

A lot of times, MyISAM tables will get corrupt and you won't even know about it unless you review the log files.

I highly suggest you add this line to your /etc/my.cnf config file. It will automatically fix MyISAM tables as soon as they become corrupt:

[mysqld]
myisam-recover=backup,force

If this doesn't help, there are a few additional tricks you can try.

2. Multiple instances of MySQL

This is pretty common. You restart MySQL and the process immediately dies.

Reviewing the log files will tell you another instance of MySQL may be running.

To stop all instances of MySQL:

/usr/local/mysql/bin/mysqladmin -uUSERNAME -pPASSWORD shutdown
killall mysql
killall mysqld

Now you can restart the database and you will have a single running instance

3. Changed InnoDB log settings

Once you have a running InnoDB MySQL database, you should never ever change these lines in your /etc/my.cnf file:

datadir = /usr/local/mysql/data
innodb_data_home_dir = /usr/local/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /usr/local/mysql/data
innodb_log_files_in_group = 2
innodb_log_file_size = 5242880

InnoDB log file size cannot be changed once it has been established. If you change it, the database will refuse to start.

4. Disappearing MySQL host tables

I've seen this happen a few times. Probably some kind of freakish MyISAM bug.

Easily fixed with:

/usr/local/bin/mysql_install_db

5. MyISAM bad auto_increment

If the auto_increment count goes haywire on a MyISAM table, you will no longer be able to INSERT new records into that table.

You can typically tell the auto_increment counter is malfunctioning, by seeing an auto_increment of -1 assigned to the last inserted record.

To fix - find the last valid auto_increment id by issuing something like:

SELECT max(id) from tablename

And then update the auto_increment counter for that table

ALTER TABLE tablename AUTO_INCREMENT = id+1

6. Too many connections

Your database is getting hit with more connections than it can handle and now you cannot even connect to the database yourself.

First, stop the database:

/usr/local/mysql/bin/mysqladmin -uUSERNAME -pPASSWORD shutdown

If that doesn't help you can try "killall mysql" and "killall mysqld"

Once the database stopped, edit your /etc/my.cnf file and increase the number of connections. Don't go crazy with this number or you'll bring your entire machine down.

On a dedicated database machine we typically use:

max_connections = 200
wait_timeout = 100

Try restarting the database and see if that helps.

If you're getting bombarded with queries and you need to be able to connect to the database to make some table changes, set a different port number in your /etc/my.cnf file, start the database, make any changes, then update the port back to normal (master-port = 3306) and restart.

7. Corrupt InnoDB tables

InnoDB tables are my favorite. Transactional, reliable and unlike MyISAM, InnoDB supports concurrent writes into the same table.

InnoDB's internal recovery mechanism is pretty good. If the database crashes, InnoDB will attempt to fix everything by running the log file from the last timestamp. In most cases it will succeed and the entire process is transparent.

Unfortunately if InnoDB fails to repair itself, the -entire- database will not start. MySQL will exit with an error message and your entire database will be offline. You can try to restart the database again and again, but if the repair process fails - the database will refuse to start.

This is one reason why you should always run a master/master setup when using InnoDB - have a redundant master if one fails to start.

Before you go any further, review MySQL log file and confirm the database is not starting due to InnoDB corruption.

There are tricks to update InnoDB's internal log counter so that it skips the queries causing the crash, but in our experience this is not a good idea. You lose data consistency and will often break replication.

Once you have corrupt InnoDB tables that are preventing your database from starting, you should follow this five step process:

Step 1: Add this line to your /etc/my.cnf configuration file:

[mysqld]
innodb_force_recovery = 4

Step 2: Restart MySQL. Your database will now start, but with innodb_force_recovery, all INSERTs and UPDATEs will be ignored.

Step 3: Dump all tables

Step 4: Shutdown database and delete the data directory. Run mysql_install_db to create MySQL default tables

Step 5: Remove the innodb_force_recovery line from your /etc/my.cnf file and restart the database. (It should start normally now)

Step 6: Restore everything from your backup

How to repair mysql database

Repairing MyISAM mySQL Tables/Databases:

cd /var/lib/mysql/DBNAME
#^ Please note that we assume your mySQL data directory is /var/lib/mysql

myisamchk *.MYI


Repairing ISAM mySQL Tables/Databases:

cd /var/lib/mysql/DBNAME
#^ Please note that we assume your mySQL data directory is /var/lib/mysql

isamchk *.MYI
OR

To repair your enite database,

mysqlcheck -r your_database
mysqlcheck -o your_database

2009/10/30

Pop and Imap difference

POP:
=====
1. Since email needs to be downloaded into desktop PC before being displayed, you may have the following problems for POP3 access:

* You need to download all email again when using another desktop PC to check your email.
* May get confused if you need to check email both in the office and at home.

The downloaded email may be deleted from the server depending on the setting of your email client.

2. All messages as well as their attachments will be downloaded into desktop PC during the 'check new email' process.
3. Mailboxes can only be created on desktop PC. There is only one mailbox (INBOX) exists on the server.
4. Filters can transfer incoming/outgoing messages only to local mailboxes.
5. Outgoing email is stored only locally on the desktop PC.
6. Messages are deleted on the desktop PC. Comparatively, it is inconvenient to clean up your mailbox on the server.
7. Messages may be reloaded onto desktop PC several times due to the corruption of system files.
-----------------------------------------------

Imap:
======
Since email is kept on server, it would gain the following benefits for IMAP access:

* No need to download all email when using other desktop PC to check your email.
* Easier to identify the unread email.
2. A whole message will be downloaded only when it is opened for display from its content.
3. Multiple mailboxes can be created on the desktop PC as well as on the server.
4. Filters can transfer incoming/outgoing messages to other mailboxes no matter where the mailboxes locate (on the server or the PC).
5. Outgoing email can be filtered to a mailbox on server for accessibility from other machine.
6. Messages can be deleted directly on the server to make it more convenient to clean up your mailbox on the server.
7. The occurrence of reloading messages from the server to PC is much less when compared to POP3.

Backend files that is effected in a cpanel server.

Apache
=======
/usr/local/apache
+ bin- apache binaries are stored here - httpd, apachectl, apxs
+ conf - configuration files - httpd.conf
+ cgi-bin
+ domlogs - domain log files are stored here
+ htdocs
+ include - header files
+ libexec - shared object (.so) files are stored here - libphp4.so,mod_rewrite.so
+ logs - apache logs - access_log, error_log, suexec_log
+ man - apache manual pages
+ proxy -
+ icons -

Init Script :/etc/rc.d/init.d/httpd - apache start script
Cpanel script to restart apache - /scripts/restartsrv_httpd

Exim
=====
Conf : /etc/exim.conf - exim main configuration file
/etc/localdomains - list of domains allowed to relay mail
Log : /var/log/exim_mainlog - incoming/outgoing mails are logged here
/var/log/exim_rejectlog - exim rejected mails are reported here
/exim errors are logged here
Mail queue: /var/spool/exim/input
Cpanel script to restart exim - /scripts/restartsrv_exim
Email forwarders and catchall address file - /etc/valiases/domainname.com
Email filters file - /etc/vfilters/domainname.com
POP user authentication file - /home/username/etc/domainname/passwd
catchall inbox - /home/username/mail/inbox
POP user inbox - /home/username/mail/domainname/popusername/inbox
POP user spambox - /home/username/mail/domainname/popusername/spam
Program : /usr/sbin/exim (suid - -rwsr-xr-x 1 root root )
Init Script: /etc/rc.d/init.d/exim

ProFTPD
========
Program :/usr/sbin/proftpd
Init Script :/etc/rc.d/init.d/proftpd
Conf: /etc/proftpd.conf
Log: /var/log/messages, /var/log/xferlog
FTP accounts file - /etc/proftpd/username - all ftp accounts for the domain are listed here

Pure-FTPD
=========
Program : /usr/sbin/pure-ftpd
Init Script :/etc/rc.d/init.d/pure-ftpd
Conf: /etc/pure-ftpd.conf
Anonymous ftp document root - /etc/pure-ftpd/ip-address

Frontpage Extensions
=================
Program - (Install): /usr/local/frontpage/version5.0/bin/owsadm.exe
Uninstall and then install for re-installations
FP files are found as _vti-bin, _vti-pvt, _vti-cnf, vti-log inside the public_html

Mysql
=======
Program : /usr/bin/mysql
Init Script : /etc/rc.d/init.d/mysql
Conf : /etc/my.cnf, /root/.my.cnf
Data directory - /var/lib/mysql - Where all databases are stored.
Database naming convention - username_dbname (eg: john_sales)
Permissions on databases - drwx 2 mysql mysql
Socket file - /var/lib/mysql/mysql.sock, /tmp/ mysql.sock

SSHD
======
Program :/usr/local/sbin/sshd
Init Script :/etc/rc.d/init.d/sshd
/etc/ssh/sshd_config
Log: /var/log/messages

Perl
====
Program :/usr/bin/perl
Directory :/usr/lib/perl5/5.6.1/

PHP
====

Program :/usr/local/bin/php, /usr/bin/php
ini file: /usr/local/lib/php.ini - apache must be restarted after any change to this file
php can be recomplied using /scripts/easyapache

Named(BIND)
============
Program: /usr/sbin/named
Init Script: /etc/rc.d/init.d/named
/etc/named.conf
db records:/var/named/
/var/log/messages

--------------------------------------------------------------------------------------------------------------------------------------

Cpanel installation directory structure
=============================
/usr/local/cpanel
+ 3rdparty/ - tools like fantastico, mailman files are located here
+ addons/ - AdvancedGuestBook, phpBB etc
+ base/ - phpmyadmin, squirrelmail, skins, webmail etc
+ bin/ - cpanel binaries
+ cgi-sys/ - cgi files like cgiemail, formmail.cgi, formmail.pl etc
+ logs/ - cpanel access log and error log
+ whostmgr/ - whm related files

WHM related files
===============
/var/cpanel - whm files
+ bandwidth/ - rrd files of domains
+ username.accts - reseller accounts are listed in this files
+ packages - hosting packages are listed here
+ root.accts - root owned domains are listed here
+ suspended - suspended accounts are listed here
+ users/ - cpanel user file - theme, bwlimit, addon, parked, sub-domains all are listed in this files
+ zonetemplates/ - dns zone template files are taken from here

Common CPanel scripts
===================
cpanel/whm Scripts are located in /scripts/
+ addns - add a dns zone
+ addfpmail - Add frontpage mail extensions to all domains without them
+ addfpmail2 -Add frontpage mail extensions to all domains without them
+ addnetmaskips - Add the netmask 255.255.255.0 to all IPs that have no netmask
+ addnobodygrp - Adds the gorup nobody and activates security
+ addpop - add a pop account
+ addservlets - Add JSP support to an account (requires tomcat)
+ addstatus - (Internal use never called by user)
+ adduser - Add a user to the system
+ bandwidth - (OLD)
+ betaexim - Installs the latest version of exim
+ biglogcheck - looks for logs nearing 2 gigabytes in size
+ bsdcryptoinstall - Installs crypto on FreeBSD
+ bsdldconfig - Configures the proper lib directories in FreeBSD
+ bsdpkgpingtest - Tests the connection speed for downloading FreeBSD packages
+ buildbsdexpect - Install expect on FreeBSD
+ builddomainaddr - (OLD)
+ buildeximconf - Rebuilds exim.conf
+ buildpostgrebsd-dev - Installs postgresql on FreeBSD.
+ chcpass - change cpanel passwords
+ easyapache - recompile/upgrade apache and/or php
+ exim4 - reinstall exim and fix permissions
+ fixcommonproblems - fixes most common problems
+ fixfrontpageperm - fixes permission issues with Front Page
+ fixmailman - fixes common mailman issues
+ fixnamed - fixes common named issues
+ fixndc - fixes rndc errors with named
+ fixquotas - fixes quota problems
+ fullhordereset - resets horde database to a fresh one - all previous user data are lost
+ initquotas - initializes quotas
+ installzendopt - installs zend optimizer
+ killacct - terminate an account - make sure you take a backup of the account first
+ mailperm - fixes permission problems with inboxes
+ park - to park a domain
+ pkgacct - used to backup an account
+ restartsrv - restart script for services
+ restorepkg - restores an account from a backup file ( pkgacct file)
+ runlogsnow - update logs of all users
+ runweblogs - update stats for a particular user
+ securetmp - secures /tmp partition with options nosuexec and nosuid
+ suspendacct - suspends an account
+ unsuspendacct - unsuspends a suspended account
+ upcp - updates cpanel to the latest version
+ updatenow - updates the cpanel scripts
+ updateuserdomains - updates userdomain entries
Important cpanel/whm files
====================
/etc/httpd/conf/httpd.conf - apache configuration file
/etc/exim.conf - mail server configuration file
/etc/named.conf - name server (named) configuration file
/etc/proftpd.conf - proftpd server configuration file
/etc/pure-ftpd.conf - pure-ftpd server configuration file
/etc/valiases/domainname - catchall and forwarders are set here
/etc/vfilters/domainname - email filters are set here
/etc/userdomains - all domains are listed here - addons, parked,subdomains along with their usernames
/etc/localdomains - exim related file - all domains should be listed here to be able to send mails
/var/cpanel/users/username - cpanel user file
/var/cpanel/cpanel.config - cpanel configuration file ( Tweak Settings )*
/etc/cpbackup-userskip.conf -
/etc/sysconfig/network - Networking Setup*
/etc/hosts -
/var/spool/exim -
/var/spool/cron -
/etc/resolv.conf - Networking Setup--> Resolver Configuration
/etc/nameserverips - Networking Setup--> Nameserver IPs ( FOr resellers to give their nameservers )
/var/cpanel/resellers - For addpkg, etc permissions for resellers.
/etc/chkserv.d - Main >> Service Configuration >> Service Manager *
/var/run/chkservd - Main >> Server Status >> Service Status *
/var/log/dcpumon - top log process
/root/cpanel3-skel - skel directory. Eg: public_ftp, public_html. (Account Functions-->Skeleton Directory )*
/etc/wwwacct.conf - account creation defaults file in WHM (Basic cPanel/WHM Setup)*
/etc/cpupdate.conf - Update Config *
/etc/cpbackup.conf - Configure Backup*
/etc/clamav.conf - clamav (antivirus configuration file )
/etc/my.cnf - mysql configuration file
/usr/local/Zend/etc/php.ini OR /usr/local/lib/php.ini - php configuration file
/etc/ips - ip addresses on the server (except the shared ip) (IP Functions-->Show IP Address Usage )*
/etc/ipaddrpool - ip addresses which are free
/etc/ips.dnsmaster - name server ips
/var/cpanel/Counters - To get the counter of each users.
/var/cpanel/bandwidth - To get bandwith usage of domain

How and email works in the server

Hello,

Please check the link below, It will show how and email works in the server.

http://support.kavi.com/khelp/kmlm/user_help/html/how_email_works.html

How to know cpanel version from the back end.

Try this,

cat /usr/local/cpanel/version && echo

You will get the cpanel version.

How to change memory_limit, upload_max_filesize and safe_mode status

php_value memory_limit 64M
php_value upload_max_filesize 8M

Safe mode can't be disabled via htaccess
Create a file including the following directive in /etc/httpd/conf/httpd.conf
under the particular domain's virtualhost add

php_admin_value safe_mode Off

2009/10/24

How to install cpanel

SSH in to the Server with root login and run the following commands:

# mkdir /home/cpanel
# cd /home/cpanel
# wget http://layer1.cpanel.net/latest
# sh latest

You have successfully installed cpanel in your server. You can access it using the URL
http://ipaddress:2086

2009/10/17

How to install Kloxso/Lxadmin in a Linux server

Make sure that you open the ports 7778 and 7777 in the firewall. Otherwise you won't be able to connect to kloxo.
You have to disable selinux by editing /etc/sysconfig/selinux and changing the line to selinux=disabled and then running
# $ setenforce 0

[/code]

Kloxo installation consists of downloading either the kloxo-install-master.sh or kloxo-install-slave.sh from download.lxlabs.com and executing them as root. They will download all the required files and do the complete installation on their own.

[code]

Commands
# $ wget http://download.lxlabs.com/download/kloxo/production/kloxo-install-master.sh
# $ sh ./kloxo-install-master.sh

You will presented with a question/menu from yum/up2date, on which you can press

[/code]

Kloxo will install:

1. Web server:

* apache
* pure-ftp
* awstats

2. Mail server:

* qmail-toaster
* courier (imap pop)
* webmail
* httpd (for webmail)

3. Nameserver:
* bind
* bind-chroot
4. Database Server:
* mysql-server

Once kloxo is installed, you can connect to 'http://machine-name:7778', and you will be presented with a login screen - the password would be 'admin'. Once you login, Kloxo will explicitly force you to change the password to something other than 'admin'.

If you want to have a cluster, you have to run 'kloxo-install-slave.sh' in all the servers that you intend to make as slaves. Once 'kloxo-install-slave.sh' is completed, you can add the server from the 'add server' page in the master's server page. From then on, you can manage every aspect of the server through our intuitive graphical interface. We expect you to have a great time managing your hosting through kloxo. IF you run into any problems, please visit our forum at our website 'http://lxlabs.com/forum', and you can ask your query there. Since our forum is integrated with mailing list which in turn has our main developers as members, you can get direct answers from the developers themselves.

Upgrading kloxo is as easy as click of button. The 'update home' page will show you the latest version of kloxo available, and the 'release notes' listing will tell you the changes that happened since your version, in a very clear format - the bug fix/security fix/feature additions all will be displayed in different colors and clearly identifiable in the listing. This wil help you in making a decision about how critical is the upgradation of kloxo, and how soon it should be updated. The release notes will also contain any special information the user should know after the upgradation is done. All this makes sure that your 'managing the server' days are over, and you can entirely focus your time more productively on your business.

2009/10/14

Howto use multiple SSH keys for password less login

Step # 1: Generate first ssh key

Type the following command to generate your first public and private key on a local workstation. Next provide the required input or accept the defaults. Please do not change the filename and directory location.

workstation#1 $ ssh-keygen -t rsa

Finally, copy your public key to your remote server using scp

workstation#1 $ scp ~/.ssh/id_rsa.pub user@remote.server.com:.ssh/authorized_keys


Step # 2: Generate next/multiple ssh key

a) Login to 2nd workstation

b) Download original the authorized_keys file from remote server using scp

workstation#2 $ scp user@remote.server.com:.ssh/authorized_keys ~/.ssh

c) Now create the new pub/private key:

workstation#2 $ ssh-keygen -t rsa

d) Now you have new public key. APPEND this key to the downloaded authorized_keys file using cat command:

workstation#2 $ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

workstation#2 $ scp ~/.ssh/authorized_keys user@remote.server.com:.ssh/

You can repeat step #2 for each user or workstations for remote server.

Step #3: Test your setup

Now try to login from Workstation #1, #2 and so on to remote server. You should not be asked for a password:

how to set up ssh keys

# First, install OpenSSH on two UNIX machines, hurly and burly. This works best using DSA keys and SSH2 by default as far as I can tell. All the other HOWTOs I've seen seem to deal with RSA keys and SSH1, and the instructions not surprisingly fail to work with SSH2.
# On each machine type ssh somemachine.example.com and make a connection with your regular password. This will create a .ssh dir in your home directory with the proper perms.
# On your primary machine where you want your secret keys to live (let's say hurly), type

ssh-keygen -t dsa

This will prompt you for a secret passphrase. If this is your primary identity key, make sure to use a good passphrase. If this works right you will get two files called id_dsa and id_dsa.pub in your .ssh dir. Note: it is possible to just press the enter key when prompted for a passphrase, which will make a key with no passphrase. This is a Bad Idea ™ for an identity key, so don't do it! See below for uses of keys without passphrases.

#
scp ~/.ssh/id_dsa.pub burly:.ssh/authorized_keys2

Copy the id_dsa.pub file to the other host's .ssh dir with the name authorized_keys2.
# Now burly is ready to accept your ssh key. How to tell it which keys to use? The ssh-add command will do it. For a test, type

ssh-agent sh -c 'ssh-add < /dev/null && bash'

This will start the ssh-agent, add your default identity(prompting you for your passphrase), and spawn a bash shell. From this new shell you should be able to:

#
ssh burly

This should let you in without typing a password or passphrase. Hooray! You can ssh and scp all you want from this bash shell and not have to type any password or passphrase.

2009/10/13

How to find the load and uptime of each nod in a VPS Master server

for i in `vzlist | awk '{print $1}'`; do echo "VPS $i"; vzctl exec $i uptime; done


vzpid processid -- will show which vps contains that process.
Eg:
vzpid 27262
Pid VEID Name
27262 290 httpd

2009/10/11

How to secure /tmp Partition with Cpanel/WHM

If you are renting a server then chances are everything is lumped in / and a small amount partitioned for /boot and some for swap. With this current setup, you have no room for making more partitions unless you have a second hard-drive. Learn how to create a secure /tmp partition even while your server is already up and running.

One of the beat way to secure /tmp is to give /tmp it's own partition and mount it using noexec- This would protect your system from MANY local and remote exploits of rootkits being run from your /tmp folder.

What we are doing it creating a file that we will use to mount at /tmp. So log into SSH and SU to root

cd /dev

Create 100MB file for our /tmp partition. If you need more space, make count size larger.

dd if=/dev/zero of=tmpMnt bs=1024 count=100000

Make an extended filesystem for our tmpMnt file

/sbin/mke2fs /dev/tmpMnt

Backup your /tmp dir- I had mysql.sock file that I needed to recreate the symbolic link for. Other programs may use it to store cache files or whatever.

cd /
cp -R /tmp /tmp_backup

Mount the new /tmp filesystem with noexec

mount -o loop,noexec,nosuid,rw /dev/tmpMnt /tmp
chmod 1777 /tmp

Copy everything back to new /tmp and remove backup

cp -R /tmp_backup/* /tmp/

rm -rf /tmp_backup

Now we need to add this to fstab so it mounts automatically on reboots.

pico -w /etc/fstab

You should see something like this:
/dev/hda3 / ext3 defaults,usrquota 1 1
/dev/hda1 /boot ext3 defaults 1 2
none /dev/pts devpts gid=5,mode=620 0 0
none /proc proc defaults 0 0
none /dev/shm tmpfs defaults 0 0
/dev/hda2 swap swap defaults 0 0

At the bottom add

/dev/tmpMnt /tmp ext2 loop,noexec,nosuid,rw 0 0

(Each space is a tab)
Save it!
Ctrl + X and Y

Your done- /tmp is now mounted as noexec.

How to upgrade the kernel on RHEL3

If you are trying to upgrade the pre-built kernel from Redhat Network or are you trying to compile your own kernel?

If it's the former, just do up2date -uf kernel-smp. If it's the latter, here's some quick instructions to learn how to compile their own kernel (for the 2.6 kernel):

1) cd /usr/src
2) unlink linux
3) rm -rfv linux-oldversion
4) wget http://kernel.org/pub/linux/kernel/v2.6/li...version.tar.bz2 (see www.kernel.org)
5) tar -jxvf linux-newversion.tar.bz2
6) ln -s linux-newversion linux
7) cd linux
8) make mrproper
9) make oldconfig (you may have to select new options available that wasn't on the old kernel. Generally, you're safe to just keep presseing enter for it to select the default for those new options.)
10) make menuconfig (ONLY if you want to edit kernel configuration)
11) make (go make some coffee)
12) make modules_install
13) make install
14) cp /usr/src/linux/.config /boot/config-newversion (newversion=version of the new kernel)
15) grub (you'll be enterred into a "grub>" prompt)
16) savedefault --default=0 --once
17) quit (you'll go back to normal bash prompt)
18) reboot

If the kernel boots up successfully:
1) open up /boot/grub/grub.conf in text editor
2) change "default=1" to "default=0"
3) save

If the kernel does not boot:
1) have techs simply hardboot the server letting it boot the default kernel (the old one)
2) figure out what went wrong and try again

To remove and old version of a kernel (do NOT do this for the rpm installed kernels (yum/up2date):
1) cd /boot
2)rm -fv config-oldversion initrd-oldversion System.map-oldversion vmlinuz-oldversion
3) cd /lib/modules
4) rm -rfv oldversion
5) remove entry from /boot/grub/grub.conf

Generally, when I go and delete a kernel, I leave atleast 2 installed. One older one (the previous working one) and the latest one installed. Anything older than those 2 can be removed.

How to Upgrade WHM / cPanel Linux server to EDGE release

Follow the steps below,

a] Just login to WHM

b] Look for Server Configuration

c] Click on Update Config

d] Set cPanel/WHM Updates option to Manual Updates Only (bleeding EDGE tree)

http://www.cyberciti.biz/faq/wp-content/uploads/2007/07/whm-cpanel-edge-upgrade.jpg

e] Click on Save.

To start upgrade procedure

Look for cPanel

Click on Upgrade to Latest Version

Click on Click Upgrade button
Edge upgrade from a shell or command prompt

Login as the root via ssh. Edit /etc/cpupdate.conf file:
# vi /etc/cpupdate.conf
Find line
CPANEL=stable
Replace with:
CPANEL=manual-edge
Save and close the file. Now update to edge:
# /scripts/upcp --force

How to stop spamming from the servers and SPF

Please go through this link, if you get an error like email spoofing or associated issues. You can use the below given link to verify the validity of the rule that you have created.

http://www.kitterman.com/spf/validate.html

You can check the below link to create the SPF record of your wish.

http://www.openspf.org/

Also most acceptable condition is with the '~' but not with '-'. The latter is Fail condition while the former is softfail. Latter will act like a neutral condition, ie, neither accept nor reject.

Also if you notice spamming in the server please try to grep the home directory in the exim error logs/applicable logs.

tail -f /var/log/exim_mainlog | grep "cwd=/home"

If the mail was generated from the home, then it will give hints to the spammer directory.

Also make sure to disable the php - nobody. Try to configure the same from the backend of the server.

http://www.webhostgear.com/232.html


Use following two script to catch the spammer.

1. exim -bpr | grep "<*@*>" | awk '{print $4}'|grep -v "<>" | sort | uniq -c | sort -n

That will show you the maximum no of email currently in the mail queue have from or to the email address in the mail queue with exact figure.

2. exim -bpr | grep "<*@*>" | awk '{print $4}'|grep -v "<>" |awk -F "@" '{ print $2}' | sort | uniq -c | sort -n

That will show you the maximum number of emails currently in the mail queue have for the domain or from the domain with number.

2009/10/02

How to change interface/source IP address in postfix.

Follow the steps below if you want to change interface/source
IP address in Postfix.

Modify the variable smtp_bind_address in /etc/postfix/main.cf

If it’s not present, just add it.

smtp_bind_address = IP Address

Then service postfix reload

Make sure you reload postfix. Restart, stop/start may not work

2009/10/01

Stop PHP nobody Spammers via mail()

PHP and Apache has a history of not being able to track which users are sending out mail through the PHP mail function from the nobody user causing leaks in formmail scripts and malicious users to spam from your server without you knowing who or where.

Watching your exim_mainlog doesn't exactly help, you see th email going out but you can't track from which user or script is sending it. This is a quick and dirty way to get around the nobody spam problem on your Linux server.

If you check out your PHP.ini file you'll notice that your mail program is set to: /usr/sbin/sendmail and 99.99% of PHP scripts will just use the built in mail(); function for PHP - so everything will go through /usr/sbin/sendmail =)

Requirements:

We assume you're using Apache 1.3x, PHP 4.3x and Exim. This may work on other systems but we're only tested it on a Cpanel/WHM Red Hat Enterprise system.

Step 1)
Login to your server and su - to root

Step 2)
Turn off exim while we do this so it doesn't freak out.
/etc/init.d/exim stop

Step 3)
Backup your original /usr/sbin/sendmail file. On systems using Exim MTA, the sendmail file is just basically a pointer to Exim itself.
mv /usr/sbin/sendmail /usr/sbin/sendmail.hidden

Step 4)
Create the spam monitoring script for the new sendmail.
vi /usr/sbin/sendmail

Paste in the following:

Code:
#!/usr/local/bin/perl

# use strict;
use Env;
my $date = `date`;
chomp $date;
open (INFO, ">>/var/log/spam_log") || die "Failed to open file ::$!";
my $uid = $>;
my @info = getpwuid($uid);
if($REMOTE_ADDR) {
print INFO "$date - $REMOTE_ADDR ran $SCRIPT_NAME at $SERVER_NAME n";
}
else {

print INFO "$date - $PWD - @infon";

}
my $mailprog = '/usr/sbin/sendmail.hidden';
foreach (@ARGV) {
$arg="$arg" . " $_";
}

open (MAIL,"|$mailprog $arg") || die "cannot open $mailprog: $!n";
while ( ) {
print MAIL;
}
close (INFO);
close (MAIL);


Step 5)
Change the new sendmail permissions
chown root:mailtrap /usr/sbin/sendmail
chmod 2755 /usr/sbin/sendmail

Step 6)
Create a new log file to keep a history of all mail going out of the server using web scripts
touch /var/log/spam_log

chmod 0666 /var/log/spam_log

Step 7)
Start Exim up again.
/etc/init.d/exim start

Step 8)
Monitor your spam_log file for spam, try using any formmail or script that uses a mail function - a message board, a contact script.
tail - f /var/log/spam_log


Sample Log Output

Code:
Mon Apr 11 07:12:21 EDT 2005 - /home/username/public_html/directory/subdirectory - nobody x 99 99 Nobody / /sbin/nologin


Log Rotation Details

Your spam_log file isn't set to be rotated so it might get to be very large quickly. Keep an eye on it and consider adding it to your logrotation.

vi /etc/logrotate.conf

FIND:
Code:
# no packages own wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
create 0664 root utmp
rotate 1
}


ADD BELOW:

Code:
# SPAM LOG rotation
/var/log/spam_log {
monthly
create 0777 root root
rotate 1
}


You may also want to chattr + i /usr/sbin/sendmail so it doesn't get overwritten.

Cpanel Hardening

You should configure the following in your WHM (CPanel):

Main >> Server Configuration >> Tweak Settings

[x] Prevent the user ‘nobody’ from sending out mail to remote addresses (php and cgi scripts generally run as nobody if you are not using phpsuexec and suexec respectively.)

[x] Track the origin of messages sent though the mail server by adding the X-Source headers (exim 4.34+ required)

Main >> Security >> Fix Insecure Permissions (Scripts)

Main >> Security >> Tweak Security

“Compilers are disabled for unpriviledge users”

Main >> Service Configuration >> Enable/Disable SuExec

suexec Status “enabled”

Main >> Account Functions >> Disable or Enable Demo Mode

Select from “Users” the “demo” account and click “Modify” then click “Disable” if it exists :)

Access Awstats from outside of cpanel

Step 1.
Download awstats from http://awstats.sourceforge.net

Step 2.
Uncompress awstats-5.6.tgz

Step 3.
Copy the contents of the uncompressed cgi-bin folder from your hard drive to the user cgi-bin directory (this includes awstats.pl, awstats.model.conf, and the lang, lib and plugins sub-directories).

Step 4.
If necessary (should not be needed with most setups), edit the first (top-most) line of awstats.pl file that is #!/usr/bin/perl to reflect the path were your Perl interpreter is installed. Default value works for most of Unix OS, but it also might be #!/usr/local/bin/perl

Step 5.
Move AWStats icon sub-directories and its content into a directory readable by your web server, for example /home/users/public_html/icons

Step 6.
Copy awstats.model.conf file into a new file named awstats.myvirtualhostname.conf. This new file must be stored in /home/user/public_html/cgi-bin.

Step 7.

Edit this new config file with your own setup :
- Change LogFile value with full path of your web server log file
(The path is:
LogFile="/usr/local/apache/domlogs/domain.com").

- Check if LogFormat has the value "1" (it means "NCSA apache combined/ELF/XLF log format").

- Change DirIcons parameter to reflect relative path of icon directory.
(DirIcons="/icons")

- Edit SiteDomain parameter with the main domain name or the intranet web server name used to reach the web site to analyze (Example: www.mydomain.com).

IMPORTANT! - Change DirData to use the same Statics file than Cpanel Awstats and do not loose any entry.
(DirData="/home/user/tmp/awstats/")

Step 8.

Access AwStats by the URL:
www.domain.com/cgi-bin/awstats.pl?config=domain.com

Awstats not updating in the cpanel server

Problem related to awstats updation.. run the following scripts

/scripts/runweblogs

Check the stats after run the scripts. If the error still persists

vi /var/cpanel/cpanel.conf then edit the extracpus=0 to 2

Then execute /usr/local/cpanel/startup

After this, run the above scripts ... it will update the awstats.

-------------------------------------------------------------------------

This problem may occur when apache log files are over 2GB in size and new logs won't update. The best way to prevent this to delete domain logs from the following path

/usr/local/apache/domlogs/yourdomain.com.log

How to secure a new server (Linux)

1. Install chkrootkit
2. Install rkhunter
3. Install Firewall
3.1. Install apf / bfd
3.2. Install csf (for cPanel/WHM servers only)
4. Securing /tmp
5. Remove all insecure packages
6. Script to Monitor Server load
7. Secure ssh
8. Prevent upload of Exploits
9. Disable InSecure Commands
10. Install Email alert script for Root Logins
11. Install AIDE

Useful Linux Commands

Command to find files accessed in last 30 days. will find files that is accessed in last 30 days, under root folder.
# find / type f -atime -30
------------------------------------------------------------------------------------

List contents of a folder along with contents of its subfolder. But it will traverse only to a depth of one. ie, it will not show the contents of subfolder's subfolder.
# ls *
------------------------------------------------------------------------------------

To print the iptables rules along with line number.
# iptables -L --line-numbers
------------------------------------------------------------------------------------

To find a particular rule with rule number #; where # is the rule number you want to list
# iptables -L OUTPUT --line-numbers | grep ^#
------------------------------------------------------------------------------------

Change permission only for folders
# find . -type d -exec chmod 755 {} \;
------------------------------------------------------------------------------------

List with 777 permission
#find . -type d -perm 777
------------------------------------------------------------------------------------

To list all the processes listening to port 80
# lsof -i TCP:80|awk {'print $2'}
------------------------------------------------------------------------------------

To kill all the process listening to apache port 443/80
# lsof -i TCP:443|awk {'print $2'} | xargs kill -9
------------------------------------------------------------------------------------

Recursively chmod only directories
find . -type d -exec chmod 755 {} \;
------------------------------------------------------------------------------------

Recursively set the execute bit on every directory
chmod -R a+X *
The +X flag sets the execute bit on directories only
------------------------------------------------------------------------------------

Recursively chmod only files
find . -type f -exec chmod 644 {} \;
------------------------------------------------------------------------------------

Recursively chmod only PHP files (with extension .php)
find . -type f -name '*.php' -exec chmod 644 {} \;
------------------------------------------------------------------------------------

Find all files in /home/user/demo directory
$ find /home/user/demo -print
------------------------------------------------------------------------------------

Now find all files in /home/user/demo directory with permission 777
$ find /home/user/demo -perm 777 -print
------------------------------------------------------------------------------------

Next you need to apply chmod on all these files using -exec option:
$ find /home/user/demo -perm 777 -print -exec chmod 755 {} \;
------------------------------------------------------------------------------------

Command to find files modified on July 12
ll|grep dr|awk '{print $9}' > 123
for i in `cat 123`;do ls -ld $i;done|grep "Jul 12"
------------------------------------------------------------------------------------

How to See the SSH password guesses

First, find the PID of the listening SSH daemon process:
# ps axuww | egrep 'PID|ssh'
Now become root and attach to the running daemon with strace:
# strace -f -e 'read,write' -p12345
------------------------------------------------------------------------------------

Yum issues. TypeError: rpmdb open failed

Yum issues.

While giving the command "yum list " getting the error

==========================================================
Loaded plugins: fastestmirror
error: no dbpath has been set
error: cannot open Packages database in /%{_dbpath}
Traceback (most recent call last):
File "/usr/bin/yum", line 29, in ?
yummain.user_main(sys.argv[1:], exit_code=True)
File "/usr/share/yum-cli/yummain.py", line 229, in user_main
errcode = main(args)
File "/usr/share/yum-cli/yummain.py", line 84, in main
base.getOptionsConfig(args)
File "/usr/share/yum-cli/cli.py", line 184, in getOptionsConfig
enabled_plugins=self.optparser._splitArg(opts.enableplugins))
File "/usr/lib/python2.4/site-packages/yum/__init__.py", line 191, in _getConfig
self._conf = config.readMainConfig(startupconf)
File "/usr/lib/python2.4/site-packages/yum/config.py", line 754, in readMainConfig
yumvars['releasever'] = _getsysver(startupconf.installroot, startupconf.distroverpkg)
File "/usr/lib/python2.4/site-packages/yum/config.py", line 824, in _getsysver
idx = ts.dbMatch('provides', distroverpkg)
TypeError: rpmdb open failed
==========================================

Solution

#rm /dev/urandom
#mknod -m 644 /dev/urandom c 1 9

that should solve problem

until second VPS reboot...

----
stop VPS
mknod --mode 644 /vz/private/100/lib/udev/devices/urandom c 1 9
start VPS

Your issue should fix your issue
For more reference you can use the link http://forum.openvz.org

How to take mysql backup and restore

To take the backup
---------------
mysqldump database > databasebackup.sql

To restore the mysql backup
---------------------------
mysql database < databasebackup.sql

To unzip database.sql.gz
------------------------
gunzip database.sql.gz

Unable to open pty: No such file or directory

While trying to login to the VPS , if you are getting the error
Unable to open pty: No such file or directory
Please try the commands in the main node VPS.

vzctl exec VEID /sbin/MAKEDEV pty
vzctl exec VEID /sbin/MAKEDEV tty

This will fix your issue.

2009/09/28

How to disble root logins in the cpanel server

Following steps will show you how to disable direct root login. If you are using cPanel server make sure you add your admin user to the ‘wheel’ group so that you will be able to ‘su -‘ to root, otherwise you may lock yourself out of root.

1. SSH into your server as ‘admin’ and gain root access by su

2. Copy and paste this line to edit the file for SSH logins
vi /etc/ssh/sshd_config

3. Find the line
Protocol 2, 1

4. Uncomment it and change it to look like
Protocol 2

5. Next, find the line
PermitRootLogin yes

6. Uncomment it and make it look like PermitRootLogin no

7. Save the file

8. Now you can restart SSH
/etc/rc.d/init.d/sshd restart

Now, no one will be able to login to root with out first loggin in as admin and ‘su -‘ to root, and you will be forcing the use of a more secure protocol. Just make sure you remember both passwords

How to block an IP range using firewall

You can block an IP range using the following command.
/sbin/iptables -I INPUT -s 42.0.0.0/8 -j DROP

2009/09/26

How to change bash3.2# to user@hostname#

To change bash3.2# to user@hostname# permenently you hav to add the following lines to .bash_profile.

PS1="[\u@\h:#] "
case `id -u`
in
0) PS1="${PS1}# ";;
*) PS1="${PS1}$ ";;
esac

------------------------
sample .bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
unset USERNAME

PS1="[\u@\h:\w] "
case `id -u`
in
0) PS1="${PS1}# ";;
*) PS1="${PS1}$ ";;
esac
---------------------------

2009/09/24

How to Limit Connections per IP using mod_limitipconn on cPanel

How to limit connections per IP in a cPanel hosting server :
there is an Apache module named mod_limitipconn which will take care of it for us.
first download the latest version of mod_limitipconn from this site : http://dominia.org/djao/limitipconn2.html
decompress and install it.
at current time the latest version is 0.23.

1.wget http://dominia.org/djao/limit/mod_limitipconn-0.23.tar.bz2
2.tar jxvf mod_limitipconn-0.23.tar.bz2
3.cd mod_limitipconn-0.23
4.usr/local/apache/bin/apxs -cia mod_limitipconn.c

next step is to add the required configuration to the Apache config file , we can add this directly to the end of httpd.conf file but the problem is that if we do this , the httpd.conf will be overwritten by easyapache so we will use include files to add our config.
login into your WHM panel , and follow the following menu items :
Main >> Service Configuration >> Apache Configuration >> Include Editor
on the Post VirtualHost Include section , choose All Versions from drop down menu and add the following config into it :

1.
2.
3.MaxConnPerIP 10
4.NoIPLimit images/*
5.

6.


then click on update and restart Apache server.

How to install Mod_security in the server

Requirements:
Apache Web Server 1.3x or 2.x

Note: We have confirmed this security addon works with Cpanel based servers.

UPDATE: Sept. 15, 2004:
Changed # Prevent path traversal (..) attacks rules to fix a typo in tutorial.

How to install?
1. Login to your server through SSH and su to the root user.

2. First your going to start out by grabbing the latest version of mod_security
wget http://www.modsecurity.org/download/mod_security-1.7.4.tar.gz

3. Next we untar the archive and cd into the directory:
tar zxvf mod_security-1.7.4.tar.gz
cd mod_security-1.7.4/

4. Now you need to determine which version of apache you use:
APACHE 1.3.x users
cd apache1/
APACHE 2.x users
cd apache2/

5. Lets Compile the module now:
/usr/local/apache/bin/apxs -cia mod_security.c

6. Ok, now its time to edit the httpd conf file. First we will make a backup just incase something goes wrong:
cp /usr/local/apache/conf/httpd.conf /usr/local/apache/conf/httpd.conf.backup

7. Now that we have backed it all up, we can edit the httpd.conf. Replace pico with nano depending on what you have
pico /usr/local/apache/conf/httpd.conf

8. Lets look for something in the config, do this by holding control and pressing W and you are going to search for

(altho any of the IfModules would work fine)

9. Now add this


# Turn the filtering engine On or Off
SecFilterEngine On

# Change Server: string
SecServerSignature " "

# Make sure that URL encoding is valid
SecFilterCheckURLEncoding On

# This setting should be set to On only if the Web site is
# using the Unicode encoding. Otherwise it may interfere with
# the normal Web site operation.
SecFilterCheckUnicodeEncoding Off

# Only allow bytes from this range
SecFilterForceByteRange 1 255

# The audit engine works independently and
# can be turned On of Off on the per-server or
# on the per-directory basis. "On" will log everything,
# "DynamicOrRelevant" will log dynamic requests or violations,
# and "RelevantOnly" will only log policy violations
SecAuditEngine RelevantOnly

# The name of the audit log file
SecAuditLog /var/log/httpd/audit_log

# Should mod_security inspect POST payloads
SecFilterScanPOST On

# Action to take by default
SecFilterDefaultAction "deny,log,status:500"

# Require HTTP_USER_AGENT and HTTP_HOST in all requests
SecFilterSelective "HTTP_USER_AGENT|HTTP_HOST" "^$"

# Prevent path traversal (..) attacks
SecFilter "../"

# Weaker XSS protection but allows common HTML tags
SecFilter "<[[:space:]]*script" # Prevent XSS atacks (HTML/Javascript injection) SecFilter "<(.|n)+>"

# Very crude filters to prevent SQL injection attacks
SecFilter "delete[[:space:]]+from"
SecFilter "insert[[:space:]]+into"
SecFilter "select.+from"

# Protecting from XSS attacks through the PHP session cookie
SecFilterSelective ARG_PHPSESSID "!^[0-9a-z]*$"
SecFilterSelective COOKIE_PHPSESSID "!^[0-9a-z]*$"


10. Save the file Ctrl + X then Y

11. Restart Apache

/etc/rc.d/init.d/httpd stop
/etc/rc.d/init.d/httpd start

You've successfully installed mod_security!

How to disabe Mod_Security2 for a domain

SecFilterEngine Off cannot be used in .htaccess, for Mod_Security 2 instead SecRuleEngine should be used.

If you get an error in apache error logs that this entry cannot be used here, use the following method instead.

Open either modsec2.conf or the modsec2/whitelist.conf in /etc/httpd/conf/ directory and put the following entry

SecRule SERVER_NAME "Domain_name" phase:1,nolog,allow,ctl:ruleEngine=off

2009/09/23

Exim

Print a count of the messages in the queue:

root@localhost# exim -bpc

Print a listing of the messages in the queue (time queued, size, message-id, sender, recipient):

root@localhost# exim -bp

Print a summary of messages in the queue (count, volume, oldest, newest, domain, and totals):

Delete emails for an email account

exim -bp | grep username@domain.com | awk ‘{print $3}’ | xargs exim -Mrm ;

root@localhost# exim -bp | exiqsumm


Print what Exim is doing right now:

root@localhost# exiwhat

Test how exim will route a given address:

root@localhost# exim -bt alias@localdomain.com
user@thishost.com
<-- alias@localdomain.com router = localuser, transport = local_delivery root@localhost# exim -bt user@thishost.com user@thishost.com router = localuser, transport = local_delivery root@localhost# exim -bt user@remotehost.com router = lookuphost, transport = remote_smtp host mail.remotehost.com [1.2.3.4] MX=0 Run a pretend SMTP transaction from the command line, as if it were coming from the given IP address. This will display Exim's checks, ACLs, and filters as they are applied. The message will NOT actually be delivered. root@localhost# exim -bh 192.168.11.22 Display all of Exim's configuration settings: root@localhost# exim -bP Searching the queue with exiqgrep Exim includes a utility that is quite nice for grepping through the queue, called exiqgrep. Learn it. Know it. Live it. If you're not using this, and if you're not familiar with the various flags it uses, you're probably doing things the hard way, like piping `exim -bp` into awk, grep, cut, or `wc -l`. Don't make life harder than it already is. First, various flags that control what messages are matched. These can be combined to come up with a very particular search. Use -f to search the queue for messages from a specific sender: root@localhost# exiqgrep -f [luser]@domain Use -r to search the queue for messages for a specific recipient/domain: root@localhost# exiqgrep -r [luser]@domain Use -o to print messages older than the specified number of seconds. For example, messages older than 1 day: root@localhost# exiqgrep -o 86400 [...] Use -y to print messages that are younger than the specified number of seconds. For example, messages less than an hour old: root@localhost# exiqgrep -y 3600 [...] Use -s to match the size of a message with a regex. For example, 700-799 bytes: root@localhost# exiqgrep -s '^7..$' [...] Use -z to match only frozen messages, or -x to match only unfrozen messages. There are also a few flags that control the display of the output. Use -i to print just the message-id as a result of one of the above two searches: root@localhost# exiqgrep -i [ -r | -f ] ... Use -c to print a count of messages matching one of the above searches: root@localhost# exiqgrep -c ... Print just the message-id of the entire queue: root@localhost# exiqgrep -i Managing the queue The main exim binary (/usr/sbin/exim) is used with various flags to make things happen to messages in the queue. Most of these require one or more message-IDs to be specified in the command line, which is where `exiqgrep -i` as described above really comes in handy. Start a queue run: root@localhost# exim -q -v Start a queue run for just local deliveries: root@localhost# exim -ql -v Remove a message from the queue: root@localhost# exim -Mrm [ ... ]


Freeze a message:

root@localhost# exim -Mf [ ... ]

Thaw a message:

root@localhost# exim -Mt [ ... ]

Deliver a message:

root@localhost# exim -M [ ... ]

Force a message to fail and bounce as "cancelled by administrator":

root@localhost# exim -Mg [ ... ]

Remove all frozen messages:

root@localhost# exiqgrep -z -i | xargs exim -Mrm


Remove all messages older than five days (86400 * 5 = 432000 seconds):

root@localhost# exiqgrep -o 432000 -i | xargs exim -Mrm

Freeze all queued mail from a given sender:

root@localhost# exiqgrep -i -f luser@example.tld | xargs exim -Mf


View a message's headers:

root@localhost# exim -Mvh

View a message's body:

root@localhost# exim -Mvb

View a message's logs:

root@localhost# exim -Mvl

Add a recipient to a message:

root@localhost# exim -Mar

[
... ]

Edit the sender of a message:

root@localhost# exim -Mes

Access control

Exim allows you to apply access control lists at various points of the SMTP transaction by specifying an ACL to use and defining its conditions in exim.conf. You could start with the HELO string.

# Specify the ACL to use after HELO
acl_smtp_helo = check_helo

# Conditions for the check_helo ACL:
check_helo:

deny message = Gave HELO/EHLO as "friend"
log_message = HELO/EHLO friend
condition = ${if eq {$sender_helo_name} }

deny message = Gave HELO/EHLO as our IP address
log_message = HELO/EHLO our IP address
condition = ${if eq {$sender_helo_name}{$interface_address} }

accept

NOTE: Pursue HELO checking at your own peril. The HELO is fairly unimportant in the grand scheme of SMTP these days, so don't put too much faith in whatever it contains. Some spam might seem to use a telltale HELO string, but you might be surprised at how many legitimate messages start off with a questionable HELO as well. Anyway, it's just as easy for a spammer to send a proper HELO than it is to send HELO im.a.spammer, so consider yourself lucky if you're able to stop much spam this way.

Next, you can perform a check on the sender address or remote host. This shows how to do that after the RCPT TO command; if you reject here, as opposed to rejecting after the MAIL FROM, you'll have better data to log, such as who the message was intended for.

# Specify the ACL to use after RCPT TO
acl_smtp_rcpt = check_recipient

# Conditions for the check_recipient ACL
check_recipient:

# [...]

drop hosts = /etc/exim_reject_hosts
drop senders = /etc/exim_reject_senders

# [ Probably a whole lot more... ]

This example uses two plain text files as blacklists. Add appropriate entries to these files - hostnames/IP addresses to /etc/exim_reject_hosts, addresses to /etc/exim_reject_senders, one entry per line.

It is also possible to perform content scanning using a regex against the body of a message, though obviously this can cause Exim to use more CPU than it otherwise would need to, especially on large messages.

# Specify the ACL to use after DATA
acl_smtp_data = check_message

# Conditions for the check_messages ACL
check_message:

deny message = "Sorry, Charlie: $regex_match_string"
regex = ^Subject:: .*Lower your self-esteem by becoming a sysadmin

accept

Fix SMTP-Auth for Pine

If pine can't use SMTP authentication on an Exim host and just returns an "unable to authenticate" message without even asking for a password, add the following line to exim.conf:

begin authenticators

fixed_plain:
driver = plaintext
public_name = PLAIN
server_condition = "${perl{$1}{$2}{$3}}"
server_set_id = $2
> server_prompts = :

This was a problem on CPanel Exim builds awhile ago, but they seem to have added this line to their current stock configuration.
Log the subject line

This is one of the most useful configuration tweaks I've ever found for Exim. Add this to exim.conf, and you can log the subject lines of messages that pass through your server. This is great for troubleshooting, and for getting a very rough idea of what messages may be spam.

log_selector = +subject

Reducing or increasing what is logged.
Disable identd lookups

Frankly, I don't think identd has been useful for a long time, if ever. Identd relies on the connecting host to confirm the identity (system UID) of the remote user who owns the process that is making the network connection. This may be of some use in the world of shell accounts and IRC users, but it really has no place on a high-volume SMTP server, where the UID is often simply "mail" or whatever the remote MTA runs as, which is useless to know. It's overhead, and results in nothing but delays while the identd query is refused or times out. You can stop your Exim server from making these queries by setting the timeout to zero seconds in exim.conf:

rfc1413_query_timeout = 0s

Disable Attachment Blocking

To disable the executable-attachment blocking that many Cpanel servers do by default but don't provide any controls for on a per-domain basis, add the following block to the beginning of the /etc/antivirus.exim file:

if $header_to: matches "example\.com|example2\.com"
then
finish
endif

It is probably possible to use a separate file to list these domains, but I haven't had to do this enough times to warrant setting such a thing up.
Searching the logs with exigrep

The exigrep utility (not to be confused with exiqgrep) is used to search an exim log for a string or pattern. It will print all log entries with the same internal message-id as those that matched the pattern, which is very handy since any message will take up at least three lines in the log. exigrep will search the entire content of a log entry, not just particular fields.

One can search for messages sent from a particular IP address:

root@localhost# exigrep '<= .* \[12.34.56.78\] ' /path/to/exim_log Search for messages sent to a particular IP address: root@localhost# exigrep '=> .* \[12.34.56.78\]' /path/to/exim_log

This example searches for outgoing messages, which have the "=>" symbol, sent to "user@domain.tld". The pipe to grep for the "<=" symbol will match only the lines with information on the sender - the From address, the sender's IP address, the message size, the message ID, and the subject line if you have enabled logging the subject. The purpose of doing such a search is that the desired information is not on the same log line as the string being searched for. root@localhost# exigrep '=> .*user@domain.tld' /path/to/exim_log | fgrep '<=' Generate and display Exim stats from a logfile: root@localhost# eximstats /path/to/exim_mainlog Same as above, with less verbose output: root@localhost# eximstats -ne -nr -nt /path/to/exim_mainlog Same as above, for one particular day: root@localhost# fgrep YYYY-MM-DD /path/to/exim_mainlog | eximstats Bonus! To delete all queued messages containing a certain string in the body: root@localhost# grep -lr 'a certain string' /var/spool/exim/input/ | \ sed -e 's/^.*\/\([a-zA-Z0-9-]*\)-[DH]$/\1/g' | xargs exim -Mrm Note that the above only delves into /var/spool/exim in order to grep for queue files with the given string, and that's just because exiqgrep doesn't have a feature to grep the actual bodies of messages. If you are deleting these files directly, YOU ARE DOING IT WRONG! Use the appropriate exim command to properly deal with the queue. If you have to feed many, many message-ids (such as the output of an `exiqgrep -i` command that returns a lot of matches) to an exim command, you may exhaust the limit of your shell's command line arguments. In that case, pipe the listing of message-ids into xargs to run only a limited number of them at once. For example, to remove thousands of messages sent from test@example.com: root@localhost# exiqgrep -i -f '' | xargs exim -Mrm
 
 
exim -bpru |awk '{print $3}' | xargs -n 1 -P 40 exim -v -M

How to reinstall spamassasin in cpanel server

Reinstalling Spamassasin

killall -9 spamd
rm /etc/mail/rulesdujour/ -rf
rm /etc/mail/spamassassin/ -rf
rm /usr/share/spamassassin/ -rf
rm -rf /var/lib/spamassassin/3.00*/saupdates_openprotect_com
rm -f /var/lib/spamassassin/3.00*/saupdates_openprotect_com.cf
rm -f /var/lib/spamassassin/3.00*/saupdates_openprotect_com.pre
/scripts/perlinstaller --force Digest::SHA1
/scripts/realperlinstaller --force IO::Zlib
/scripts/perlinstaller --force Mail::SpamAssassin
/scripts/fixspamassassinfailedupdate
/scripts/perlinstaller --force Mail::SPF Mail::DomainKeys
/scripts/perlinstaller --force Mail::DKIM Encode::Detec Tie::Cache

Also run a cpanel update after all these steps are over.

/scripts/upcp --force
/scripts/upcp

2009/09/16

Plesk passwords in Linux and Windows

Linux:

root@localhost#cat /etc/psa/.psa.shadow
“Password”

Windows:

Check the Plesk installation path:
Via command prompt:
C:\SWSoft\Plesk\admin\bin\>”plesksrvclient.exe” -get
Password will be displayed in a dialog box

SSL

Generating a Certificate Signing Request (CSR)
To generate the keys for the Certificate Signing Request (CSR) run the following command from a terminal prompt:

$ openssl genrsa -des3 -out server.key 1024

To create the CSR:-

run the following command at a terminal prompt:
$ openssl req -new -key server.key -out server.csr



Creating a Self-Signed Certificate:-

To create the self-signed certificate, run the following command at a terminal prompt:

$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Installing the Certificate:-

You can install the key file server.key and certificate file server.crt, or the certificate file issued by your CA, by running following commands at a terminal prompt:

$ sudo cp server.crt /etc/ssl/certs
$ sudo cp server.key /etc/ssl/private


Now simply configure any applications, with the ability to use public-key cryptography, to use the certificate and key files. For example, Apache can provide HTTPS.

To configure Apache for HTTPS add the following three lines to the /etc/apache2/sites-available/subversion file

SSLEngine on
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key

Configure Apache Server (https) the Repository:-

We need to be sure the right modules are enabled

$ a2enmod dav
$ a2enmod dav_svn
We must set up virtual host for subversion server. File that you can put in /etc/apache2/sites-available/default (original file).so we can copy the original file (default) to duplication file (subversion).
$ sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/subversion.
Edit file $ sudo vim /etc/apache2/sites-available/subversion

NameVirtualHost 192.170.50.61:443

ServerAdmin webmaster@localhost
#SSLCertificate
SSLEngine on
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key

DAV svn
SVNPath /home/svn/repos
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile /etc/apache2/dav_svn.passwd
#Required authentication
Require valid-user
# Require encryption
SSLRequireSSL

ErrorLog /var/log/apache2/error.log
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature On



Symbolic link:-

Be sure to make a symbolic link to that file in /etc/apache2/sites-enabled:

$ ln –s /etc/apache2/sites-available/subversion/ /etc/apache2/sites-enabled


Open Port Number:-

Add "Listen 443" to /etc/apache2/ports.conf:

$ sudo vim /etc/apache2/ports.conf

Listen 443



Subversion main configuration file:-

Edit /etc/apache2/mods-available/dav_svn.conf configuration file and follow the instructions:
$ sudo vim /etc/apache2/mods-available/dav_svn.conf


DAV svn
SVNPath /home/svn/repos
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile /etc/apache2/dav_svn.passwd
Require valid-user
SSLRequireSSL


User authentication:-

To add the first user, you can run the following command:

$ sudo htpasswd -c /etc/apache2/dav_svn.passwd suresh



Note: If you have just installed SVN, the passwd file will not yet exist and needs to be created using the "-c" switch. Adding any users after that should be done without the "-c" switch to avoid overwriting the passwd file.

Direct repository you can run the following command:

$ sudo svn co file:///home/svn/repos



You should start apache service
$ sudo /etc/init.d/apache2 start

Email limit for a particular domain in cpanel

To increase the mail limit for the particular domain then you would need to add the domain in your maxemailsperdomain from the below mentioned location:

pico /var/cpanel/maxemailsperdomain/yourdomainhere.com

yourdomainhere.com is the domain for increasing the number of mails. Once you enter the no. in the file. You may save it and REMEMBER to restart exim services by executing the following command :

/scripts/build_maxemails_config

How to find a hacked website?

To finding the website is hacked by someone or badware scripts running on the server. You can find here…

http://unmaskparasites.com/

This site should be healthy report…. If the report shows badware running..

You need to clean the site on the server & restore the old backup..

Then send review to google web tools &b google will unblock from google blacklist.

Email me for further doubts..

Thanks…

How to disabe mod security using htaccess

Inorder to disable mod_security add the following code into the .htaccess file


# Turn off mod_security filtering.
SecFilterEngine Off

# The below probably isn't needed, but better safe than sorry.
SecFilterScanPOST Off



/// If it is apache 2 then mod_security will be version2 so in that case use
SecRuleEngine Instead of SecFilterEngine