Skip to content

Instantly share code, notes, and snippets.

@meeuw
Last active August 29, 2015 14:10
Show Gist options
  • Save meeuw/c3bc9dd07945c87c89e6 to your computer and use it in GitHub Desktop.
Save meeuw/c3bc9dd07945c87c89e6 to your computer and use it in GitHub Desktop.
find files on a samba share
import hashlib
import sys
import os
import pexpect
import re
class SMBClient():
def __init__(self, host, share, username, password):
self.p = pexpect.spawn('smbclient //%s/%s -U "%s%%%s"' % (host, share, username, password))
self.cmd()
self._re_ls = re.compile(r"""
\s{2} # file lines start with 2 spaces
(.*?)\s+ # capture filename non-greedy, eating remaining spaces
([ADHSRN]*) # capture file mode
\s+ # after the mode you can have any number of spaces
(\d+) # file size
\s+ # spaces after file size
( # begin date capturing
\w{3} # abbrev weekday
\s # space
\w{3} # abbrev month
\s{1,2} # one or two spaces before the day
\d{1,2} # day
\s # a space before the time
\d{2}:\d{2}:\d{2} # time
\s # space
\d{4} # year
) # end date capturing
$ # end of string""", re.VERBOSE)
def cmd(self, command=None):
if command: self.p.sendline(command)
self.p.expect(r'smb:\s.*\>')
return self.p.before
def ls(self, path):
ret = []
for line in self.cmd('ls "%s/*"' % path).splitlines():
m = self._re_ls.match(line)
if m: ret.append(m.groups())
return ret
def recurse(smbclient, dir):
print dir
for fn in smbclient.ls(dir):
if fn[0] in ('.', '..'): continue
if 'D' in fn[1]:
recurse(smbclient, dir+fn[0]+'/')
else:
ext = fn[0].split('.')[-1]
if ext.lower() in ('ttf','ttc','pfa','pfb','otf','otc','cff','sfnt','fnt','bdf','pfr'):
print dir, fn[0], smbclient.cmd('get "%s" %s' % (dir.replace('/', '\\')+fn[0], 'tmp'))
m = hashlib.md5()
with open('tmp') as f:
while 1:
buf = f.read(2048)
if not buf: break
m.update(buf)
digest = m.hexdigest()
if digest == 'd41d8cd98f00b204e9800998ecf8427e':
print 'empty file', fn[0]
if os.path.isdir(digest):
os.remove('tmp')
else:
os.mkdir(digest)
os.rename('tmp', digest+'/'+fn[0])
# username password servername serverip sharename
smbclient = SMBClient(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
recurse(smbclient, '/')
@jean-helsinki
Copy link

Hi, maybe my code will be usefuly for you
https://gist.github.com/jean-helsinki/85b3ea97b7445abdd9a7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment