Thursday 24 October 2013

35 Linux Find Commands Examples

The Linux Find Command is one of the most important and much used command in Linux sytems. Find command used to search and locate list of files and directories based on conditions you specify for files that match the arguments. Find can be used in variety of conditions like you can find files by permissions, users, groups, file type, date, size and other possible criteria.

35 Linux Find Commands Examples
Through this article we are sharing our day-to-day Linux find command experience and its usage in the form of examples. In this article we will show you the most used 35 Find Commands examples in Linux. We have divided the section into Five parts from basic to advance usage of find command.

  1. Part I: Basic Find Commands for Finding Files with Names
  2. Part II: Find Files Based on their Permissions
  3. Part III: Search Files Based On Owners and Groups
  4. Part IV: Find Files and Directories Based on Date and Time
  5. Part V: Find Files and Directories Based on Size
Part I – Basic Find Commands for Finding Files with Names

1. Find Files Using Name in Current Directory

Find all the files whose name is tecmint.txt in a current working directory.
# find . -name tecmint.txt

./tecmint.txt

2. Find Files Under Home Directory

Find all the files under /home directory with name tecmint.txt.
# find /home -name tecmint.txt

/home/tecmint.txt

3. Find Files Using Name and Ignoring Case

Find all the files whose name is tecmint.txt and contains both capital and small letters in /home directory.
# find /home -iname tecmint.txt

./tecmint.txt
./Tecmint.txt

4. Find Directories Using Name

Find all directories whose name is Tecmint in / directory.
# find / -type d -name Tecmint

/Tecmint

5. Find PHP Files Using Name

Find all php files whose name is tecmint.php in a current working directory.
# find . -type f -name tecmint.php

./tecmint.php

6. Find all PHP Files in Directory

Find all php files in a directory.
# find . -type f -name "*.php"

./tecmint.php
./login.php
./index.php
Part II – Find Files Based on their Permissions

7. Find Files With 777 Permissions

Find all the files whose permissions are 777.
# find . -type f -perm 0777 -print

8. Find Files Without 777 Permissions

Find all the files without permission 777.
# find / -type f ! -perm 777

9. Find SGID Files with 644 Permissions

Find all the SGID bit files whose permissions set to 644.
# find / -perm 2644

10. Find Sticky Bit Files with 551 Permissions

Find all the Sticky Bit set files whose permission are 551.
# find / -perm 1551

11. Find SUID Files

Find all SUID set files.
# find / -perm /u=s

12. Find SGID Files

Find all SGID set files.
# find / -perm /g+s

13. Find Read Only Files

Find all Read Only files.
# find / -perm /u=r

14. Find Executable Files

Find all Executable files.
# find / -perm /a=x

15. Find Files with 777 Permissions and Chmod to 644

Find all 777 permission files and use chmod command to set permissions to 644.
# find / -type f -perm 0777 -print -exec chmod 644 {} \;

16. Find Directories with 777 Permissions and Chmod to 755

Find all 777 permission directories and use chmod command to set permissions to 755.
# find / -type d -perm 777 -print -exec chmod 755 {} \;

17. Find and remove single File

To find a single file called tecmint.txt and remove it.
# find . -type f -name "tecmint.txt" -exec rm -f {} \;

18. Find and remove Multiple File

To find and remove multiple files such as .mp3 or .txt, then use.
# find . -type f -name "*.txt" -exec rm -f {} \;

OR

# find . -type f -name "*.mp3" -exec rm -f {} \;

19. Find all Empty Files

To file all empty files under certain path.
# find /tmp -type f -empty

20. Find all Empty Directories

To file all empty directories under certain path.
# find /tmp -type d -empty

21. File all Hidden Files

To find all hidden files, use below command.
# find /tmp -type f -name ".*"
Part III – Search Files Based On Owners and Groups

22. Find Single File Based on User

To find all or single file called tecmint.txt under / root directory of owner root.
# find / -user root -name tecmint.txt

23. Find all Files Based on User

To find all files that belongs to user Tecmint under /home directory.
# find /home -user tecmint

24. Find all Files Based on Group

To find all files that belongs to group Developer under /home directory.
# find /home -group developer

25. Find Particular Files of User

To find all .txt files of user Tecmint under /home directory.
# find /home -user tecmint -iname "*.txt"
Part IV – Find Files and Directories Based on Date and Time

26. Find Last 50 Days Modified Files

To find all the files which are modified 50 days back.
# find / -mtime 50

27. Find Last 50 Days Accessed Files

To find all the files which are accessed 50 days back.
# find / -atime 50

28. Find Last 50-100 Days Modified Files

To find all the files which are modified more than 50 days back and less than 100 days.
# find / -mtime +50 –mtime -100

29. Find Changed Files in Last 1 Hour

To find all the files which are changed in last 1 hour.
# find / -cmin -60

30. Find Modified Files in Last 1 Hour

To find all the files which are modified in last 1 hour.
# find / -mmin -60

31. Find Accessed Files in Last 1 Hour

To find all the files which are accessed in last 1 hour.
# find / -amin -60
Part V – Find Files and Directories Based on Size

32. Find 50MB Files

To find all 50MB files, use.
# find / -size 50M

33. Find Size between 50MB – 100MB

To find all the files which are greater than 50MB and less than 100MB.
# find / -size +50M -size -100M

34. Find and Delete 100MB Files

To find all 100MB files and delete them using one single command.
# find / -size +100M -exec rm -rf {} \;

35. Find Specific Files and Delete

Find all .mp3 files with more than 10MB and delete them using one single command.
# find / -type f -name *.mp3 -size +10M -exec ls -l {} \;
That’s it, We are ending this post here, In our next article we will discuss more about other Linux commands in depth with practical examples. Let us know your opinions on this article using our comment section.

A tcpdump Primer

Source: http://danielmiessler.com/study/tcpdump/#.UmeB19dHniw

tcp_header
Image from securitywizardry.com
tcpdump is the premier network analysis tool for information security professionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP. Many prefer to use higher level analysis tools such as Ethereal Wireshark, but I believe this to usually be a mistake.
In a discipline so dependent on a true understanding of concepts vs. rote learning, it's important to stay fluent in the underlying mechanics of the TCP/IP suite. A thorough grasp of these protocols allows one to troubleshoot at a level far beyond the average analyst, but mastery of the protocols is only possible through continued exposure to them.
When using a tool that displays network traffic a more natural (raw) way the burden of analysis is placed directly on the human rather than the application. This approach cultivates continued and elevated understanding of the TCP/IP suite, and for this reason I strongly advocate using tcpdump instead of other tools whenever possible.
15:31:34.079416 IP (tos 0x0, ttl  64, id 20244, offset 0, flags [DF], 
proto: TCP (6), length: 60) source.35970 > dest.80: S, cksum 0x0ac1 
(correct), 2647022145:2647022145(0) win 5840 0x0000:  4500 003c 4f14 4000 
4006 7417 0afb 0257  E..  0x0010:  4815 222a 8c82 0050 9dc6 5a41 0000 
0000  H."*...P..ZA....  0x0020:  a002 16d0 0ac1 0000 0204 05b4 
0402 080a  ................  0x0030:  14b4 1555 0000 0000 0103 0302

Options

Below are a few options (with examples) that will help you greatly when working with the tool. They're easy to forget and/or confuse with other types of filters, i.e. ethereal, so hopefully this page can serve as a reference for you, as it does me.
First off, I like to add a few options to the tcpdump command itself, depending on what I'm looking at. The first of these is -n, which requests that names are not resolved, resulting in the IPs themselves always being displayed. The second is -X, which displays both hex and ascii content within the packet. The final one is -S, which changes the display of sequence numbers to absolute rather than relative. The idea there is that you can't see weirdness in the sequence numbers if they're being hidden from you. Remember, the advantage of using tcpdump vs. another tool is getting manual interaction with the packets.
It's also important to note that tcpdump only takes the first 68 96 bytes of data from a packet by default. If you would like to look at more, add the -s number option to the mix, where number is the number of bytes you want to capture. I recommend using 0 (zero) for a snaplength, which gets everything. Here's a short list of the options I use most:
  • -i any : Listen on all interfaces just to see if you're seeing any traffic.
  • -n : Don't resolve hostnames.
  • -nn : Don't resolve hostnames or port names.
  • -X : Show the packet's contents in both hex and ASCII.
  • -XX : Same as -X, but also shows the ethernet header.
  • -v, -vv, -vvv : Increase the amount of packet information you get back.
  • -c : Only get x number of packets and then stop.
  • -s : Define the snaplength (size) of the capture in bytes. Use -s0 to get everything, unless you are intentionally capturing less.
  • -S : Print absolute sequence numbers.
  • -e : Get the ethernet header as well.
  • -q : Show less protocol information.
  • -E : Decrypt IPSEC traffic by providing an encryption key.
[ The default snaplength as of tcpdump 4.0 has changed from 68 bytes to 96 bytes. While this will give you more of a packet to see, it still won't get everything. Use -s 1514 to get full coverage ]

Basic Usage

So, based on the kind of traffic I'm looking for, I use a different combination of options to tcpdump, as can be seen below:
  1. Basic communication // see the basics without many options
    # tcpdump -nS

  2. Basic communication (very verbose) // see a good amount of traffic, with verbosity and no name help
    # tcpdump -nnvvS

  3. A deeper look at the traffic // adds -X for payload but doesn't grab any more of the packet
    # tcpdump -nnvvXS
  4. Heavy packet viewing // the final "s" increases the snaplength, grabbing the whole packet
    # tcpdump -nnvvXSs 1514
Here's a capture of exactly two (-c2) ICMP packets (a ping and pong) using some of the options described above. Notice how much we see about each packet.
hermes root # tcpdump -nnvXSs 0 -c2 icmp
tcpdump: listening on eth0, link-type EN10MB (Ethernet), 23:11:10.370321 IP 
(tos 0x20, ttl  48, id 34859, offset 0, flags [none], length: 84) 
69.254.213.43 > 72.21.34.42: icmp 64: echo request seq 0

        0x0000:  4520 0054 882b 0000 3001 7cf5 45fe d52b  E..T.+..0.|.E..+
        0x0010:  4815 222a 0800 3530 272a 0000 25ff d744  H."*..50'*..%..D
        0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
        0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
        0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
        0x0050:  3435 3637                                4567
23:11:10.370344 IP (tos 0x20, ttl  64, id 35612, offset 0, flags [none], 
length: 84) 72.21.34.42 > 69.254.213.43: icmp 64: echo reply seq 0
        0x0000:  4520 0054 8b1c 0000 4001 6a04 4815 222a  E..T....@.j.H."*
        0x0010:  45fe d52b 0000 3d30 272a 0000 25ff d744  E..+..=0'*..%..D
        0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
        0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
        0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
        0x0050:  3435 3637                                4567
2 packets captured
2 packets received by filter
0 packets dropped by kernel
hermes root # 

Common Syntax

Expressions allow you to trim out various types of traffic and find exactly what you're looking for. Mastering the expressions and learning to combine them creatively is what makes one truly powerful with tcpdump. There are three main types of expression: type, dir, and proto.
Type options are host, net, and port. Direction is indicated by dir, and there you can have src, dst, src or dst, and src and dst. Here are a few that you should definitely be comfortable with:
  • host // look for traffic based on IP address (also works with hostname if you're not using -n)
    # tcpdump host 1.2.3.4

  • src, dst // find traffic from only a source or destination (eliminates one side of a host conversation)
    # tcpdump src 2.3.4.5
    # tcpdump dst 3.4.5.6

  • net // capture an entire network using CIDR notation
    # tcpdump net 1.2.3.0/24

  • proto // works for tcp, udp, and icmp. Note that you don't have to type proto
    # tcpdump icmp

  • port // see only traffic to or from a certain port
    # tcpdump port 3389

  • src, dst port // filter based on the source or destination port
    # tcpdump src port 1025
    # tcpdump dst port 389

  • src/dst, port, protocol // combine all three
    # tcpdump src port 1025 and tcp
    # tcpdump udp and src port 53
You also have the option to filter by a range of ports instead of declaring them individually, and to only see packets that are above or below a certain size.
  • Port Ranges // see traffic to any port in a range
    tcpdump portrange 21-23

  • Packet Size Filter // only see packets below or above a certain size (in bytes)
    tcpdump less 32
    tcpdump greater 128
  • [ You can use the symbols for less than, greater than, and less than or equal / greater than or equal signs as well. ]
    // filtering for size using symbols
    tcpdump > 32
    tcpdump <= 128

Writing to a File

tcpdump allows you to send what you're capturing to a file for later use using the -w option, and then to read it back using the -r option. This is an excellent way to capture raw traffic and then run it through various tools later.
The traffic captured in this way is stored in tcpdump format, which is pretty much universal in the network analysis space. This means it can be read in by all sorts of tools, including Wireshark, Snort, etc.

Capture all Port 80 Traffic to a File

# tcpdump -s 1514 port 80 -w capture_file
Then, at some point in the future, you can then read the traffic back in like so:

Read Captured Traffic back into tcpdump

# tcpdump -r capture_file

Getting Creative

Expressions are nice, but the real magic of tcpdump comes from the ability to combine them in creative ways in order to isolate exactly what you're looking for. There are three ways to do combinations, and if you've studied computers at all they'll be pretty familar to you:
  1. AND
    and or &&
  2. OR
    or or ||
  3. EXCEPT
    not or !

More Examples

# TCP traffic from 10.5.2.3 destined for port 3389
tcpdump -nnvvS and src 10.5.2.3 and dst port 3389
# Traffic originating from the 192.168 network headed for the 10 or 172.16 networks
tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or 172.16.0.0/16
# Non-ICMP traffic destined for 192.168.0.2 from the 172.16 network
tcpdump -nvvXSs 1514 dst 192.168.0.2 and src net and not icmp
# Traffic originating from Mars or Pluto that isn't to the SSH port
tcpdump -vv src mars and not dst port 22
As you can see, you can build queries to find just about anything you need. The key is to first figure out precisely what you're looking for and then to build the syntax to isolate that specific type of traffic.

Grouping

Also keep in mind that when you're building complex queries you might have to group your options using single quotes. Single quotes are used in order to tell tcpdump to ignore certain special characters -- in this case the "( )" brackets. This same technique can be used to group using other expressions such as host, port, net, etc. Take a look at the command below:
# Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (incorrect)
tcpdump src 10.0.2.4 and (dst port 3389 or 22)
If you tried to run this otherwise very useful command, you'd get an error because of the parenthesis. You can either fix this by escaping the parenthesis (putting a \ before each one), or by putting the entire command within single quotes:
# Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (correct)
tcpdump 'src 10.0.2.4 and (dst port 3389 or 22)'

Advanced

You can also filter based on specific portions of a packet, as well as combine multiple conditions into groups. The former is useful when looking for only SYNs or RSTs, for example, and the latter for even more advanced traffic isolation.
[ Hint: An anagram for the TCP flags: Unskilled Attackers Pester Real Security Folk ]
Show me all URGENT (URG) packets...
# tcpdump 'tcp[13] & 32!=0'
Show me all ACKNOWLEDGE (ACK) packets...
# tcpdump 'tcp[13] & 16!=0'
Show me all PUSH (PSH) packets...
# tcpdump 'tcp[13] & 8!=0'
Show me all RESET (RST) packets...
# tcpdump 'tcp[13] & 4!=0'
Show me all SYNCHRONIZE (SYN) packets...
# tcpdump 'tcp[13] & 2!=0'
Show me all FINISH (FIN) packets...
# tcpdump 'tcp[13] & 1!=0'
Show me all SYNCHRONIZE/ACKNOWLEDGE (SYNACK) packets...
# tcpdump 'tcp[13]=18'
[ Note: Only the PSH, RST, SYN, and FIN flags are displayed in tcpdump's flag field output. URGs and ACKs are displayed, but they are shown elsewhere in the output rather than in the flags field ]
Keep in mind the reasons these filters work. The filters above find these various packets because tcp[13] looks at offset 13 in the TCP header, the number represents the location within the byte, and the !=0 means that the flag in question is set to 1, i.e. it's on.
As with most powerful tools, however, there are multiple ways to do things. The example below shows another way to capture packets with specific TCP flags set.
Capture TCP Flags Using the tcpflags Option...
# tcpdump 'tcp[tcpflags] & & tcp-syn != 0'

Specialized Traffic

Finally, there are a few quick recipes you'll want to remember for catching specific and specialized traffic, such as IPv6 and malformed/likely-malicious packets.
IPv6 traffic
# tcpdump ip6
Packets with both the RST and SYN flags set (why?)
# tcpdump 'tcp[13] = 6'
Traffic with the 'Evil Bit' Set
# tcpdump 'ip[6] & 128 != 0'

Conclusion

Well, this primer should get you going strong, but the man page should always be handy for the most advanced and one-off usage scenarios. I truly hope this has been useful to you, and feel free to contact me if you have any questions. ::

How to remove vmware workstation


#vmware-installer -l
This will list the installed vmware product with version

#vmware-installer -u vmware-workstation 8.0.0.471780
where  "vmware-workstation 8.0.0.471780" is your vmware product name and version

Wednesday 16 October 2013

wget – recursively download all files from certain directory listed by apache

source:
http://bmwieczorek.wordpress.com/2008/10/01/wget-recursively-download-all-files-from-certain-directory-listed-by-apache/


Case: recursively download all the files that are in the ‘ddd’  folder for the url ‘http://hostname/aaa/bbb/ccc/ddd/&#8217;
Solution:
wget -r -np -nH –cut-dirs=3 -R index.html http://hostname/aaa/bbb/ccc/ddd/
Explanation:
It will download all files and subfolders in ddd directory:
recursively (-r),
not going to upper directories, like ccc/… (-np),
not saving files to hostname folder (-nH),
but to ddd by omitting first 3 folders aaa, bbb, ccc (–cut-dirs=3),
excluding index.html files (-R index.html)

Monday 14 October 2013

Session Initiation Protocol (SIP) Basic Call Flow Examples

http://tools.ietf.org/html/rfc3665

run vlc as root (CENTOS 6)

Use okteta to find "geteuid" and replace it with "getppid". Save file. Done.

Check listening port with netstat

Checking Listening Ports with netstat


netstat

If you're troubleshooting a service that you know is running normally the next step is to make sure it's listening to the right network port.
The netstat command shows the services listening to ports on a Linux server along with the details of any connections currently made to them. The connection details we look at during basic network daemon troubleshooting are the addresses the daemon is listening on (including the port number), the daemon's PID (process identifier), and the program name.
Of course, you need to run netstat on the server running the service. Remember that netstat is not affected by your firewall configuration.

Checking ports

To list tcp ports that are being listened on, along with the name of each listener's daemon and its PID, run:
sudo netstat -plnt
The following example shows netstat's output for three common programs that are listening on three different sockets.
$ sudo netstat -plnt 
Active Internet connections (only servers) 
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      3686/mysqld            
tcp        0      0 :::443                      :::*                        LISTEN      2218/httpd          
tcp        0      0 :::80                       :::*                        LISTEN      2218/httpd          
tcp        0      0 :::22                       :::*                        LISTEN      1051/sshd

Filtering the list

If the list of listening daemons is long you can use grep to filter it. For example, to filter out everything except the default web server port - number 80 – run:
$ sudo netstat -plnt | grep ':80'     
tcp        0      0 :::80                       :::*                        LISTEN      8448/httpd

Analysing the results

Common outcomes are:
  • Nothing is listening on the port. Check the service configuration files then try restarting the service.
  • The correct service is listening on the correct port. In this case we need to test the service more thoroughly - skip to the article on testing the listening service for response using netcat.
  • Something other than the expected service appears to be listening on the port.
Note: If a super-server, such as xinetd, is listening on the port this may be desired. See above for details on looking at your xinetd configuration.
If something else is listening to the port, try disabling that program, e.g. "sudo service httpd stop", or changing its configuration so it no longer listens on the required port. Then enable the correct service when netstat shows the port is free, e.g. "sudo service vsftpd start".
If you make any changes because the incorrect service is listening or nothing is, run the netstat command again to see if it has made a difference. If netstat doesn't show the program listening on the correct port you need to address its configuration before you go any further.

Friday 11 October 2013

How to test microphone with Audio Linux Sound Architecture - ALSA

Source: http://linuxconfig.org/how-to-test-microphone-with-audio-linux-sound-architecture-alsa

1. List of sound devices

$ cat /proc/asound/cards
 0 [NVidia         ]: HDA-Intel - HDA NVidia
 HDA NVidia at 0xefff0000 irq 20
you may get bunch of devices but we are interested in the one which seems to familiar to you or the one which has IRQ. Another command to use to check which sound devices are recognized by your alsa system is arecord -l:
$ arecord -l
**** List of CAPTURE Hardware Devices ****
card 0: NVidia [HDA NVidia], device 0: AD198x Analog 
[AD198x Analog]
 Subdevices: 3/3
 Subdevice #0: subdevice #0
 Subdevice #1: subdevice #1
 Subdevice #2: subdevice #2

2. Test MIC

to test microphone we would used arecord on the command line. This small utility will record sound from your default alsa default sound device. No special arguments as device name are not required since we I have only one sound card.
$ arecord -d 10 /tmp/test-mic.wav
this will record 10 seconds.

3. Play test-mic.wav

Now it is easy to play your wav file with another simple alsa utility a play:
$ aplay /tmp/test-mic.wav
NOTE:
If you have a more sound devices on your system and you need to use the non default sound card you can specify it to arecord with -D option. For example:
$ arecord  hw:1,0 -d 10  /tmp/test-mic.wav
will use second sound card where 1 refers to card and 0 refers to device as returned by arecord -l command. If you want to change your default alsa sound device globally on the system here is a link to unofficial alsa wiki which you might find helpful:
http://alsa.opensrc.org/index.php/FAQ026

The Difference Between Fedora, Redhat, and CentOS

Differences

  1. Fedora is the main project, and it's a communitity-based, free distro focused on quick releases of new features and functionality.
  2. Redhat is the corporate version based on the progress of that project, and it has slower releases, comes with support, and isn't free.
  3. CentOS is basically the community version of Redhat. So it's pretty much identical, but it is free and support comes from the community as opposed to Redhat itself.

What is CPython

19 down vote accepted

So what is CPython

CPython is the original Python implementation. It is the implementation you download from Python.org. People call it CPython to distinguish it from other, later, Python implementations, and to distinguish the implementation of the language engine from the Python programming language itself.
The latter part is where your confusion comes from; you need to keep Python-the-language separate from whatever runs the Python code.
CPython happens to be implemented in C. That is just an implementation detail really. CPython compiles your python code into bytecode (transparently) and interprets that bytecode in a evaluation loop.

What about Jython, etc.

Jython, IronPython and PyPy are the current 'other' implementations of the Python programming language; these are implemented in Java, C# and RPython (a subset of Python), respectively. Jython compiles your Python code to Java bytecode, so your Python code can run on the JVM. IronPython lets you run Python on the Microsoft CLR. And PyPy, being implemented in (a subset of) Python, lets you run Python code faster than CPython, which rightly should blow your mind. :-)

Actually compiling to C

So CPython does itself not translate your Python code to C. It instead runs a interpreter loop. There is a project that does translate Python-ish code to C, and that is called Cython. Cython adds a few extensions to the Python language, and lets you compile your code to C extensions, code that plugs into the CPython interpreter.

Thursday 10 October 2013

Linux WiFi: operation not possible due to RF-kill

SOURCE: http://www.geekmind.net/2011/01/linux-wifi-operation-not-possible-due.html


Some people have been experiencing WiFi problems with Ubuntu 10.10 since an update that happend just before Christmas 2010. The problem seems to be a bug in a kernel module, which prevents the rfkill's soft and hard block from syncing correctly.

In practice that means you can press your laptop's WiFi button as often as you want, it doesn't change anything. Your wireless adapter will always appear as disabled. If you try to start the wireless interface manually you get the following error message:

sk@ubuntu:~# sudo ifconfig wlan0 up
SIOCSIFFLAGS: Operation not possible due to RF-kill
If you do a rfkill list all you should get an output similar to this:
sk@ubuntu:~$ sudo rfkill list all
0: hp-wifi: Wireless LAN
Soft blocked: yes
Hard blocked: no
1: phy0: Wireless LAN
Soft blocked: yes
Hard blocked: no
Depending on the state of your WiFi button the Hard blocked will either be yes or no. Press the WiFi button and run rfkill list all again to make sure the value for Hard blocked changes.

The actual problem is, that the Soft blocked value is always set to yes, because for some reason the syncing between the hardware block and the software block doesn't work as supposed. To override this behavior, you can just run rfkill unblock wifi and it should work again. Double check by entering rfkill list all again and make sure it looks like this, with all values set to no:
sk@ubuntu:~$ sudo rfkill list all
0: hp-wifi: Wireless LAN
Soft blocked: no
Hard blocked: no
1: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no
If you then run ifconfig wlan0 up (or enable the wireless via your desktop's network manager) you should be able to connect to a wireless network again without any further issues.

The configuration, which I've been using:
  • Compaq Presario CQ60
  • Atheros AR5001 Wireless Network Adapter
  • Ubuntu 10.10
I also read, that some people could fix it, by turning off the WiFi button during the boot process and then switch it on again, once the system is up and running. It seems that the system expects the hard block to be set to off. This is still a bug, but it could explain why then the soft block didn't sync with the hard block any more.

Install Broadcom 4313 on Centos 6

SOURCE: http://elrepo.org/tiki/wl-kmod


Please note: The current Broadcom closed-source Linux drivers when built according to the instructions provided here have provided functional wireless capability to some users, but have failed for other users.

Broadcom Corp. provides closed-source IEEE 802.11a/b/g/n Linux drivers for use with Broadcom's BCM4311, BCM4312, BCM4313, BCM4321, BCM4322, BCM43224, BCM43225, BCM43227 and BCM43228 wireless chipsets. We (ELRepo) cannot create and redistribute binary RPMS for these drivers due to the Broadcom licensing restrictions (i.e., liability issues). However, we do make available no-source SRPMS (.nosrc.rpm) which contain the framework required to build the binaries, but lack the proprietary code and are not subject to Broadcom's licensing restrictions.

These no-source SRPMS can be used by the end user to build kABI-compatible binary drivers for local use. These kABI-compatible binaries should be usable after future kernel updates, so there is no need to recompile them for each new kernel. Please note that the nosrc.rpm package does not build kmod-wl for kernel-xen and kmod-wl cannot be built on a system running kernel-xen.

To build a kmod-wl binary, you will need to (1) configure a build tree, (2) download the wl-kmod*nosrc.rpm for your EL release, (3) download the closed-source tarball from Broadcom for your architecture (i.e., 32-bit vs 64-bit) into the build tree and (4) initiate the kmod-wl build. For convenience, the kernel development package for the running kernel will be used in the build process, as opposed to our normal policy of building against an older kernel development package.

The kmod-wl package can be built on any system running the same EL release/architecture as the target system. If you are building on the target system and lack network connectivity, then the downloads can be made onto a USB flash drive and copied onto your system.

Below are the detailed instructions on how to build the binary packages. If you are already familiar with using rpmbuild to build packages, then this process should only take you 5-10 minutes to complete.



Build and install kmod-wl for EL5/6


1) Install needed tools/packages:


   1a) EL5:

     # yum groupinstall 'Development Tools'

     # yum install redhat-lsb

     * Install appropriate kernel*devel

       - For 32-bit:     # yum install kernel-devel-$(uname -r|sed 's/PAE//') kernel-PAE-devel-$(uname -r|sed 's/PAE//')

       - For 64-bit:     # yum install kernel-devel-$(uname -r)

   1b) EL6:

     # yum groupinstall 'Development Tools'

     # yum install redhat-lsb

     # yum install kernel-devel-$(uname -r)



2) As a regular user (not as root), configure a build tree and minimal .rpmmacros:


   $ mkdir -p ~/rpmbuild/{BUILD,RPMS,SPECS,SOURCES,SRPMS}

   $ echo -e "%_topdir $(echo $HOME)/rpmbuild\n%dist .el$(lsb_release -s -r|cut -d"." -f1).local" >> ~/.rpmmacros



3) Download wl-kmod*nosrc.rpm



4) Download the Broadcom driver matching your architecture (i.e., 32-bit vs 64-bit):


   from:   http://www.broadcom.com/support/802.11/linux_sta.php (external link)

   to:      ~/rpmbuild/SOURCES/



5) Build kmod-wl as a regular user (not as root):


   $ rpmbuild --rebuild --target=`uname -m` --define 'packager ' //wl-kmod*nosrc.rpm
   ...
   Wrote: /home//rpmbuild/RPMS/x86_64/kmod-wl-.x86_64.rpm
   ...
   + exit 0

     (Note: The rpmbuild option --target=`uname -m` is only required for EL5 32-bit builds.)




   Note: The above build may not yield a fully functional binary driver for certain older Broadcom hardware under EL 6.

   If an EL 6 driver built using the above instructions does not appear to be fully functional, then try building it using the Wireless Extensions API:

   $ rpmbuild --rebuild --define 'packager ' --define 'apiwext 1' //wl-kmod*el6.elrepo.nosrc.rpm

   Assuming you have already installed a faulty kmod-wl, then be sure to uninstall it (i.e., # rpm -e kmod-wl) before installing the new kmod-wl.



6) If ndiswrapper is installed and is no longer needed, then remove it:


     # yum remove \*ndiswrapper\*



7) Install kmod-wl:


   # rpm -Uvh /path-to-rpm/kmod-wl*rpm

   OR

   # yum --nogpgcheck localinstall /path-to-rpm/kmod-wl*rpm



8) Reboot or to start wireless now:


   8a) EL5:

     * Works immediately after installation without intervention

   8b) EL6:

     # modprobe -r b43 b43legacy ssb wl lib80211
     # modprobe -r bcma (Note: needed for EL 6.4 and later)
     # modprobe lib80211_crypt_tkip
     # modprobe wl



9) Store kmod-wl*rpm for safe keeping


10) Optional - Remove the build tree:


   $ rm -rf ~/rpmbuild

Using KVM and VirtualBox side by side

Source: http://www.dedoimedo.com/computers/kvm-virtualbox.html


KVM and VirtualBox supposedly cannot coexist, or rather, VirtualBox won't run while the KVM modules are loaded in memory. KVM can work fine alongside VirtualBox, so it's a one-way problem, really. Solving it is easy too. Unfortunately, I've come across many terrible tutorials that recommend uninstalling either this or that product. And among the saner guides that go for a less stringent solution, most simply tell you rmmod this or that, but they don't tell you how to get things back running again.
I will show you how to use KVM and VirtualBox side-by-side, without uninstalling any one or rebooting in between uses. You will learn how to disable and enable the products so the conflicting counterpart can run. In vivo, no reboots. Let's do this.

Symptom - VirtualBox won't run

You may see this kind of error when you launch VirtualBox:
VirtualBox error
It says, VirtualBox can't operate in VMX root mode. Please disable the KVM kernel extension, recompile your kernel and reboot. Wow, wow, slow down. This is a very geeky and frightening message. There's no need to recompile anything. The fix takes five seconds and it's completely non-destructive.

Problem explained

VirtualBox and KVM can't work together. This means that KVM needs to be disabled if we want to run VirtualBox. The question is how we do this. The answer is: by inserting and removing kernel modules.
The Linux operating system supports insertion and removal of kernel modules on the fly, without a reboot. This means you can load and unload kernel modules to and from the memory in vivo. More details in my Linux commands article and the Crash Book.
To achieve what we need, we will use insmod and rmmod commands.

Remove modules

Let's examine the kernel space. We will issue the lsmod command first, to see what modules are loaded into memory:
Vbox lsmod
KVM lsmod
As you can see, VirtualBox uses vboxdrv and vboxnetflt drivers, while KVM uses kvm and kvm_intel drivers. Note: kvm_intel is specific to Intel architecture. There's kvm_amd for AMD platforms. We need to unload KVM modules.
/sbin/rmmod kvm_intel
/sbin/rmmod kvm
KVM unloaded
VirtualBox running
Big question: But now, KVM is gone. How can I get it back, please?
Ah, very good! Let's see how we can recover.

Insert modules

Just as we removed the modules, we can insert them. You will need to locate the modules on your disk and then insert them. You can also use the modprobe command, which is always useful if there are dependencies.
Let's find the modules (assume sudo in commands, but can be run as root, too):
updatedb
locate kvm
There will be many results, so you can restrict the search to kvm.ko and kvm-intel.ko.
Locate modules
Now, insert the one that matches your running kernel. You can check using uname -r.
/sbin/insmod /lib/modules/`uname -r`/kernel/arch/x86/kvm/kvm.ko
/sbin/insmod /lib/modules/`uname -r`/kernel/arch/x86/kvm/kvm-intel.ko
Here's a screenshot. First, we check for kvm module. lsmod command shows it is not loaded. Then, we load the kvm modules and issue the lsmod command once again.
Please note the screenshot commands differ slightly from the commands written in the code box above. I assumed that /sbin was in the PATH, so I used a shortened insmod command for brevity. At the same time, I also used the full module path, to show you what it looks like. If you intend to script the procedure, which you should, then full paths are a must and command substitution using backticks is recommended for greater modularity.
Insert kvm

Scripts

Now, time to automate this. You need two scripts. One to unload KVM modules and one to load them. If you really want to be strict, then you can also stop the VirtualBox service when using KVM and start it after using KVM. Example, mucking about with VirtualBox drivers:
Status
Stop service
Therefore, a sample script to enable VirtualBox and disable KVM would be:
#!/bin/bash
/sbin/rmmod kvm_intel
/sbin/rmmod kvm
/etc/init.d/vboxdrv start
And one to load KVM and stop VirtualBox would be:
#!/bin/bash
/etc/init.d/vboxdrv stop
/sbin/insmod /lib/modules/`uname -r`/kernel/arch/x86/kvm/kvm.ko
/sbin/insmod /lib/modules/`uname -r`/kernel/arch/x86/kvm/kvm-intel.ko
For AMD machines, replace kvm-intel.ko with kvm-amd.ko. Please note that sanity checks are required to make sure that you're not trying to start a started service. I have not added these; consider them as homework.
Likewise, please note the processor architecture. For most people, x86 (and x86_64) will work, but you may have other architecture, like SPARC, ARM, Itanium, or others, so change accordingly.
Now, place desktop shortcuts that links to these scripts and Bob's your uncle. Using uname instead of specific kernel versions ensures that your scripts will work even after kernel upgrades.

Conclusion

As you can see, the reality is not as harsh as you may have expected. This tutorial reveals the simple ways of getting VirtualBox and KVM to cooperate, without uninstalling one or the other or constantly rebooting. The Linux architecture allows live insertion of modules, so the only thing you really must reboot for is the kernel upgrade.
This tutorial teaches you several things, including a clever way of combining comfort with usability, how to insert and remove kernel modules, how to script your work and how to achieve the desired goal of having KVM and VirtualBox side by side.
I hope you liked this one.
Cheers.

Install Fonts on CENTOS

Source: http://linuxpoison.blogspot.com/2009/12/how-to-install-additional-true-type-ttf.html

Installation:
First, find and download your desired fonts into /home/nikesh/fonts diretory (user directory). Then extract them and copy to the system fonts directory as follows:

cd /usr/share/fonts/truetype
sudo mkdir customFonts
cd customFonts
sudo cp /home/nikesh/fonts/*.ttf .
sudo chown root.root *.ttf
sudo mkfontdir
cd ..
fc-cache

Friday 4 October 2013

Turn windows 7 to wifi hotspot

SOURCE: I forgot where I read this

Getting started with wireless Hosted Networks
In order to use the wireless Hosted Network feature, your wireless adapter must be using drivers certified for Windows 7. If Windows detects a supported adapter, it will automatically add a connection to the Network Connections window, named Microsoft Virtual WiFi Miniport Adapter, such as Figure 1 shows. If multiple supported-adapters exist, Windows will automatically choose the one to use for the wireless Hosted Network.

Figure 1.

Microsoft requires all wireless Hosted Networks to use WPA2-PSK (AES) encryption. However, there is not a mechanism put in place to prevent file sharing. Hosts and clients should manually protect shares if not all users can be trusted.

In addition, keep in mind that wireless Hosted Networks do not automatically restart after the computer resumes from sleep, hibernate, or restarts. However, if used, a third-party utility might initiate a reconnection. If you manually start the wireless Hosted Network again, Windows will use the previously entered network details though.

Manually create a virtual AP with netsh
If you want to experiment with the wireless Hosted Network feature with text commands, click the Start button, enter “cmd” and hit Enter. Once the Command Prompt window appears, you can enter the following to set the network details:

netsh wlan set hostednetwork mode=allow ssid=YourVirtualNetworkName  key=YourNetworkPassword

Of course, replace the SSID and key placeholders with your desired network name and WPA2-PSK encryption key.

Before you enable the Hosted Network, you can configure the real network adapter to share its Internet access using the Internet Connection Sharing (ICS) feature of Windows. This way people connecting to the virtual AP will receive Internet access. You can leave the Command Prompt open so you can start the Hosted Network later.

To enable ICS, navigate through the Control Panel or Network and Sharing Center to bring up the Network Connections window. Then right-click the network adapter that’s connected to the Internet and select Properties. Then select the Sharing tab, check the Allow other network users to connect through this computer’s Internet connection, choose the Hosted Network Connection from the drop-down listbox, and click OK. See Figure 2 for an example.

Figure 2.

Now return to the Command Prompt and enter the following to enable the Hosted Network:

netsh wlan start hostednetwork

To manually turn the Hosted Network off, enter the following:

netsh wlan stop hostednetwork

To see the Hosted Network details (see Figure 3), including the MAC addresses of connected users, enter the following:

netsh wlan show hostednetwork

To change the WPA2-PSK key, you can enter the following:

netsh wlan refresh hostednetwork YourNewNetworkPassword



It’s a virtual AP
Now others nearby should see the Hosted Network appear in their list of available wireless networks. They can connect like normal and enter the encryption key when prompted.

Remember, you’ll have to manually start the Hosted Network again, if desired, after rebooting the computer. Most importantly, remember sharing isn’t blocked; make sure you only invite people you trust.


Recover the deleted files in ext3 or ext4 filesystem

Source: http://www.switchroot.com/how-to-recover-a-deleted-file-in-ext3-or-ext4-filesystem
Note: you need an account with root priviledges.
1) First install the following packages with yum:
[test@server ~]$ sudo yum install -y e2fsprogs e2fsprogs-libs e2fsprogs-devel gcc-c++ 
[test@server ~]$ cd /tmp
[test@server tmp]$ wget https://sourceforge.net/project/platformdownload.php?group_id=260221
3) Run the following commands to extract and install the downloaded file:
[test@server tmp]$ tar -xvjf extundelete-0.2.0.tar.bz2
[test@server tmp]$ cd extundelete-0.2.0
[test@server extundelete-0.2.0]$ ./configure
[test@server extundelete-0.2.0]$ make
[test@server extundelete-0.2.0]$ sudo make install
4) Now, extundelete is installed.

5) To recover a file, it is recommended that we should first unmount the partition from which you deleted the file or mount it in read only mode:
(Lets say here the partition is /dev/sda6 which is mounted on /test )

To mount it in read only mode:
[test@server ~]$ sudo mount -o remount,ro /dev/sda6
OR to umount the device:
[test@server ~]$ umount /dev/sda6
6) Now, to recover a specific file, we have to type the path of file with the extundelete command. path should be from root of that filesystem (but should not contain a / in beginning).
For example: If the file /test/abc/xyz was deleted then path will be abc/xyz as /test is the mount point (root) of that filesystem. So run:
[test@server ~]$ cd /tmp
[test@server tmp]$  sudo /usr/local/bin/extundelete --restore-file abc/xyz /dev/sda6
7) It will create a directory RECOVERED_FILES at current location having all the recovered files into it. - See more at: http://www.switchroot.com/how-to-recover-a-deleted-file-in-ext3-or-ext4-filesystem#sthash.KwuA2Ndd.dpuf

Tuesday 1 October 2013

How to change Magento domain name

When you need to move Magento store to another domain name, there is one issue which, according to forums, costed developers hours of frustration. And the issue is domain name which is stored in Magento configuration tables.
So, if you moved Magento to another domain name and all you get when you open your new domain in the browser is redirect to the old domain, you are not alone :) I just wasted lots of time sorting this out! Here is solution which worked for me.
First step was simple – finding in the database base url value: table name is core_config_data and the keys are /web/unsecure/base_url and web/secure/base_url. Change those two to the proper values.
Second step is also very logical – cleanup cache! Magento does cache everything, including values of config table, so go to the Magento root with FTP or SSH, remove everything from the folders var/cache/ and var/session/.
At this point changing URL seems to be working for most installations, so if you are lucky, that’s all you have to do. For me it was just a start :) Magento was redirecting to my old domain name. Browser cache cleanup – doesn’t help. APC cache cleanup – doesn’t work. Still redirecting…
Solution was simple (well, as usual with problems like this). Permissions were messed up on the var folder of Magento, so it was not able to write cache there (result of files transfer). That issue doesn’t stop Magento from caching (which is kinda good), but trick is that you need to find where the cache is hidden. So, check your tmp folder. It could be system /tmp/, or, in my case, /var/www/tmp/ (that was FreeBSD). In the temp folder I discovered magento subdirectory with all the cached files. After removing files, I see my site up!
Let me know if that helped you or if there are some other issues to watch for!

How to solve Magento error – Exception printing is disabled

Source: http://www.ipserverone.info/applications/magento/how-to-solve-magento-error-exception-printing-is-disabled/
Whenever you see this error:

There has been an error processing your request
Exception printing is disabled by default for security reasons.
Error log record number: XXXXXXXXXXXXXXX
You can do as followed:

1. Locate the root directory where your Magento is installed. Search for “errors” directory.
2. Change the filename of local.xml.sample to local.xml
3. Reload the page where it shows error message, you will see a full list of error message – The purpose of rename local.xml is to allow the full error message to be shown.
4. Now, locate magento_directory/lib/Zend/Cache/Backend/File.php and look for:

protected $_options = array(
'cache_dir' => 'null',
Replace it with:

protected $_options = array(
'cache_dir' => 'tmp/',
And save the file.
5. Now, go to Magento root directory and create a new directory with the name “tmp”.
6. Refresh the error page and see if the issue solved.

Extract Without First Directory

Source: http://www.marksanborn.net/linux/extract-without-first-directory/
 
Whenever I download something that is compressed on the Internet in a .zip, .rar or .tar.gz it is always a crapshot whether or not it contains a “container directory”. A “container directory” is a directory that contains all the other files usually with the same name as the compressed file.
For example the Zend Framework when downloaded contains a folder called, ’ZendFramework-1.7.2’. All the other files are contained under this folder. This is great but sometimes I want to extract the contents of the folder without the “container folder”.
This is how I used to extract the contents and remove the “container folder”:
tar -xvf ZendFramework-1.7.2.tar.gz
Get rid of the tarball…
rm ZendFramework-1.7.2.tar.gz
cd ZendFramework-1.7.2/
Which would result in:
Zend Framework Directory Structure
Copy everything in the “container” folder and move it up a directory.
cp -rf * ../
Now I have found a better way…

A better way

The flag that I have learned is the strip flag. This will strip off the first directory and extract the rest.
tar -xvf ZendFramework-1.7.2.tar.gz --strip 1
The only thing now is… How do I tell if a tar contains a “container folder”?
Easy
tar -tf ZendFramework-1.7.2.tar.gz | head
This will list contents of the file ’ZendFramework-1.7.2.tar.gz’ showing only the first few lines.
What do you think? Is there an even better way?

mysql: Get the database size, free space and last update

Source: http://mysqladministrators.blogspot.com/2012/02/get-database-size.html

To get the current database size just by querying into your query browser or CLI from the INFORMATION_SCHEMA database in table TABLES.


SELECT table_schema "Data Base Name",
sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB"
FROM information_schema.TABLES
GROUP BY table_schema ;

Get the database free space

SELECT table_schema "Data Base Name",
sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB",
sum( data_free )/ 1024 / 1024 "Free Space in MB"
FROM information_schema.TABLES
GROUP BY table_schema;

Get the database last update ordered by update time then by create time.

SELECT MAX(UPDATE_TIME), MAX(CREATE_TIME), TABLE_SCHEMA
FROM `TABLES`
GROUP BY TABLE_SCHEMA
ORDER BY 1, 2;

If "root" is access denied (mysql)

Source: http://feeds.feedburner.com/blogspot/Qasmk

Have you ever encountered that after a successful logins to your mysql then the other day you are not able to login anymore using the root account? To fix it, follow below steps for linux users.

1. Stop Mysql

shell> /etc/init.d/mysql stop

2. Start Mysql Safe
shell> mysqld_safe -skip-grant-tables &

3. Start Mysql
shell> /etc/init.d/mysql start

4. Login as root
shell> mysql -u root -p

Backup and Restore MySQL Database Using mysqldump

Source: http://www.thegeekstuff.com/2008/09/backup-and-restore-mysql-database-using-mysqldump/


mysqldump is an effective tool to backup MySQL database. It creates a *.sql file with DROP table, CREATE table and INSERT into sql-statements of the source database. To restore the database,  execute the *.sql file on destination database.  For MyISAM, use mysqlhotcopy method that we explained earlier, as it is faster for MyISAM tables.

Using mysqldump, you can backup a local database and restore it on a remote database at the same time, using a single command. In this article, let us review several practical examples on how to use mysqldump to backup and restore.

For the impatient, here is the quick snippet of how backup and restore MySQL database using mysqldump:
backup: # mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

restore:# mysql -u root -p[root_password] [database_name] < dumpfilename.sql

How To Backup MySQL database


1. Backup a single database:

This example takes a backup of sugarcrm database and dumps the output to sugarcrm.sql
# mysqldump -u root -ptmppassword sugarcrm > sugarcrm.sql

# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql
The sugarcrm.sql will contain drop table, create table and insert command for all the tables in the sugarcrm database. Following is a partial output of sugarcrm.sql, showing the dump information of accounts_contacts table:
--
-- Table structure for table `accounts_contacts`
--

DROP TABLE IF EXISTS `accounts_contacts`;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `accounts_contacts` (
`id` varchar(36) NOT NULL,
`contact_id` varchar(36) default NULL,
`account_id` varchar(36) default NULL,
`date_modified` datetime default NULL,
`deleted` tinyint(1) NOT NULL default '0',
PRIMARY KEY  (`id`),
KEY `idx_account_contact` (`account_id`,`contact_id`),
KEY `idx_contid_del_accid` (`contact_id`,`deleted`,`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--
-- Dumping data for table `accounts_contacts`
--

LOCK TABLES `accounts_contacts` WRITE;
/*!40000 ALTER TABLE `accounts_contacts` DISABLE KEYS */;
INSERT INTO `accounts_contacts` VALUES ('6ff90374-26d1-5fd8-b844-4873b2e42091',
'11ba0239-c7cf-e87e-e266-4873b218a3f9','503a06a8-0650-6fdd-22ae-4873b245ae53',
'2008-07-23 05:24:30',1),
('83126e77-eeda-f335-dc1b-4873bc805541','7c525b1c-8a11-d803-94a5-4873bc4ff7d2',
'80a6add6-81ed-0266-6db5-4873bc54bfb5','2008-07-23 05:24:30',1),
('4e800b97-c09f-7896-d3d7-48751d81d5ee','f241c222-b91a-d7a9-f355-48751d6bc0f9',
'27060688-1f44-9f10-bdc4-48751db40009','2008-07-23 05:24:30',1),
('c94917ea-3664-8430-e003-487be0817f41','c564b7f3-2923-30b5-4861-487be0f70cb3',
'c71eff65-b76b-cbb0-d31a-487be06e4e0b','2008-07-23 05:24:30',1),
('7dab11e1-64d3-ea6a-c62c-487ce17e4e41','79d6f6e5-50e5-9b2b-034b-487ce1dae5af',
'7b886f23-571b-595b-19dd-487ce1eee867','2008-07-23 05:24:30',1);
/*!40000 ALTER TABLE `accounts_contacts` ENABLE KEYS */;
UNLOCK TABLES;

2. Backup multiple databases:

If you want to backup multiple databases, first identify the databases that you want to backup using the show databases as shown below:
# mysql -u root -ptmppassword

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| bugs               |
| mysql              |
| sugarcr            |
+--------------------+
4 rows in set (0.00 sec)
For example, if you want to take backup of both sugarcrm and bugs database, execute the mysqldump as shown below:
# mysqldump -u root -ptmppassword --databases bugs sugarcrm > bugs_sugarcrm.sql
Verify the bugs_sugarcrm.sql dumpfile contains both the database backup.
# grep -i "Current database:" /tmp/bugs_sugarcrm.sql
-- Current Database: `mysql`
-- Current Database: `sugarcrm`

3. Backup all the databases:

The following example takes a backup of  all the database of the MySQL instance.
# mysqldump -u root -ptmppassword --all-databases > /tmp/all-database.sql

4. Backup a specific table:

In this example, we backup only the accounts_contacts table from sugarcrm database.
# mysqldump -u root -ptmppassword sugarcrm accounts_contacts \
      > /tmp/sugarcrm_accounts_contacts.sql

4. Different mysqldump group options:

  • –opt is a group option, which is same as –add-drop-table, –add-locks, –create-options, –quick, –extended-insert, –lock-tables, –set-charset, and –disable-keys. opt is enabled by default, disable with –skip-opt.
  • –compact is a group option, which gives less verbose output (useful for debugging). Disables structure comments and header/footer constructs. Enables options –skip-add-drop-table –no-set-names –skip-disable-keys –skip-add-locks

How To Restore MySQL database


1. Restore a database

In this example, to restore the sugarcrm database, execute mysql with < as shown below. When you are restoring the dumpfilename.sql on a remote database, make sure to create the sugarcrm database before you can perform the restore.
# mysql -u root -ptmppassword

mysql> create database sugarcrm;
Query OK, 1 row affected (0.02 sec)

# mysql -u root -ptmppassword sugarcrm < /tmp/sugarcrm.sql

# mysql -u root -p[root_password] [database_name] < dumpfilename.sql

2. Backup a local database and restore to remote server using single command:

This is a sleek option, if you want to keep a read-only database on the remote-server, which is a copy of the master database on local-server. The example below will backup the sugarcrm database on the local-server and restore it as sugarcrm1 database on the remote-server. Please note that you should first create the sugarcrm1 database on the remote-server before executing the following command.
[local-server]# mysqldump -u root -ptmppassword sugarcrm | mysql \
                 -u root -ptmppassword --host=remote-server -C sugarcrm1
[Note: There are two -- (hyphen) in front of host]

20 mysqladmin command for database administration

SOURCE: http://www.tecmint.com/mysqladmin-commands-for-database-administration-in-linux/

mysqladmin is a command-line utility the comes with MySQL server and it is used by Database Administrators to perform some basic MySQL tasks easily such as setting root password, changing root password, monitoring mysql processes, reloading privileges, checking server status etc.
In this article we’ve compiled some very useful ‘mysqladmin‘ commands that are used by system/database administrators in their day-to-day work. You must have MySQL server installed on your system to perform these tasks.
mysqladmin commands

20 mysqladmin commands examples
If you don’t have MySQL server installed or you are using older version of MySQL server, then we recommend you all to install or update your version by following our below article.
  1. Installation of MySQL 5.5.28 Server on RHEL/CentOS/Fedora

1. How to set MySQL Root password?

If you have fresh installation of MySQL server, then it doesn’t required any password to connect it as root user. To set MySQL password for root user, use the following command.
# mysqladmin -u root password YOURNEWPASSWORD

2. How to Change MySQL Root password?

If you would like to change or update MySQL root password, then you need to type the following command. For example, say your old password is 123456 and you want to change it with new password say xyz123.
mysqladmin -u root -p123456 password 'xyz123'

3. How to check MySQL Server is running?

To find out whether MySQL server is up and running, use the following command.
# mysqladmin -u root -p ping

Enter password:
mysqld is alive

4. How to Check which MySQL version I am running?

The following command shows MySQL version along with the current running status .
# mysqladmin -u root -p version

Enter password:
mysqladmin  Ver 8.42 Distrib 5.5.28, for Linux on i686
Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.5.28
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 7 days 14 min 45 sec

Threads: 2  Questions: 36002  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.059

5. How to Find out current Status of MySQL server?

To find out current status of MySQL server, use the following command. The mysqladmin command shows the status of uptime with running threads and queries.
# mysqladmin -u root -ptmppassword status

Enter password:
Uptime: 606704  Threads: 2  Questions: 36003  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.059

6. How to check status of all MySQL Server Variable’s and value’s?

To check all the running status of MySQL server variables and values, type the following command. The output would be similar to below.
# mysqladmin -u root -p extended-status

Enter password:
+------------------------------------------+-------------+
| Variable_name                            | Value       |
+------------------------------------------+-------------+
| Aborted_clients                          | 3           |
| Aborted_connects                         | 3           |
| Binlog_cache_disk_use                    | 0           |
| Binlog_cache_use                         | 0           |
| Binlog_stmt_cache_disk_use               | 0           |
| Binlog_stmt_cache_use                    | 0           |
| Bytes_received                           | 6400357     |
| Bytes_sent                               | 2610105     |
| Com_admin_commands                       | 3           |
| Com_assign_to_keycache                   | 0           |
| Com_alter_db                             | 0           |
| Com_alter_db_upgrade                     | 0           |
| Com_alter_event                          | 0           |
| Com_alter_function                       | 0           |
| Com_alter_procedure                      | 0           |
| Com_alter_server                         | 0           |
| Com_alter_table                          | 0           |
| Com_alter_tablespace                     | 0           |
+------------------------------------------+-------------+

7. How to see all MySQL server Variables and Values?

To see all the running variables and values of MySQL server, use the command as follows.
# mysqladmin  -u root -p variables

Enter password:
+---------------------------------------------------+----------------------------------------------+
| Variable_name                                     | Value                                        |
+---------------------------------------------------+----------------------------------------------+
| auto_increment_increment                          | 1                                            |
| auto_increment_offset                             | 1                                            |
| autocommit                                        | ON                                           |
| automatic_sp_privileges                           | ON                                           |
| back_log                                          | 50                                           |
| basedir                                           | /usr                                         |
| big_tables                                        | OFF                                          |
| binlog_cache_size                                 | 32768                                        |
| binlog_direct_non_transactional_updates           | OFF                                          |
| binlog_format                                     | STATEMENT                                    |
| binlog_stmt_cache_size                            | 32768                                        |
| bulk_insert_buffer_size                           | 8388608                                      |
| character_set_client                              | latin1                                       |
| character_set_connection                          | latin1                                       |
| character_set_database                            | latin1                                       |
| character_set_filesystem                          | binary                                       |
| character_set_results                             | latin1                                       |
| character_set_server                              | latin1                                       |
| character_set_system                              | utf8                                         |
| character_sets_dir                                | /usr/share/mysql/charsets/                   |
| collation_connection                              | latin1_swedish_ci                            |
+---------------------------------------------------+----------------------------------------------+

8. How to check all the running Process of MySQL server?

The following command will display all the running process of MySQL database queries.
# mysqladmin -u root -p processlist

Enter password:
+-------+---------+-----------------+---------+---------+------+-------+------------------+
| Id    | User    | Host            | db      | Command | Time | State | Info             |
+-------+---------+-----------------+---------+---------+------+-------+------------------+
| 18001 | rsyslog | localhost:38307 | rsyslog | Sleep   | 5590 |       |                  |
| 18020 | root    | localhost       |         | Query   | 0    |       | show processlist |
+-------+---------+-----------------+---------+---------+------+-------+------------------+

9. How to create a Database in MySQL server?

To create a new database in MySQL server, use the command as shown below.
# mysqladmin -u root -p create databasename

Enter password:
# mysql -u root -p

Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 18027
Server version: 5.5.28 MySQL Community Server (GPL) by Remi

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| databasename       |
| mysql              |
| test               |
+--------------------+
8 rows in set (0.01 sec)

mysql>

10. How to drop a Database in MySQL server?

To drop a Database in MySQL server, use the following command. You will be asked to confirm press ‘y‘.
# mysqladmin -u root -p drop databasename

Enter password:
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'databasename' database [y/N] y
Database "databasename" dropped

11. How to reload/refresh MySQL Privileges?

The reload command tells the server to reload the grant tables. The refresh command flushes all tables and reopens the log files.
# mysqladmin -u root -p reload;
# mysqladmin -u root -p refresh

12. How to shutdown MySQL server Safely?

To shutdown MySQL server safely, type the following command.
mysqladmin -u root -p shutdown

Enter password:
You can also use the following commands to start/stop MySQL server.
# /etc/init.d/mysqld stop
# /etc/init.d/mysqld start

13. Some useful MySQL Flush commands

Following are some useful flush commands with their description.
  1. flush-hosts: Flush all host information from host cache.
  2. flush-tables: Flush all tables.
  3. flush-threads: Flush all threads cache.
  4. flush-logs: Flush all information logs.
  5. flush-privileges: Reload the grant tables (same as reload).
  6. flush-status: Clear status variables.
# mysqladmin -u root -p flush-hosts
# mysqladmin -u root -p flush-tables
# mysqladmin -u root -p flush-threads
# mysqladmin -u root -p flush-logs
# mysqladmin -u root -p flush-privileges
# mysqladmin -u root -p flush-status

14. How to kill Sleeping MySQL Client Process?

Use the following command to identify sleeping MySQL client process.
# mysqladmin -u root -p processlist

Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 5  | root | localhost |    | Sleep   | 14   |       |      |
| 8  | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
Now, run the following command with kill and process ID as shown below.
# mysqladmin -u root -p kill 5

Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 12 | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
If you like to kill multiple process, then pass the process ID‘s with comma separated as shown below.
# mysqladmin -u root -p kill 5,10

15. How to run multiple mysqladmin commands together?

If you would like to execute multiple ‘mysqladmin‘ commands together, then the command would be like this.
# mysqladmin  -u root -p processlist status version

Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 8  | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
Uptime: 3801  Threads: 1  Questions: 15  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.003
mysqladmin  Ver 8.42 Distrib 5.5.28, for Linux on i686
Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.5.28
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 1 hour 3 min 21 sec

Threads: 1  Questions: 15  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.003

16. How to Connect remote mysql server

To connect remote MySQL server, use the -h (host)  with IP Address of remote machine.
# mysqladmin  -h 172.16.25.126 -u root -p

17. How to execute command on remote MySQL server

Let’s say you would like to see the status of remote MySQL server, then the command would be.
# mysqladmin  -h 172.16.25.126 -u root -p status

18. How to start/stop MySQL replication on a slave server?

To start/stop MySQL replication on salve server, use the following commands.
# mysqladmin  -u root -p start-slave
# mysqladmin  -u root -p stop-slave

19. How to store MySQL server Debug Information to logs?

It tells the server to write debug information about locks in use, used memory and query usage to the MySQL log file including information about event scheduler.
# mysqladmin  -u root -p debug

Enter password:

20. How to view mysqladmin options and usage

To find out more options and usage of myslqadmin command use the help command as shown below. It will display a list of available options.
# mysqladmin --help
We have tried our best to include almost all of ‘mysqladmin‘ commands with their examples in this article, If still, we’ve missed anything, please do let us know via comments and don’t forget to share with your friends.