Tips:Simple Bash Ad-hoc file sharing

From Wiki

Jump to: navigation, search
TIPS edit

FreeBSD vnode SambaHPing3 (patch)Fetchmail (POP3s)NetBSD pkgsrc under OSXSimple Bash Ad-hoc file sharing256 colors in Urxvt

Goal

To have a simple way of sharing files accross the network from the command-line. This method only require nc to have the sockets up and running, and common unix tools (ifconfig,stat,grep,cut,file). Add the following function in your bash dotfile (bashrc, bash_profile, whatever you use) and enjoy file sharing using share filename.

  • Note that this function simulate the behaviour of a real HTTP server, sending the correct headers.
  • It has been developed for both Mac OSX and Linux. Maybe *BSD ?
# written in bash
function share() {
	! have nc && die "This machine doesn't have 'nc'" && return
	[[ $# -ne 1 ]] && die "Usage: share <filename>" && return
	[[ ! -f $1 ]] && die "No such file : $1" && return
	port=$((8000 + RANDOM%1000))
	if [[ $OSTYPE == darwin[0-9]* ]] ; then
		ip=$(/sbin/ifconfig | egrep inet[^6] | fgrep -v 127.0.0.1 | cut -d" " -f2)
		for i in $ip ; do echo "http://$i:$port/$1" ; done
		cat - "$1" <<- EOF | $(type -p nc) -l -w 30 $port
			HTTP/1.1 200 OK\r
			Content-Length: $(stat -f %z "$1")
			Content-Type: $(file -b --mime-type "$1") 
			EOF
	elif [[ $OSTYPE == "linux-gnu" ]] ; then
		ip=$(/sbin/ifconfig | grep "inet addr" | egrep -v 127.0.0.1 | cut -d: -f2 | cut -d" " -f1)
		for i in $ip ; do echo "http://$i:$port/$1" ; done
		cat - "$1" <<- EOF | $(type -p nc) -l -p $port -q 0
			HTTP/1.1 200 OK\r
			Content-Length: $(stat -c %s "$1")
			Content-Type: $(file -b --mime-type "$1") 
			EOF
	fi
}

References

Personal tools