#!/usr/bin/python
from subprocess import check_output
import re, sys, argparse

parser = argparse.ArgumentParser(description='A simple script to enumerate the accessible SMB shares in a given list of targets')
parser.add_argument('-H', '--hst',help='The file containing the target systems, one per line', required=True)
parser.add_argument('-u', '--usr',help='The username to log in with', required=False, default='')
parser.add_argument('-d', '--dom',help='The domain to log in with', required=False, default='')
parser.add_argument('-p', '--pwd',help='The password to log in with', required=False, default='')
parser.add_argument('-V', '--verbose',help='Enable verbose mode', required=False, default=True)
parser.add_argument('-D', '--debug',help='Enable debug mode', required=False, default=False)
args = vars(parser.parse_args())

debug=args['debug']
verbose=args['verbose']
usr=args['usr']
dom=args['dom']
pwd=args['pwd']
hstfile=args['hst']

with open(hstfile) as hfile:
   for hst in hfile:
      if verbose:
         print "Trying host: " + hst.rstrip('\n')
      shareDiscoveryCommand = "timeout 5 smbclient -L " + str(hst.rstrip('\n')) + " -U '" + str(dom) + "'/'" + str(usr) + "'%'" + str(pwd) + "' 2>/dev/null | grep Disk | awk {'print $1'}"
      if debug:
         print "Running the following command:\n" + shareDiscoveryCommand
      shrs = check_output(shareDiscoveryCommand, shell=True)
      if debug:
         print "Discovered the following shares\n" + shrs
      for shr in shrs.split('\n'):
         if bool(re.search('[a-zA-Z0-9]', shr)):
            shr = shr.replace('$', '\$')
            if verbose:
               print "Trying share: " + shr + "@" + hst.rstrip('\n')
            shareAccessCommand = "smbclient \\\\\\\\" + str(hst.rstrip('\n')) + "\\\\" + str(shr) + " -U " + str(dom) + "/" + str(usr) + " '" + str(pwd) + "' -c ls 2>/dev/null"
            if debug:
               print "Running the following command:\n" + shareAccessCommand
            try:
               listing = check_output(shareAccessCommand, shell=True)
               print listing
            except:
               print "No access to share"
