LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Print fields to a file based on protocol type from netstat. (https://www.linuxquestions.org/questions/linux-newbie-8/print-fields-to-a-file-based-on-protocol-type-from-netstat-4175525385/)

vipinsqa 11-14-2014 07:43 AM

Print fields to a file based on protocol type from netstat.
 
Hi Guys,

I am trying to fetch the network connections on Centos host and write to a log. However, as UDP doesnt have a connection state, the report has a problem with displaying data as tcp has a state in the corresponding field. I am trying to handle this using below:-

if [$(netstat -anputw | awk '{print $1}')=="tcp"] then
netstat -anputw | awk '{print $1,",",$4,",",$5,",",$6,",",$7}' >> $HOME/MyLog/connections_$HOSTNAME.csv

elif [$(netstat -anputw | awk '{print $1}')=="udp"] then
netstat -anputw | awk '{print $1,",",$4,",",$5,",",",",$6}' >> $HOME/MyLog/connections_$HOSTNAME.csv
fi

So, I am trying to see wherever the protocol from netstat command is tcp, it prints the required fields and when its udp, then the corresponding state field should be empty.

However, it doesnt work. Any idea what could be wrong here?

MensaWater 11-14-2014 08:40 AM

The test commands should have spaces between the brackets and the items inside them.

The "then" and "elif" should be preceded by semicolon if on the line with the test - really they should be on the line on which you're doing the awk instead (i.e. start of following line rather than end of preceding line).

I'd suggest using "=" rather than "==" in your test AND putting a space before and after the "=" to separate the elements.

However the main issue is your conditional is testing the entire output of netstat as if it were one long line. You need to create a while loop so it processes each line as it gets to it from the netstat output.

If you do a web search for terms:
while read on netstat output
You'll find various examples of while loops related to netstat output.


All times are GMT -5. The time now is 07:04 PM.