Issue with exim — require_files: Permission denied in logs ?

Facing issue in sending/receiving mails in a cPanel server ?

As always, first place is to check for /var/log/exim_mainlog.
If you spot something like this :

2014-04-30 17:07:34 H=(xxxx-122-106-xx-xx-co.in) [xx.xx.xx.xx]:55278 F= temporarily rejected RCPT : require_files: error for /home/account/etc/domain.com: Permission denied

It looks like the permission/ownership has been altered for the path
given in the logs ( the mailbox location )

Fix this issue by running the following :

/scripts/mailperm 'account-name'

— mailperm script is provided by cPanel to automatically fix the permission
and ownership of mailboxes with the user account provided.

virt-manager without root

To be able to execute virt-manager without root privilege,

– create a new group

# group add libvirt

– Add the required users to this group by editing the /etc/groups file

– Edit the libvirtd configurations:

# vi /etc/libvirt/libvirtd.conf

– Add the following configurations.

unix_sock_group = "libvirt"
auth_unix_rw = "none"

– Restart libvirtd,

#service libvirtd restart

– Logout and try to access libvirtd

$ ssh -X <username>@<host> virt-manager

./arun

Plesk upgrade to the latest stable version — Centos 5.x 64 bit arch

— Plesk can be upgraded upto version 9.5.4 either from Plesk control
Panel or by using the following script :

# /usr/local/psa/admin/bin/autoinstaller

— Till this version, its pretty straightforward.

— But when trying to upgrade to a version higher with a PHP
version < 5.3, you will face issues. -- We are now trying to Upgrade Plesk using the stock CentOS repo's and do not depend on any 3rd Party repo's including the trusted atomic. -- From the version 9.5.4, do an installation again, selecting the same version number (9.5.4) # /usr/local/psa/admin/bin/autoinstaller

# After selecting the version from the installation menu, you will find such a screen in the
next page :

Please select the components of Parallels Plesk Panel you want to install:
………
………

Different PHP interpreter versions
14. (*) PHP5 support
15. ( ) PHP5.3 support

— From this select ’15. ( ) PHP5.3 support’ and proceed with the installation.

— At the end of this installation, you will get Plesk 9.5.4 with PHP 5.3 support,
which means you will have the PHP required to upgrade to the next level,
without any further repo’s

— Although this is the case, when you try to check the PHP version,
you will get something like this :

PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/php/
modules/sqlite.so' - /usr/lib64/php/modules /sqlite.so: cannot open shared
object file: No such file or directory in Unknown on line 0

— Ignore this error for the moment

— Upgrade Plesk to 11.5 using the auto-installer.

— There should not be errors ( in usual cases), other than the license error which can
be ignored.

— Once Upgrade is completed, we will have to fix the issue with sqlite.so.

# yum list php*sqlite*

— This is acutally a bug in Plesk that this module comes with the 32-bit arch, even
if the CentOS arch is 64-bit and all other modules are installed as 64 bit.

— To get around this, remove the rpm ‘php53-sqlite2’ and install a 64-bit arch one
from RHEL/CentOS

— Remove it using the command,

# rpm -e --nodeps php53-sqlite2 ( Dont remove using YUM or without ‘–nodeps’ option )

— Download and install the 64bit arch package

# wget http://plesk-autoinstall.mirror.serverloft.eu/PSA_10.1.1/
dist-rpm-RedHat-el5-x86_64/opt/php53/php53-sqlite2-5.3.2-11011812.x86_64.rpm

— Run the following command to install the Package :

# rpm -i php53-sqlite2-5.3.2-11011812.x86_64.rpm

— Check php -v and ensure things are fine.

cPanel – Chkservd showing Exim/IMAP getting failed numerous times ?

— Check chkservd logs (/var/log/chkservd.log ) and see if we can find something
like this in-relation to exim

==========================

>> AUTH PLAIN AF9fsdsdxcxcxcX19pspdivxc1k1MGJYek44eXpOMVliWkdOdF
dfTVRWbjNPU29uADlBVEFlMG 1MR0hsMVRESlI2WnFIZ3FRSDWWEXQ0dMYUlqZzVEbTFMY
k1FQUpHJokUtTAn:DWQ=

<< 421 host.xxxx.com Service not available - closing connection exim: ** [421 host.xxxx.com: Service not available - closing connection != 2]

==========================

-- This shows that the check daemon failed to authenticate
with the temporal auth key (exim ) and therefore check is getting
failed.

-- As a result of this, we can find lots of SMTP authentication failures
in exim_mainlog ( both from valid and invalid IP's )

-- To fix this issue with exim-auth key, we need to generate them.

-- # cd /var/cpanel/serviceauth/
# rm -rf exim
# service cpanel restart
# service exim restart

Monitor chkservd logs ( /var/log/chkservd.log ) and make sure things are fine !

METALS AS DISINFECTANTS

1.     INTRODUCTION

Pathogen-free drinking water is a priority for the safety of human health concerned with waterborne infectious diseases. Increasing urbanization has aggravated the problem of microbial contamination in most of drinking water sources resulting into outbreaks and sporadic incidences of water transmitted diseases mainly gastroenteritis, cholera, dysentery, typhoid, poliomyelitis and hepatitis. Although there are a number of popular methods such as filtration, ozonisation, reverse osmosis and UV radiation, chlorination is the most popular globally used method for drinking water disinfection, particularly in piped supplies at community level. Recent analytical studies have revealed that chlorination of water produces numerous disinfection by-products (DBPs) after the reaction of residual chlorine with natural organic compounds such as humic and fulvic acids in water. Many of such DBPs have been reported to be mutagenic/ carcinogenic. To overcome this problem, there is a pressing need to replace chlorination with a safer and appropriate alternative process.

Certain metals like mercury, silver and copper with an oligodynamic property have been found to be biocidal with the capability to disinfect the water. Among these, silver is more appropriate as it is non-toxic and an efficient water disinfectant. Silver has been known as an effective biocide against viruses, bacteria, protozoa, algae, yeasts and moulds. Silver has strength, malleability, ductility, high reflectance of light, temperature resistance and electrical as well as thermal conductivity. Silver is used for electroplating, currency, ornaments, utensils, mirror plating, sweet coating, photography, electrical/electronic instrumentation, solar energy, medical (dental) applications and scientific research. The use of pots and pitchers made up of silver for storage of drinking water is an age-old tradition which indicates that its bactericidal property was well known to our ancestors.

2.     SILVER AS DISINFECTANT

The antimicrobial effects of silver (Ag) have been recognized for thousands of years. In ancient times, it was used in water containers and to prevent putrefaction of liquids and foods. In ancient times in Mexico, water and milk were kept in silver containers. Silver was also mentioned in the Roman pharmacopoeia of 69 B.C.

In 1884, silver nitrate drops were introduced as a prophylactic treatment for the eyes of new-borns, and this became a common practice in many countries throughout the world to prevent infections caused by Neisseria gonorrhoeae transmitted from infected mothers during childbirth. In 1928, the “Katadyn Process” based on the use of silver in water at low concentrations, was introduced.

Silver ions have the highest level of antimicrobial activity of all the heavy metals. Gram-negative bacteria appear to be more sensitive than gram-positive species. Kawahara et al. posited that some silver binds to the negatively charged peptidoglycan of the bacterial cell wall. Because gram-positive species have a thicker peptidoglycan layer than do gram-positive species, perhaps more of the silver is prevented from entering the cell.

Generally speaking, the observed bactericidal efficacy of silver and its associated ions is through the strong binding with disulphide (S–S) and sulfhydryl (–SH) groups found in the proteins of microbial cell walls. Through this binding event, normal metabolic processes are disrupted, leading to cell death. The antimicrobial metals silver (Ag), copper (Cu), and zinc (Zn) have thus found their way into a number of applications.

2.1.  Applications And Uses

a)      Drinking Water

Chlorine has been used as the principal disinfectant for drinking water since the early 1900s. In the 1970s, it was discovered that chlorination caused the formation of numerous chlorinated compounds in water, including trihalo-methanes and other disinfection by-products (DPB), that are known to be hazardous to human health. There is therefore a need to assess alternative disinfectants.

Silver electrochemistry experiments suggest that silver may have potential as a chlorine alternative in drinking water disinfection in applications in which chlorine may be considered too hazardous. Silver has been used as an effective water disinfectant for many decades, primarily in Europe. It has also been used to treat recycled water aboard the MIR space station and aboard NASA space shuttles.

Both the Environmental Protection Agency (EPA) and the World Health Organization (WHO) regard silver as safe for human consumption. Only argyria (irreversible skin discoloration) occurs with the ingestion of gram quantities of silver over several years or by the administration of high concentrations to ill individuals. There have been no reports of argyria or other toxic effects caused by silver in healthy persons (World Health Organization 1996). Based on epidemiological and pharmacokinetic data, a lifetime limit of 10 grams of silver can be considered a No Observable Adverse Effect Level (NOAEL) for humans (World Health Organization 1996). In the United States, no primary standards exist for silver as a component in drinking water. The EPA recommends a secondary non-enforceable standard of 0.1 mg/L (100 ppb) (Environmental Protection Agency 2002). The World Health Organization (1996) has stated this amount of silver in water disinfection could easily be tolerated because the total absorbed dose would only be half of the NOAEL after 70 years. Silver has been used as an integral part of EPA- and National Sanitation Foundation (NSF)-approved point-of-use (POU) water filters to prevent bacterial growth. Home water purification units (e.g., faucet-mounted devices and water pitchers) in the United States contain silverized activated carbon filters along with ion-exchange resins (Gupta et al. 1998). Today, some 50 million consumers obtain drinking water from POU devices that utilize silver (Water Quality Association 2001). These products leach silver at low levels (1–50 ppb) with no known observable adverse health effects. Such filters have been shown to prevent the growth of Pseudomonas flu-rescens and Pseudomonas aeruginosa in water; however, several studies have raised questions about their efficacy. Reasoner et al. (1987) established that bacterial colonization of such devices occurs within a matter of days and may result in a large number of bacteria in the product water.

b)     Cooling Towers/Large Building Water Distribution Systems

Cooling towers provide cooling water for air compressors and industrial processes that generate heat. They provide an ideal environment and a suitable balance of nutrients for microbial multiplication. Chlorine is a popular method for controlling such bacterial growth, but there are difficulties in maintaining disinfection efficacy, particularly at a high temperature or pH. Chlorination can also cause corrosion of cooling tower facilities.

Ag/Cu ionization has been used in cooling towers to control bacterial growth. In a study by Martinez et al. (2004), an appreciably reduced chlorine concentration of 0.3 parts per million (ppm or mg/L) was combined with 200 ppb Ag and 1.2 ppm Cu. This method had an appreciable impact on levels of coliform bacteria, iron-related bacteria, sulphate-reducing bacteria and slime-forming bacteria in a cooling tower.

Large hot water distribution systems in hospitals and hotels have also often been attributed as a source of contaminating bacteria.  Contaminated systems are usually treated by either superheating the water with flushing of the distal sites (heat-flush), by hyper chlorination, or by installing Ag/Cu ionization units. Greater bacterial reductions have been observed with Ag/Cu ionization than with the heat-flush method. Ag/Cu ionization is known to provide long-term control and may be used in older buildings in which the pipes could be damaged by hyper chlorination. Such systems are easy to install and maintain, are relatively inexpensive, and do not produce toxic by-products.

One microorganism that has been commonly isolated from cooling towers is Legionella pneumophila, the causative agent of Legionnaires’ disease. Many outbreaks have been linked to cooling towers and evaporative condensers. L. pneumophila is also commonly isolated from the periphery of hot water systems in large buildings such as hospitals, hotels, and apartment buildings where temperatures tend to be lower. Ag/Cu systems have been in common use in hospitals to control Legionella for more than a decade. Mietzner et al. reported that one such ionization system maintained effective control of L. pneu-mophila for at least 22 mon. Legionella may develop a tolerance to silver after a period of years, requiring higher concentrations to achieve the same effect.

c)  Recreational Waters

Bacteria, protozoa, and viruses may occur naturally in recreational waters or be introduced into swimming pools by bathers or through faulty connections between the filtration and sewer systems. Species carried by bathers include the intestinal Streptococcus faecalis and Escherichia coli, as well as skin, ear, nose, and throat organisms such as Staphylococcus aureus, Staphylococcus epidermidis, Streptococcus salivarius, Pseudomonas aeruginosa, and Mycobacterium marinum (Singer 1990). Mild to serious illnesses caused by inges

Monitor VMware ESXi hardware without root (Nagios)

Download and configure the plugin: http://exchange.nagios.org/directory/Plugins/Operating-Systems/*-Virtual-Environments/VMWare/check_esxi_hardware-2Epy/

– Create a new user in ESXi with no access privilege, you need to login to the ESXi directly to do that.

user

esxi_access

– Enable SSH, and add nagios user to root group:
# vi /etc/group
root:x:0:root,nagios

– Check from the command line, if it works
./check_esxi_hardware.py --host https://esxihost:5989 --user file:credentials.txt --pass file:credentials.txt
OK - Server: Cisco Systems Inc.....

– Configure the credentials files to use the nagios user credentials.

Setup GeoIP (PECL) for piwik geolocation and updating old visits

GeoIP is the recommended way to accurately determine the location of the visitor, by default geolocation settings may provide in accurate result.

To enable GeoIP(PECL) from redhat/centos machines:
# yum install php-pecl-geoip
#apachectl restart
# php -m | grep -i geo
geoip

From Piwik, Settings –> Geolocation –> GeoIP (PECL)

To reindex the old visits:
# cd misc/others
# php ./geoipUpdateRows.php
[note] Found working provider: geoip_pecl
90094 rows to process in piwik_log_visit and piwik_log_conversion....
.
.
.
100% done!

Error when trying to FTP !

When trying to FTP-in, facing this error ? :

=================

Status: Resolving address of xxxxxxxxxxxxxxx.com
Status: Connecting to xx.xx.xx.xx:21…
Status: Connection established, waiting for welcome message…
Response: 421 Too many connections (x) from this IP
ons (x) from this IP

=================

As the logs indicate, the limit for connections from the IP you are trying
to login has reached its maximum value.

Increase this from the configuration file, the value 'MaxClientsPerIP'
( if its pure-ftp ) or 'MaxClientsPerHost' ( pro-ftpd)
and restart the service.

Alternatively, you can also terminate the existing connections, if they are not in use.
# netstat -plan | grep :21 and kill the corresponding process
( # kill -9 PID )

Error when enabling SMTP Restrictions – cPanel/WHM

SMTP restrictions prevent users from bypassing your mail server to send mail.
This feature allows you to configure your server so that the mail
transport agent (MTA), Mailman mailing list software, and root user
are the only accounts able to connect to remote SMTP servers.

Enable from WHM as :

Home >> Security Center >> SMTP Restrictions

When doing so, do you face this error ?

An error occurred attempting to update this setting.
The SMTP restriction is disabled.

When trying to do it from backend,

# /scripts/smtpmailgidonly on

SMTP Mail protection has been disabled. All users may make smtp connections.
There was a problem setting up iptables. You either have an older kernel or a
broken iptables install, or ipt_owner could not be loaded.

In Most cases, the required iptables module, ‘ipt_owner’ would be disabled.
You can confirm it by running # /etc/csf/csftest.pl

If your’s is a VPS, ask the provider to enable it for you, or if
you manage your server, enable it using the command :

# modprobe ipt_owner

Send attachments from command line with mutt

To send e-mails from command line with attachments using mutt.

Set the from address with EMAIL=
-s – Subject
-a – attachment file
recipient name
-c – for CC
-b – for BCC
create a text file (eg: /tmp/testmessage) , with the body of the message.

EMAIL="foo@bar" mutt -s "Subject" -a test.doc foo1@bar -c foo2@bar < /tmp/testmessage

Issue with NTP servers — The new DDoS target !!

Just like the DDoS is hitting web-servers and DNS servers, it has started hitting
the ntpd servers which are left open.

This is a very recent attack. The Network Time Protocol, or NTP, syncs time
between machines on the network, and runs over port 123 UDP. It’s typically
configured once by network administrators and often is not updated.

Recently there is a major jump in attacks via the protocol. Attackers appear to be
employing NTP for DDoSing similar to the way DNS is being abused in such attacks.
They transmit small spoofed packets requesting a large amount of data sent to the
DDoS target’s IP address. It’s all about abusing the so-called “monlist” command
in an older version of NTP. Monlist returns a list of the last 600 hosts that have
connected to the server.

To check if your ntp service is open/vulernable :

# ntpdc -c monlist IP ( See if it returns the list of hosts,
if it does, it is vulnerable )

To get around this,

# The easiest way to update to NTP version 4.2.7, which removes the monlist
command entirely.

# If upgrading is not an option, you can start the NTP daemon with noquery enabled
in the NTP conf file. This will disable access to mode 6 and 7 query
packets (which includes monlist).

Add the below lines to /etc/ntp.conf :

========

restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery

========

If monolist query is disabled,

# ntpdc -n -c monlist IP should return,

xx.xx.xx.xx: timed out, nothing received
***Request timed out

The basic issue is that all the ntp servers are left open, meaning any servers
can query them. For eg we have the following part in the config
file of a ntpd server :

============

# — CLIENT NETWORK ——-

============

– under this portion, either nothing would be given ( which means all can access/query )
or the following,

restrict 192.168.1.0 mask 255.255.255.0 notrust nomodify notrap

which means all can still access/query, in particular that range specified cannot do the
above 3 actions.

still this makes them an open ntpd service, which responds to the queries.

If the following was given,

restrict 192.168.1.0 mask 255.255.255.0 notrust noquery nomodify notrap

it implies all systems under the above n/w segment can access, but cannot
query, –similar to the 2 liner which is given irrespective of all n/w segments.

Before you become a part in the chain, take the preventive measures.

Apache error_log – piling up with PHP errors ?

Is error_log associated with a domain piling up in huge size ?

Check the contents of it and see if its something like this :

=============

[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JDispatcher::getInstance() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JLoader::load() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JLoader::register() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JPluginHelper::_import() should not be called statically in
[07-Feb-2014 00:19:15 America/New_York] PHP Strict Standards: Non-static method JLoader::import() should not be called statically in

……….
……….

=============

We can see that it is reporting PHP Strict-Standards errors.
As each and every strict standard errors is being reported,
error_log is consuming huge amount of space.

This is a change which has been seen in the newer version of PHP, ( PHP 5.4 )
which now reports E_STRICT errors on default.

To get around this issue, disable error reporting for strict standards,
by adding the below line to PHP configuration file.

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

Could not connect to https://vcenter_address:7331/

This usually happens from the vSphere web client while opening a console session with virtual machine.

and the log (/var/log/vmware/vsphere-client/logs/vsphere_client_virgo.log) shows something like:

[ERROR] Thread-42 System.err
INFO:oejsh.ContextHandler:started o.e.j.w.WebApp Context{/console,file:/tmp/jetty-0.0.0.0-7331-console.war-_console-any-/webapp/},/usr/lib/vmware-vsphere-client/server/work/tmp/console-distro/webapps/console.war

To fix this set the environment variable VMWARE_JAVA_HOME to proper path:

– SSH to vcenter
# vi /usr/lib/vmware-vsphere-client/server/wrapper/conf/wrapper.conf

– Under Environment variables add:
set.default.VMWARE_JAVA_HOME=/usr/java/jre-vmware

– Restart vsphere-client
# /etc/init.d/vsphere-client restart
Stopping VMware vSphere Web Client...
Stopped VMware vSphere Web Client.
Starting VMware vSphere Web Client...
Intializing registration provider...
Getting SSL certificates
Service with name was updated.
Return code is: Success
Waiting for VMware vSphere Web Client......
running: PID:

Reference: http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2060604

An issue with exim — mails not getting delivered to certain mail-servers

Facing an issue with exim, that it doesn’t send any mails to certain SMTP server’s like gmail etc?

First place to check is the /var/log/exim_mainlog and see if you can spot something like this

=============

-bash-3.2# grep 1W6OuM-0005cl-J8 /var/log/exim_mainlog
2014-01-23 19:21:42 1W6OuM-0005cl-J8 <= root@host.xxxx. U=root P=local S=350 T=”test mail” for test@gmail.com
2014-01-23 19:21:42 cwd=/var/spool/exim 4 args: /usr/sbin/exim -v -Mc 1W6OuM-0005cl-J8
2014-01-23 19:21:42 1W6OuM-0005cl-J8 gmail-smtp-in.l.google.com [xxxx:abcd:xxxx:xab::xa] Network is unreachable
2014-01-23 19:21:43 1W6OuM-0005cl-J8 Completed

============

You can see that exim is trying to send outgoing emails via IPv6 . It happens if the recipient server supports it, ( gmail supports it ) as a result mail delivery gets affected or the mails reach junk/spam folder.

If IPv6 delivery is not intended and DNS records for the same are not configured, then the recipient SMTP server would not be able to obtain a reverse DNS entry of the sending IP ( IP in IPv6 ) and as a result it affects the mail delivery.

To get around this, either configure your IPv6 DNS entries or just force exim to send mails only via IPv4 by adding the below line to the exim config file ( /etc/exim.conf

disable_ipv6 = true

Finally restart exim.

Create bootable USB on OSX

– Identify the disk number for the USB disk inserted, usually you can find it from the “Name” and “Size” field.
Below eg: , We inserted a USB with 4.1 GB size (so as the identified: “disk2”.)
Open terminal and execute the following commands:

sh-3.2$ diskutil list
/dev/disk0
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:      GUID_partition_scheme                        *120.0 GB   disk0
1:                        EFI EFI                     209.7 MB   disk0s1
2:          Apple_CoreStorage                         119.0 GB   disk0s2
3:                 Apple_Boot Recovery HD             650.0 MB   disk0s3
/dev/disk1
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:                  Apple_HFS Macintosh HD           *118.7 GB   disk2
/dev/disk2
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:                            UNTITLED        *4.1 GB     disk2

– Unmount the disk
sh-3.2$ diskutil unmountDisk /dev/disk3
Unmount of all volumes on disk3 was successful

– write the ISO file to USB using dd command
sh-3.2$ sudo dd if=Downloads/ubuntu-12.04.3-desktop-i386.iso of=/dev/disk2 bs=1m
Password:
707+0 records in
707+0 records out
741343232 bytes transferred in 139.059398 secs (5331126 bytes/sec)

– Unmount the disk
sh-3.2$ diskutil eject /dev/disk3
Disk /dev/disk3 ejected

vCenter Converter

Convert Linux Physical Server to VMware virtual machine

Download and install vCenter Converter on a windows machine.
http://www.vmware.com/products/converter
Unfortunately this tool does not have a Linux / MAC version.

vCenter Converter

vCenter Converter

In case you see an error: “Permission to perform this operation was denied”, right click and run the program as Administrator.

Permission to perform this operation was denied
Provide the source and destination information, the source is the physical server to be converted and the destination vCenter.
vCenter Converter

vCenter Converter

vCenter Converter

vCenter Converter

Follow the steps, to do the conversion , a temporary OS will be started on the destination, by default it try to get an IP address from the DHCP server so that it can connect to the source machine and fetch the files required. But in case if you don’t have DHCP server you might see error like: “Unable to obtain the IP address of the helper virtual machine” . Fix this issue by setting up a static IP to the helper virtual machine during the conversion setup. Basically the helper VM IP should be able to communicate with the source machine which needs to be migrated

vCenter Converter Static IP

vCenter Converter Static IP

Proceed with the conversion, the duration will be based on the size of the VM and the connectivity if it belongs to another site/LAN.

You may need to change the network configuration (eg: HWADDR) and the MAC address mapping (/etc/udev/rules.d) to get it connected.

Useful MySQL commands

To find MySQL root/admin pass :

cPanel server           : cat /root/.my.cnf ( username : root )
Plesk server             : cat /etc/psa/.psa.shadow ( username : admin )
DirectAdmin server  : cat /usr/local/directadmin/conf/mysql.conf

To login to MySQL :

mysql -u 'username' -p ( will prompt for password )
Password:

To create MySQL dump of a database :

mysqldump -u 'username' -p dbname > database_name.sql ( will prompt for password )

To create MySQL dump of all databases :

mysqldump -u 'username' -p --all-databases > all_databases.sql ( will prompt for password )

To restore all databases from the MySQL dump :

mysql -u username -p < all_databases.sql ( will prompt for password )

To restore a MySQL dump for a database :

mysql -u 'username' -p dbname < database_name.sql ( will prompt for password )

To restore a single database from dump of all databases :

mysql -u 'username' -p --one-database dbname < all_databases.sql ( will prompt for password )

To create MySQL dump of a single table in a database :

mysqldump -u 'username' -p dbname table_name > table_name.sql ( will prompt for password )

To restore the above table from MySQL dump :

mysql -u 'username' -p dbname < /path/to/table_name.sql ( will prompt for password )

One liner to truncate all tables in a db from MySQL :

mysql -Nse 'show tables' DBNAME | while read table;
do mysql -e "truncate table $table" DBNAME; done

One liner to drop all tables in a db from MySQL :

mysql -Nse 'show tables' DBNAME | while read table;
do mysql -e "drop table $table" DBNAME; done