I am trying to write a bash script that will take port id I retrieve from an nmap command, and then use those ports to send a file using netcat. So I got some basic knowledge using this link,

How can I use a bash script to run nmap and capture both IP and hostname?

and nmap man page. As a result I came up with the following script:

#! /bin/bash

sudo nmap -p1-20000 -sS -oG - | awk '$4=="Status:" && $5=="Up" {cat $FILE | nc $2 $6}'

So the issue I am having has to do with the $6. It is suppose to be the port numbers retrieved from the nmap command but it actually is nothing at all. I was wondering if you guys would be able to help me retrieve the port ids.

  • Ok, so -oG is for "grepable" output not XML, so you should fix your title. Also, which version of nmap are you using? Mine (v6.47) has the host status and ports listed on different lines. Also, there's the issue of multiple ports on each host and the fact that just because a host is listed as "up" doesn't mean that any ports are open on it. – hololeap Mar 5 '15 at 9:32
  • I'm not even going to question why you are trying to send a file to arbitrary ports, but are you trying to send it to every open port on a host? You didn't really make it clear exactly what you are trying to do. – hololeap Mar 5 '15 at 9:46

Assuming that you are trying to send the file to every open port on a host, here is a script that should work for you:



nmap --open -n -p1-20000 $HOST | sed -rn 's/^([0-9]+)\/tcp.*open.*/\1/p' | 
    while read port; do nc $HOST $port < "$FILE"; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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