Andy Shulman
Andy Shulman

Reputation: 1915

Get open ports as an array

So, I'm using netstat -lt to get open ports. However, I'm not interested in certain values (like SSH or 22), so I want to be able to exclude them. I also want to get them as an array in bash. So far I have netstat -lt | sed -r 's/tcp[^:]+://g' | cut -d' ' -f1 but they're not an array, nor am I excluding anything.

Upvotes: 4

Views: 1707

Answers (3)

fork0
fork0

Reputation: 3459

Add ($()) around your statement:

port=($(netstat -ltn | sed -rne '/^tcp/{/:(22|25)\>/d;s/.*:([0-9]+)\>.*/\1/p}'))

Filtering ports 22 and 25.

Upvotes: 2

chepner
chepner

Reputation: 531055

Try using the ss command, which replaces netstat.

ss -atu | awk '{print $5}' | awk -F: '{print $NF}'

The ss command gives you all TCP and UDP ports on the local machine (the only sockets that would have ports). The first awk extracts the column containing the local address and port number. The second awk takes only the last field following a colon; this is necessary in case you have IPv6 sockets on your machine, whose IP address will also include colons.

Once you've done this, you can grep out the ports you don't want. Also, see the documentation referred to by the ss man page for information on filters, which may let you filter out unwanted sockets from the output of ss.

Upvotes: 3

akostadinov
akostadinov

Reputation: 18594

a=( `netstat -ltn --inet | sed -r -e '1,2d''s/tcp[^:]+://g' | cut -d' ' -f1 | sed -e '1,2d' | grep -v "22\|33\|25"` )

second sed command removes headers if your version of netstat prints such. I have "Active" and "Proto" as first two lines. Use grep to filter unwanted ports. add -n to netstat to see port numbers instead of names. --inet is to force ipv4, otherwise you may see IPv6 which may confuse your script.

btw not sure you need an array. usually arrays are needed only if you are going to work on a subset of values you have. If you work on all values there are simpler constructs but not sure what you're going to do.

Regards.

update: you can use a single sed command with two operations instead of two separate invocations:

sed -r -e '1,2d' -e 's/tcp[^:]+://g'

Upvotes: 0

Related Questions