aurumpurum
aurumpurum

Reputation: 1082

Why does >/dev/null not work as expected?

I have written the following shell script:

#! /bin/bash

# This script is designed to find hosts with MySQL installed

nmap -sT my_IP_address -p 3306 >/dev/null -oG MySQLscan

cat MySQLscan | grep open > MySQLscan2

cat MySQLscan2

According to the script the output of nmap should be sent to /dev/null. On the other hand, the final out put should be written to the file MySQLscan2 in my pwd.

Not as I have expected, two files are written to my pwd: MySQLscan: Contains the output of the scan that I have expected to be in MySQLscan2. MySQLscan2: This file is empty.

Is there an mistake in my script? How can I solve the problem?

Earlier today, I managed to run the script with correct output. I am not sure if I have changed the script in some way. I checked it again and again, but cannot find, what is wrong...

I am working with Kali Linux and Oracle VM Virtual Box.

Upvotes: 1

Views: 1233

Answers (1)

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12383

> /dev/null causes shell to redirect stdout, that is a file with file descriptor to 1 to /dev/null before the command starts so in other words to discard it. When nmap runs with -oG MySQLscan option it opens a new file and gets a new file descriptor. You can check it with strace:

$ strace -f nmap -sT localhost -p 3306  -oG MySQLscan |& grep MySQLscan
execve("/usr/bin/nmap", ["nmap", "-sT", "localhost", "-p", "22", "-oG", "MySQLscan"], 0x7ffc88805198 /* 60 vars */) = 0
openat(AT_FDCWD, "MySQLscan", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 4

In this example openat() returned 4 as a new file descriptor (you can read more about this function with man 2 openat). Since file descriptor 4 hasn't been redirected before command started MySQLscan gets created. Also notice that even if file descriptor that openat() returns to open MySQLscan is redirected to /dev/null:

nmap -sT localhost -p 22  -oG MySQLscan 4>/dev/null

it doesn't prevent MySQLscan from being created because openat() requests a new unused file descriptor from kernel every time it's run.

Upvotes: 1

Related Questions