Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I use the telnet command to check if MySQL port is responding.

telnet 3306

I use the ctrl character to disconnect. This is working as expected. How do I use this command in shell script?

share|improve this question
Actually, do the echo with newlines as Janne propose, and add a sane timeout value with -w. – 3molo Aug 5 '11 at 9:34
up vote 10 down vote accepted

If you're just looking to check if the port is open, try:

$ nc -zv 3306
Connection to localhost 3306 port [tcp/mysql] succeeded!

nc will return 0 if the port is open and 1 if it is not. This is quite helpful for scripting as well. Omit the v switch to keep it quiet:

if ! nc -z 3306
share|improve this answer
Thanks. But the -z switch is working on server but not working on another. Do I need to check the version of nc command? – shantanuo Aug 6 '11 at 4:41
Perhaps. What version is the one not working? – Cakemox Aug 6 '11 at 4:46
The -z switch is working correctly. I was wrong, ignore the above comment. – shantanuo Aug 7 '11 at 4:51

nc is much better for non-interactive usage. Try something like

echo -e "\n\n" | nc 3306
share|improve this answer
If I execute this, I get some garbled output, but the command doesn't exit. Does someone know why? – Legate Aug 5 '11 at 18:09
Hmmm? It should exit. – Janne Pikkarainen Aug 6 '11 at 5:08

To automate telnet script, you should use expect. See the expect home page.

share|improve this answer

If you don't have nc, you can use bash special files redirectons:

head -1 < /dev/tcp/ >/dev/null && echo MySQL is on || echo MySQL is off
share|improve this answer

This is my script for any specific cases .

DATE=`date +%Y-%m-%d`
TIME=`date +%H%M%S`

for port in 80 25 22 443 110
if telnet -c $host $port </dev/null 2>&1 | grep -q Escape; then
  echo "$DATE $TIME  $port: Connected" >> $LOG_OK
  echo "$DATE $TIME $port : no connection" >> $LOG_FAIL

share|improve this answer

I would use netcat and it's '-w' instead;

host:~ user$  nc -w 1 3306
5.1.57-1~dotdeb.1?WO`rA*L#h?b4z.pmT;i~^;host:~ user$ 
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.