Skip to content

Instantly share code, notes, and snippets.

@DoctorD90
Created August 22, 2020 09:34
Show Gist options
  • Save DoctorD90/9da10b24c5ccea2da6f5f3adffc13bd7 to your computer and use it in GitHub Desktop.
Save DoctorD90/9da10b24c5ccea2da6f5f3adffc13bd7 to your computer and use it in GitHub Desktop.
Receive and send file via netcat tool
#!/bin/bash
# COMMANDS
# 1) Receive a file
# nctransfer r ListenPort ?FileToReceive?
#
# 2) Send a file
# nctransfer s ServerIP ServerPort FileToSend
if [ "$1" == "r" ]; then
# Receive mode
# Check args number
if [[ "$#" < 2 ]]; then
echo "Error: missing parameters"
echo "$0 r ListenPort ?FileToReceive?"
exit
fi
# Listen Port
myport="$2"
# File name to transfer
if [[ "$#" < 3 ]]; then
# Received by the sender
myfile="$(nc -vvv -l -p "$myport")"
else
# Decided by terminal
nc -vvv -l -p "$myport" > /dev/null
myfile="$3"
fi
# Netcat waiting file
nc -vvv -l -p "$myport" > "$myfile"
# Waiting for md5 hash
mynchash="$(nc -vvv -l -p "$myport")"
# Calculate md5 hash of received file
myhash="$(md5sum "$myfile"|awk '{print $1}')"
# Compare the md5 hash
if [ "$mynchash" == "$myhash" ]; then
echo Transfer completed successfully!
else
echo Transfer FAILED!
fi
elif [ "$1" == "s" ]; then
# Send mode
# Check args number
if [[ "$#" < 4 ]]; then
echo "Error: missing parameters"
echo "$0 s ServerIP ServerPort FileToSend"
exit
fi
# Server IP
myip="$2"
# Server Port
myport="$3"
# File to transfer
myfile="$4"
# Send the file name
echo "$myfile" | nc -vvv -q 1 "$myip" "$myport"
sleep 1
if [ ! -e "$myfile" ]; then
# Check if file exists
echo "Error: $myfile doesn't exist"
exit
else
# Calculate md5 hash of file
myhash="$(md5sum "$myfile"|awk '{print $1}')"
fi
# Send the file
nc -vvv -q 1 "$myip" "$myport" < "$myfile"
sleep 1
# Send the md5 hash
echo "$myhash" | nc -vvv -q 1 "$myip" "$myport"
else
# Not defined mode
echo "Error: Choose mode r(eceive) or s(end)"
echo " - Receive: $0 r Port ?FileToReceive?"
echo " - Send: $0 s ServerIP ServerPort FileToSend"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment