How to Pipe Segment of Heredoc Output to Local File

fifohere-documenttcpdump

I am issuing a command to a remote device in order to run a tcpdump on one of it's interfaces, but capture the output to a local .pcap file on my Ubuntu VM. The command that I'm issuing is as follows:

drew@Drew-Ubuntu:~/Desktop$ sshpass -p $password ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -T $username@$remote-ip -p $remote-port << EOF \ > /home/drew/Desktop/Example_Capture.pcap
> sh
> tcpdump -i eth5.1 -s 0 -n -v not host $local-ip -w -
> EOF
tcpdump: listening on eth5.1, link-type EN10MB (Ethernet), capture size 65535 bytes
^Ct 23
drew@Drew-Ubuntu:~/Desktop$

The issue that I'm having is that this does allow me to start up a tcpdump. I can see the "Got $counter" values increasing as the tcpdump runs which is great. I can then simply "CTRL + c" in order to stop the capture and my file is generated at my specified location. The issue is that the first command "> sh" shows up in the very first line of this capture file, which stops me from being able to properly open this file for review.

I've tried adding "> sh > /dev/null", but I'm pretty sure that is only going to suppress output on the remote side, and not mine, as it didn't work. I've tried messing with the syntax of this a bunch, but either my command doesn't work entirely, or that first line is included. Hoping there is a proper syntax out there to just populate my local file with the tcpdump information.

Update:

I have since tried to update things to work within a single script that runs my tcpdump capture, and then once cancelled out, sed would clean up the first line as needed. Below is what I have built:

#!/bin/bash

read -p $'\e[32mEnter Remote IP: \e[0m' remote_ip
read -p $'\e[32mEnter Username: \e[0m' username
read -sp $'\e[32mEnter Password: \e[0m' password
echo
read -p $'\e[32mEnter File Save Location and Name: \e[0m' save_file
echo -e '\e[32mEnter tcpdump Options (ie. -i eth1 -s 0 .....)\e[0m'
read -p $'\e[32m*note: You do not need to enter the \"-w\" modifier to save to a file: \e[0m' tcpdump_options

sshpass -p $password ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -T $username@$remote_ip -p 30007 <<- EOF \ > /tmp/Remote_Capture.pcap
        sh
        tcpdump $tcpdump_options -U -w -
EOF

trap '{ sed 1d /tmp/Remote_Capture.pcap > $save_file; rm /tmp/Remote_Capture.pcap; }' SIGINT SIGTERM

The issue with this is that when I enter a CTRL+C, it seems to terminate out of the entire script and not make it to that final line. My capture file gets created in my /tmp directory with that extra line up top, but the sed operations don't actually happen to clean things up and push the cleaned up file to my set location.

Best Answer

You could strip off the first line before the redirection into your file:

sshpass ... "$remote-port" | sed 1d << EOF > /home/drew/Desktop/Example_Capture.pcap
sh
tcpdump -i eth5.1 -s 0 -n -v not host $local-ip -w -
EOF
Related Question