10/28/09

Forwarding Samba over SSH - Plus! an easy to use script

Here is a simple example for connecting to a samba server:

ssh -L 22330:SAMBA_SERVER:139 USER_NAME@SSH_SERVER

smbmount //SAMBA_SERVER/SHARE_NAME /PATH/TO/SHARE_MOUNT --verbose -o ip=127.0.0.1,port=22330,credentials=/PATH/TO/CREDS/FILE


Now my problem was I need to make an easy to use way for dev's to access samba without installing a VPN. They also needed to make two hops from an access server to another ssh server then finally the samba server.

Here is the two hop method on one line:

ssh -t -t -L 22330:localhost:22330 USER_NAME@SSH_SERVER "ssh -t -t -L 22330:SAMBA_SERVER:139 INTERNAL_SSH_SERVER_IP"

-t Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

Now for the script, Its written in two parts, one script for creating the tunnel, the other for mounting the smb share.

createsshtunnel.sh
----------------------------------------------------------
#!/bin/bash
#This script will forward a randomly generated port for tunneling samba connections

username=user_name
PORT=$[ ( $RANDOM % ( $[ 22999 - 22000 ] + 1 ) ) + 22000 ]

echo " "
echo Port Number is: $PORT
echo " "
echo " "
echo "Creating Samba Tunnel"
ssh -t -t -L $PORT:localhost:$PORT $username@ssh_server "ssh -t -t -L $PORT:SAMBA_SERVER:139 INTERNAL_SSH_SERVER"
-------------------------------------------------------------------------

mountsamba.sh
------------------------------------------------------------------------
#!/bin/bash
#This will mount samba shares in combination with the sambassh.sh script
#Enter in the port number returned from sambassh.sh

#Location of a credentials file (chmod 600 file)
#Format:
#username=
#password=

credentials=/PATH/TO/creds

echo " "
echo "Enter Port Number:"
read portnumber
echo "$portnumber is "
echo "Which Share?"
read sharename

if [ -d "~/$sharename" ]
then
echo "Mount Point Exists, trying to unmount if its mounted"
sudo umount "~/$sharename"
echo " "
else
echo "Directory "~/$sharename" does not exist, creating for you."
echo " "
mkdir "~/$sharename"
fi

smbmount //SMB_SERVER/$sharename ~/$sharename --verbose -o ip=127.0.0.1,port=$portnumber,credentials=$credentials
----------------------------------------------------------------------