예제 #1
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()
예제 #2
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")
예제 #3
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')
예제 #4
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()
예제 #5
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
    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')
예제 #7
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
예제 #8
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
 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!")
예제 #10
0
def smb_login(server, domain, user, passwd):
    #randomize client name each time
    client = ''.join([choice(ascii_letters + digits) for x in xrange(7)])
    try:
        #test smb connection
        conn = SMBConnection(user,
                             passwd,
                             client,
                             server,
                             domain=domain,
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        conn.connect(server, 445, timeout=2)
        # list shares with no output to test for valid connection
        conn.listShares(timeout=2)
        conn.close()
        print_success("Success %s %s:%s" % (server, user, passwd))
    except:
        print_failure("Login Failed %s %s:%s" % (server, user, passwd))
예제 #11
0
    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
예제 #12
0
 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
예제 #13
0
def gradeSMB(difficulty):
    print(Style.BRIGHT + '\n'+"-" * 31)
    print("Grading SMB Secure Configuration Lab...")
    print("=" * 31 + Style.NORMAL)

    #Variables
    userID = ''
    password = ''
    myname = ''
    remote_name = ''
    server_ip= '127.0.0.1'

    try:
        conn = SMBConnection(userID, password, myname, remote_name)
        conn.connect(server_ip, 445)
        shares=conn.listShares()
        sharenames=[]
        for share in shares:
            sharenames.append(share.name)
        if ('public' in sharenames):
            smbAuthPass = False
        elif ('homes' in sharenames):
            smbAuthPass = True
        else:
            raise Exception("Can't find neither the public share nor the homes share")
    except Exception as e:
        print(Fore.RED + 'Unknown Exception: '+ Fore.WHITE +'Failed to check SMB Configuration')
    finally:
        conn.close()

    ####Provide Feedback and Record Score for SMB Server Configuration
    message = "-" * 40 + '\n'
    message = message + "Grade for SMB Server Configuration Lab: \n"
    message = message + "-" * 40 + '\n'

    try:
        if(smbAuthPass): #if smb configuration passes
            if (difficulty == "1" or difficulty == "2"):
                print(Fore.GREEN + 'PASS: '******'SMB Configuration was fixed')
            message = message + "(1/1) PASS: SMB Configuration was fixed\n"
        elif(not (smbAuthPass)): #if smb configuration Fails
            if (difficulty == "1" or difficulty == "2"):
                print(Fore.RED + 'FAIL: '+ Fore.WHITE +'SMB Configuration was NOT fixed')
                if(difficulty =="1"):
                    print("  HINT: Remove the entire [public] share in /etc/samba/smb.conf and replace it as a [homes] share")
                    print("    ([homes]\n       comment = Home Directories\n       browseable = yes\n       read only = no\n       create mask = 0700\n       directory mask = 0700\n       valid users = %S)")
            message = message + "(0/1) FAIL: SMB Configuration was NOT fixed\n"
            message = message + "      List of SMB Shares: " + str(sharenames)
    except:
        print(Fore.RED + 'Error: '+ Fore.WHITE +'Failed to record grade for SMB')
        message = message + 'Error: Failed to record grade for SMB\n'

    return message
예제 #14
0
def check_smb(ip, port, anon, share, checkfile, filehash, domain):
    if not domain:
        domain = ""

    conn = SMBConnection("Guest",
                         "",
                         socket.gethostname(),
                         "none",
                         domain,
                         is_direct_tcp=True)
    try:
        conn.connect(ip, port)
    except Exception as e:
        return 0, "Failed to connect to ip: %s on port %s." % (ip, port)

    try:
        shareList = conn.listShares(timeout=5)
        found = False
        for i in range(len(shareList)):
            if shareList[i].name == share:
                found = True
                break

        if found == False:
            return 0, "Samba share %s not found." % (share)
    except Exception as e:
        return 0, "Failed to retrieve list of shares."

    if checkfile and filehash:
        print("[DEBUG-SMB] Grabbing file for", ip)
        tmpfile = path + "engine/tmpfiles/smb-%s-%s-%s-checkfile" % (share, ip,
                                                                     checkfile)
        try:
            with open(tmpfile, "wb") as fp:
                conn.retrieveFile(share, checkfile, fp)

            with open(tmpfile, "rb") as f:
                content = f.read()
                checkhash = hashlib.sha1(content).hexdigest()
            if checkhash != filehash:
                return (0,
                        "Hash %s does not match %s." % (checkhash, filehash))
            return 1, None
        except Exception as e:
            return 0, "Failed to read share %s." % (share)
    else:
        print("[DEBUG-SMB] Trying anonymous/noauth for", ip)
        try:
            fileList = conn.listPath(share, "/")
            return 1, None
        except Exception as e:
            return 0, "Failed to read share %s." % (share)
예제 #15
0
    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):
            shares = smbClient.listShares()

            print "[+] SMB Connection Success ... "
            print "[+] Listing the Shared resources"
            for share in shares:
                print "[*][*] Resource name: %s " %(share.name)
            return True
        else:
            return False
예제 #16
0
 def displayyp(self):
     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()))
     sharelist = conn.listShares()  # 列出共享目录
     yp.delete(0, END)
     for i in sharelist:
         #print(i.name)
         yp.insert(END, i.name)
    def getNetworkShares(self, hostip, hostname):
        sharelist = []
        self.sharecache_file = None
        self.sharecache_file = eEnv.resolve(
            "${sysconfdir}/enigma2/") + hostname.strip(
            ) + '.cache'  #Path to cache directory

        username = "******"
        password = ""
        if os_path.exists(self.sharecache_file):
            print '[Networkbrowser] Loading userinfo from ', self.sharecache_file
            try:
                self.hostdata = load_cache(self.sharecache_file)
                username = self.hostdata['username']
                password = self.hostdata['password']
            except:
                pass

        for port in (445, 139):
            try:
                smbconn = SMBConnection(username,
                                        password,
                                        self._myhostname,
                                        hostname,
                                        is_direct_tcp=(port == 445))
                if smbconn.connect(hostip, port=port, timeout=1):
                    print '[Networkbrowser] established SMB connection to %s:%d' % (
                        hostip, port)
                    for share in smbconn.listShares(timeout=1):
                        if share.type == SharedDevice.DISK_TREE and not share.isSpecial:
                            sharelist.append(
                                NetworkItemSmb(
                                    hostname,
                                    hostip,
                                    share.name.encode('utf-8'),
                                    'Disk',
                                    comment=share.comments.encode('utf-8')))
                    smbconn.close()
                    break
            except Exception as e:
                Log.w('[Networkbrowser] SMBConnection: ' + str(e))
        try:
            exports = showmount(hostip)
        except IOError as e:
            Log.w('[Networkbrowser] showmount: ' + str(e))
        else:
            for ex in exports:
                sharelist.append(
                    NetworkItemNfs(os_path.basename(ex['dir']), hostip,
                                   ex['dir'], ','.join(ex['groups'])))
        return sharelist
예제 #18
0
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')
예제 #19
0
    def searchTarget(self, host, username, password, domainname):
        success = False

        try:
            self.display.debug('### Analyzing system: ' + system_name)
            # 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(system_name, 445)
            success = True

            try:
                Response = conn.listShares(
                    timeout=30)  # obtain a list of shares
                self.display.debug('Shares on: ' + system_name)
                for i in range(
                        len(Response)):  # iterate through the list of shares
                    self.display.debug("  Share[", i, "] =", Response[i].name)
                    try:
                        # list the files on each share (recursivity?)
                        Response2 = conn.listPath(Response[i].name,
                                                  '/',
                                                  timeout=30)
                        self.display.debug(
                            '    Files on: ' + system_name + '/' + "  Share[",
                            i, "] =", Response[i].name)
                        for i in range(len(Response2)):
                            for pattern in self.filepatterns:
                                match_list = fnmatch.filter(
                                    Response2[i].filename, pattern)
                                for fname in match_list:
                                    # host.download(fpath, self.config["proofsDir"] + ip + fpath.replace("/", "_"))
                                    self.display.debug("    File[", i, "] =",
                                                       Response2[i].filename)
                    except:
                        self.display.error('### can not access the resource')
            except:
                self.display.error('### can not list shares')
        except:
            self.display.error('### can not access the system')

        return success
예제 #20
0
def listTarget(target):
	conn = SMBConnection('guest@'+target, '', 'Athena', target, '', True, 2, True)
	try:
		conn.connect(target, 445)
		shares = conn.listShares()
	except:
		return []
	# filter on disks and not special shares only
	shares = [share for share in shares if share.type == SharedDevice.DISK_TREE and not share.isSpecial]
	sharenames = [share.name.encode('ascii') for share in shares]
	# filter out remaining special or administrative shares
	sharenames = [name for name in sharenames if not name.endswith('$')]
	conn.close()
	return sharenames
예제 #21
0
def hostsEnum(hostsFile, ports, user, pword, slptm, addomain, lssubdirs, tmout,
              lsfiles, kwdexp):
    try:
        with io.open(hostsFile, "r") as hosts:
            for host in hosts.read().splitlines():
                for port in ports:
                    try:
                        s = SMBConnection(
                            username=user,
                            password=pword,
                            my_name=gethostname(),
                            remote_name=host,
                            domain=addomain,
                            use_ntlm_v2=True,
                            sign_options=SMBConnection.SIGN_WHEN_REQUIRED,
                            is_direct_tcp=True)
                        s.connect(host, port, timeout=tmout)
                        sleep(slptm)

                        print(
                            "[i] MACHINE NAME: {}\n[i] IP ADDRESS: {}\n[i] PORT: {}\n[i] SHARE INFO:\n"
                            .format(getfqdn(host), host, port))

                        for share in s.listShares():
                            print("{} : {}{}".format(
                                getPermissions("\\\\{}\\{}".format(
                                    host, share.name)), share.name,
                                getShareComments(share.comments)))

                            if lssubdirs:
                                print(
                                    "RESURSIVE SUBDIRECTORY LISTINGS FOR SHARE: \\\\{}\\{}:"
                                    .format(host, share.name))
                                listallsubdirs(
                                    "\\\\{}\\{}".format(host, share.name),
                                    kwdexp)
                            elif lsfiles:
                                print(
                                    "RECURSIVE FILE LISTINGS FOR SHARE: \\\\{}\\{}:"
                                    .format(host, share.name))
                                listallfiles(
                                    "\\\\{}\\{}".format(host, share.name),
                                    kwdexp)

                        print("{}".format("=" * 150))
                    except Exception as e:
                        print("!!!ERROR: {}:{} ({}) - {}\n{}\n".format(
                            host, port, getfqdn(host), e, "=" * 150))
    except KeyboardInterrupt as ki:
        print("[!]: Script Aborted!")
예제 #22
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!")
예제 #23
0
    def main(self):
        self.banner()

        if len(sys.argv) < 5:
            self.usage()

        host = sys.argv[1]

        uwordlist = self.readfile(sys.argv[2])
        pwordlist = self.readfile(sys.argv[3])
        domain = sys.argv[4]

        userTotal = len(uwordlist)
        passTotal = len(pwordlist)
        usercount = 0
        passcount = 0
        print("Bruteforcing.......")
        for user in uwordlist:
            usercount = usercount + 1
            for passwd in pwordlist:
                passcount = passcount + 1

                try:
                    smb = SMBConnection(username=user.decode('utf-8'),
                                        password=passwd.decode('utf-8'),
                                        my_name='',
                                        remote_name=domain,
                                        domain='',
                                        use_ntlm_v2=True,
                                        is_direct_tcp=True)

                    smb.connect(host, 445)

                    shares = smb.listShares()

                except Exception as e:

                    break
                print('\n[+] Username: '******'utf-8') +
                      ' Password: '******'utf-8') + "\t",
                      end='')
                print('\x1b[6;30;42m' + 'Founded!' + '\x1b[0m')

                for share in shares:
                    print('\t\t' + share.name)

                smb.close()

        exit(0)
예제 #24
0
    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
예제 #25
0
파일: GUI.py 프로젝트: ssuhrid/emTv
def lanConnectionInit():
    global _conn
    _conn = SMBConnection(
        'username',
        '',
        ' ',
        ' ',
        '',  # use_ntlm_v2=True,
        # sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
        is_direct_tcp=True)
    connected = _conn.connect('192.168.1.10', 445)
    Response = _conn.listShares(timeout=30)

    for i in range(len(Response)):
        print("Share[", i, "] =", Response[i].name)
예제 #26
0
def smb(host, port=445):
    try:
        conn = SMBConnection("", "", "", "", use_ntlm_v2=True)
        if conn.connect(host, port, timeout=timeout):
            color_print.green(f"[*] smb service detected:{host}:{port}")
            sharelist = conn.listShares()
            for i in sharelist:
                try:
                    conn.listPath(i.name, "/")
                    color_print.red(f"[+] smb unauthorised directory:{host}:{port}/{i.name}")
                except:
                    color_print.green(f"[*] smb directory:{host}:{port}/{i.name}")

        conn.close()
    except:
        pass
예제 #27
0
파일: auth.py 프로젝트: reskontr/nephy
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)
예제 #28
0
def get_shares(target, domain_name, remote_name, username, password):
    my_name = 'WIN-2003'
    logger.verbose('Client name configured to: '+logger.YELLOW(my_name))
    logger.blue('Looking up shares on {}'.format(logger.BLUE(target)))
    server_ip = target
    if remote_name != None:
        logger.verbose('Connection status: [{} | {} | {}]'.format(logger.YELLOW(
            server_ip), logger.YELLOW(remote_name), logger.YELLOW(domain_name)))
    else:
        try:
            logger.verbose('Connection status: [{} | {} | {}]'.format(logger.YELLOW(
                server_ip), logger.YELLOW('Could not resolve name'), logger.YELLOW(domain_name)))
        except:
            pass
    open_shares = []
    if remote_name == None:
        logger.red_indent('Could not get remote hosts name, skipping...')
        return None
    else:
        conn = SMBConnection(username, password, my_name, remote_name,
                             domain=domain_name, use_ntlm_v2=True, is_direct_tcp=True)
        logger.verbose('SMB configuration:')
        logger.verbose('\tConnecting with: {}'.format(logger.YELLOW(username)))
        for k, v in vars(conn).items():
            attribute = str(k)
            value = str(v)
            if '<class' not in value and 'bound method' not in value and 'object' not in value and "b''" not in value:
                logger.verbose('\t'+attribute+': '+value)
    try:
        conn.connect(server_ip, 445)
        logger.green('Successfully connected to {} on {}'.format(
            logger.GREEN('smb'), logger.GREEN(server_ip)))

        try:
            shares = conn.listShares(timeout=15)
            for share in range(len(shares)):
                share_name = str(shares[share].name)
                logger.green_indent_list(logger.GREEN(share_name))
                open_shares.append(share_name)
        except Exception as e:
            logger.red_indent('Got error: {}'.format(logger.RED(e)))

    except:
        logger.red_indent(
            'Failed to obtain shares from {}'.format(logger.RED(server_ip)))

    return open_shares
예제 #29
0
    def listShares(self, username='', password=''):
        smbConnect = SMBConnection(username,
                                   password,
                                   '',
                                   '',
                                   use_ntlm_v2=True)
        smbConnect.connect(str(self.target), self.port)
        shareObjs = smbConnect.listShares()
        shares = {}

        for share in shareObjs:
            if self.listFiles(share.name):
                shares[share.name] = True
            else:
                shares[share.name] = False

        return shares
예제 #30
0
def get_all_shared_files(
        conn: SMBConnection, hostname: str,
        patterns: List[str]) -> Generator[Tuple[str, List[File]], None, None]:
    share_names = [s.name for s in conn.listShares()]
    for pattern_string in patterns:
        pattern = pattern_string.replace("\\**\\**\\",
                                         "\\**\\").strip("\\").split("\\")
        if pattern[0] != hostname:
            raise RuntimeError(
                f"Pattern {pattern_string} doesn't match {hostname} hostname")

        share_name = pattern[1]
        if share_name not in share_names:
            raise RuntimeError(
                f"Share {share_name} doesn't exist on host {hostname}")

        yield pattern_string, list(
            iter_shared_files(conn, hostname, share_name, pattern[2:]))
예제 #31
0
def enumerateShares(ip):
	print "Enumerating file shares on: ", ip
	try:
		conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True) 
		conn.connect(ip, 445) 
	except:
		print "Failed to Connect"
		pass
	try:
		shareList = conn.listShares(timeout=10)
	except:
		shareList=None
	if shareList != None:
		shareNameList=[]
		for x in shareList:
			shareName = x.name
			print shareName
		return shareList
예제 #32
0
def enumShares(hostsFile, ports, user, pword, slptm, addomain, lsdir):
    try:
        with io.open(hostsFile, "r") as hosts:
            for host in hosts.read().splitlines():
                for port in ports:
                    try:
                        s = SMBConnection(
                            user,
                            pword,
                            gethostname(),
                            host,
                            addomain,
                            use_ntlm_v2=True,
                            sign_options=SMBConnection.SIGN_WHEN_REQUIRED,
                            is_direct_tcp=True)
                        s.connect(host, port)
                        sleep(slptm)

                        print(
                            "[i] IP ADDRESS OR MACHINE NAME: {}\n[i] PORT: {}\n[i] SHARE INFO:\n"
                            .format(host, port))

                        for share in s.listShares():
                            print("{} : {}{}".format(
                                getPermissions("\\\\{}\\{}".format(
                                    host, share.name)), share.name,
                                getShareComments(share.comments)))

                            if lsdir:
                                print("DIRECTORY LISTING FOR {}:".format(
                                    share.name))
                                try:
                                    for item in listdir("\\\\{}\\{}".format(
                                            host, share.name)):
                                        print("{}{}".format("   -", item))
                                except Exception as le:
                                    print("MESSAGE: {}".format(le))
                                print("\n")

                        print("\n")
                    except Exception as e:
                        print("MESSAGE: {}:{} - {}\n".format(host, port, e))
    except KeyboardInterrupt as ki:
        print("[!]: Script Aborted!")
예제 #33
0
    def test_find():
        """
        test
        """
        director = urllib2.build_opener(SMBHandler)

        userID = ''
        password = ''
        client_machine_name = 'localpcname'

        server_name = 'servername'
        server_ip = ['10','0','0','10']

        domain_name = 'domainname'

        conn = SMBConnection(userID, password, client_machine_name, server_name, domain=domain_name, use_ntlm_v2=True,
                             is_direct_tcp=True)

        server_addr = '.'.join(server_ip) 
        conn.connect(server_addr, 445)

        shares = conn.listShares()
        # import pudb
        # pudb.set_trace()
        for share in shares:
            if share.name.isupper() and len(share.name) == 1:
                print "Files in {}/".format(share.name)
                sharedfiles = None
                try:
                    sharedfiles = conn.listPath(share.name, '/Movies/')
                except Exception:
                    continue
                if sharedfiles:
                    for file in sharedfiles:
                    #     if sharedfile.filename == "Movies":
                            # path = "smb://'':''@" + server_addr + "/" + share.name
                            # print "{} was found in {}".format(sharedfile.filename, path)
                            # movies = conn.listPath(share.name + '/' + sharedfile.filename, '/')
                            # for m in movies:
                            #     print m.filename
                            # movies = director.open(path)
                        if not file.filename.startswith("."):\
                            print file.filename
        conn.close()
예제 #34
0
    def createList(self, ipList, outfile):
        with open(outfile, 'a') as out:
            for ip in ipList:
                out.write(
                    "\n----------------------------------------------------\n")
                print "Attempting to access: ", ip
                out.write("Attempting to access: %s \n" % ip)
                try:
                    conn = SMBConnection('guest',
                                         '',
                                         client_machine_name,
                                         remote_machine_name,
                                         use_ntlm_v2=True)
                    conn.connect(ip, 139)
                    print "Connected to: ", ip
                    out.write("Connected To: %s \n" % ip)
                except:
                    print "Failed to Connect"
                    out.write("Failed to Connect To: %s \n" % ip)
                    pass
                try:
                    shareList = conn.listShares()
                except:
                    out.write("Failed to open Shares\n")
                    shareList = None
                if shareList != None:
                    for x in shareList:
                        try:
                            out.write("found Share: %s \n" % x.name)
                            print "Listing files in share: ", x.name
                            out.write("Listing files in share: %s \n" % x.name)
                            filelist = conn.listPath(x.name, '/')
                            for y in filelist:
                                if y.isDirectory:
                                    print "DIR", y.filename
                                out.write("-----")
                                out.write(y.filename)
                                out.write('\n')
                        except:
                            print "failed to open share: ", x.name
                            out.write("Failed to open Share: %s \n" % x.name)

        print "report written to outfile.txt"
예제 #35
0
def enum_thread(args, 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 for s in conn.listShares()
        if s.type == smb.base.SharedDevice.DISK_TREE
    ]
    for s in shares:
        logger.debug('Crawling share ' + s)
        crawl_share(conn, s)
    conn.close()
예제 #36
0
    def get_smb_connection_with_shares(self, host):
        connection = SMBConnection("RaspBerryPi$", "K3ks3!", "Testtest", host["hostname"], use_ntlm_v2 = True)

        if not connection.connect(host["address"], 139):
            raise NotConnectedError()

        shares = connection.listShares()

        smb_connection = {
            "connection": connection,
            "shares": [],
        }

        for share in shares:
            if share.isSpecial or share.isTemporary:
                continue
            smb_connection["shares"].append(share)

        return smb_connection
예제 #37
0
    def searchTarget(self, host, username, password, domainname):
        success = False

        try:
            self.display.debug('### Analyzing system: ' + system_name)
            # 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(system_name, 445)
            success = True

            try:
                Response = conn.listShares(timeout=30)  # obtain a list of shares
                self.display.debug('Shares on: ' + system_name)
                for i in range(len(Response)):  # iterate through the list of shares
                    self.display.debug("  Share[", i, "] =", Response[i].name)
                    try:
                        # list the files on each share (recursivity?)
                        Response2 = conn.listPath(Response[i].name, '/', timeout=30)
                        self.display.debug('    Files on: ' + system_name + '/' + "  Share[", i, "] =",
                                           Response[i].name)
                        for i in range(len(Response2)):
                            for pattern in self.filepatterns:
                                match_list = fnmatch.filter(Response2[i].filename, pattern)
                                for fname in match_list:
                                    # host.download(fpath, self.config["proofsDir"] + ip + fpath.replace("/", "_"))
                                    self.display.debug("    File[", i, "] =", Response2[i].filename)
                    except:
                        self.display.error('### can not access the resource')
            except:
                self.display.error('### can not list shares')
        except:
            self.display.error('### can not access the system')

        return success
예제 #38
0
	def createList(self, ipList, outfile):
		with open(outfile, 'a') as out:
			for ip in ipList:
				out.write("\n----------------------------------------------------\n")
				print "Attempting to access: ", ip
				out.write("Attempting to access: %s \n" % ip)
				try:
					conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True)
					conn.connect(ip, 139)
					print "Connected to: ", ip
					out.write("Connected To: %s \n" % ip)
				except:
					print "Failed to Connect"
					out.write("Failed to Connect To: %s \n" % ip)
					pass
				try:
					shareList = conn.listShares()
				except:
					out.write("Failed to open Shares\n")
					shareList = None
				if shareList != None:
					for x in shareList:
						try:
							out.write("found Share: %s \n" % x.name)
							print "Listing files in share: ", x.name
							out.write("Listing files in share: %s \n" % x.name)
							filelist = conn.listPath(x.name, '/')
							for y in filelist:
								if y.isDirectory:
									print "DIR", y.filename
								out.write("-----")
								out.write(y.filename)
								out.write('\n')
						except:
							print "failed to open share: ", x.name
							out.write("Failed to open Share: %s \n" % x.name)

		print "report written to outfile.txt"
예제 #39
0
	def getNetworkShares(self, hostip, hostname):
		sharelist = []
		self.sharecache_file = None
		self.sharecache_file = eEnv.resolve("${sysconfdir}/enigma2/") + hostname.strip() + '.cache' #Path to cache directory

		username = "******"
		password = ""
		if os_path.exists(self.sharecache_file):
			print '[Networkbrowser] Loading userinfo from ',self.sharecache_file
			try:
				self.hostdata = load_cache(self.sharecache_file)
				username = self.hostdata['username']
				password = self.hostdata['password']
			except:
				pass

		for port in (445, 139):
			try:
				smbconn = SMBConnection(username, password, self._myhostname, hostname, is_direct_tcp=(port == 445))
				if smbconn.connect(hostip, port=port, timeout=1):
					print '[Networkbrowser] established SMB connection to %s:%d' % (hostip, port)
					for share in smbconn.listShares(timeout=1):
						if share.type == SharedDevice.DISK_TREE and not share.isSpecial:
							sharelist.append( NetworkItemSmb(hostname, hostip, share.name.encode('utf-8'), 'Disk', comment=share.comments.encode('utf-8')) )
					smbconn.close()
					break
			except Exception as e:
				Log.w('[Networkbrowser] SMBConnection: ' + str(e))
		try:
			exports = showmount(hostip)
		except IOError as e:
			Log.w('[Networkbrowser] showmount: ' + str(e))
		else:
			for ex in exports:
				sharelist.append( NetworkItemNfs(os_path.basename(ex['dir']), hostip, ex['dir'], ','.join(ex['groups'])) )
		return sharelist
예제 #40
0
class SMB_client():
	def __init__(self,username=None,password=None,smb_name=None,print_errors=True):
		self.username     = username
		self.password     = password
		self.smb_name     = smb_name
		self.print_errors = print_errors
		self.smb_ip       = None
		self.conn         = None
		self.service_name = None
		self.my_name      = None
		self.error        = None
		self.tree         = []

	def getBIOSName(self, remote_smb_ip, timeout=5):			# unused if dynamic IP
		# ip -> smb name
		try:
			self.error = None
			bios = NetBIOS()
			srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
			return srv_name[0]
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
			return None
			
	def getIP(self):
		# smb name -> ip
		try:
			self.error = None
			bios = NetBIOS()
			ip = bios.queryName(self.smb_name)
			return ip[0]
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
			return None
			
	def connect(self):
		try:
			self.error = None
			self.my_name = gethostname()				# iDevice name
			self.smb_ip = self.getIP()
			smb_structs.SUPPORT_SMB2 = True
			self.conn = SMBConnection(self.username, self.password, self.my_name, self.smb_name, use_ntlm_v2 = True)
			self.conn.connect(self.smb_ip, 139)		#139=NetBIOS / 445=TCP
			if self.conn:
				shares = self.conn.listShares()
				for share in shares:
					if share.type == 0:		# 0 = DISK_TREE
						self.service_name = share.name  
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
			
	def close(self):
		try:
			self.error = None
			self.conn.close()
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
 
	def getRemoteDir(self, path, pattern):
		try:
			self.error = None
			files = self.conn.listPath(self.service_name, path, pattern=pattern)
			return files
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
			return None
				
	def getRemoteTree(self,path=''):
		try:
			self.error = None
			if path == '':
				w = ''
			else:
				w = path+'/'
			files = self.getRemoteDir(path, '*')
			if files:
				for file in files:
					if file.filename[0] == '.':
						continue
					self.tree.append({'name':w+file.filename, 'isdir':file.isDirectory, 'size':file.file_size})
					if file.isDirectory:
						self.getRemoteTree(path=w+file.filename)
			return self.tree
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
			return None

	def download(self, path, filename,buffersize=None,callback=None, local_path=None):
		try:
			self.error = None
			#print('Download = ' + path + filename)
			attr = self.conn.getAttributes(self.service_name, path+filename)
			#print('Size = %.1f kB' % (attr.file_size / 1024.0))
			#print('start download')
			file_obj = BytesIO()
			if local_path:
				fw = open(local_path+filename, 'wb')
			else:
				fw = open(filename, 'wb')
			offset = 0
			transmit =0
			while True:
				if not buffersize:
					file_attributes, filesize = self.conn.retrieveFile(self.service_name, path+filename, file_obj)
				else:
					file_attributes, filesize = self.conn.retrieveFileFromOffset(self.service_name, path+filename, file_obj,offset=offset,max_length=buffersize)
					if callback:
						transmit = transmit + filesize
						callback(transmit)
				file_obj.seek(offset)
				for line in file_obj:
					fw.write(line)
				offset = offset + filesize
				if (not buffersize) or (filesize == 0):
					break
			fw.close()
			#print('download finished')
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
			
	def upload(self, path, filename,buffersize=None,callback=None, local_path=None):
		try:
			self.error = None
			#print('Upload = ' + path + filename)
			#print('Size = %.1f kB' % (os.path.getsize(filename) / 1024.0))
			#print('start upload')
			if local_path:
				file_obj = open(local_path+filename, 'rb')
			else:
				file_obj = open(filename, 'rb')
			offset = 0
			while True:
				if not buffersize:
					filesize = self.conn.storeFile(self.service_name, path+filename, file_obj)
					break
				else:	
					buffer_obj = file_obj.read(buffersize)			
					if buffer_obj:
						buffer_fileobj = BytesIO()
						buffer_fileobj.write(buffer_obj)
						buffer_fileobj.seek(0)
						offset_new = self.conn.storeFileFromOffset(self.service_name, path+filename, buffer_fileobj, offset=offset, truncate=False)
						#return the file position where the next byte will be written.
						offset = offset_new
						if callback:
							callback(offset)
					else:
						break
			file_obj.close()
			#print('upload finished')
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)

	def delete_remote_file(self,path, filename):
		try:
			self.error = None
			self.conn.deleteFiles(self.service_name, path+filename)
			#print('Remotefile ' + path + filename + ' deleted')
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)

	def createRemoteDir(self, path):
		try:
			self.error = None
			self.conn.createDirectory(self.service_name, path)
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
  
	def removeRemoteDir(self,path):
		try:
			self.error = None
			self.conn.deleteDirectory(self.service_name, path)
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)

	def renameRemoteFileOrDir(self,old_path, new_path):
		try:
			self.error = None
			self.conn.rename(self.service_name, old_path, new_path)
		except Exception as e:
			if self.print_errors:
				print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
			else:
				self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
예제 #41
0
파일: mount.py 프로젝트: tkmpypy/nasmount
# -*- coding: utf-8 -*-

from smb.SMBConnection import SMBConnection
from subprocess import *
import os
import sys


USER_NAME = 'NASのログインユーザ'
PASSWORD = '******'
CLIENT_USER_NAME = 'クライアントのユーザ名'
SERVER_NAME = 'NASのホスト名'
SERVER_IP = 'NASのIP'

if __name__ == '__main__':

    conn = SMBConnection(USER_NAME, PASSWORD, CLIENT_USER_NAME, SERVER_NAME)
    
    conn.connect(SERVER_IP)

    for path in conn.listShares():
        if not os.path.exists('/Volumes/' + path.name):
            os.mkdir('/Volumes/' + path.name)

        try:
            res = run(['mount_smbfs', '//'+USER_NAME +'@'+SERVER_NAME+ '/' + path.name, '/Volumes/' + path.name], stdout=PIPE)
            sys.stdout.buffer.write(res.stdout)
        except:
            sys.stdout.buffer.write("ERROR")
예제 #42
0
#!/usr/bin/python

import sys
from smb.SMBConnection import SMBConnection

host = sys.argv[1]
domain = ""
conn = SMBConnection("guest", "guest", "workgroup", host, domain, True, 2)
conn.connect(host, 139)

shares = conn.listShares()
for share in shares:
	print("Share: %s" % share.name)

conn.close()
class CommonCIFSShare(object):
    """
    Handle CIFS shares
    """

    def __init__(self):
        self.smb_conn = None

    def com_cifs_connect(self, ip_addr, user_name='guest', user_password=''):
        """
        Connect to share
        """
        server_name = 'Server'
        client_name = 'My Computer'
        self.smb_conn = SMBConnection(user_name, user_password, client_name, server_name,
                                      use_ntlm_v2=True)
        self.smb_conn.connect(ip_addr, 139)

    def com_cifs_share_list_by_connection(self):
        """
        List shares
        """
        share_names = []
        for row_data in self.smb_conn.listShares():
            share_names.append(row_data.name)
        return share_names

    def com_cifs_share_file_list_by_share(self, share_name, path_text='/'):
        """
        List files in share
        """
        file_names = []
        for row_data in self.smb_conn.listPath(share_name, path_text):
            common_global.es_inst.com_elastic_index('info', {'stuff': row_data.filename})
            file_names.append(row_data.filename)
        return file_names

    def com_cifs_share_directory_check(self, share_name, dir_path):
        """
        Verify smb directory
        """
        # try due to fact invalid file/path freaks out the connection
        try:
            return self.smb_conn.getAttributes(share_name, dir_path).isDirectory
        except:
            pass
        return False

    def com_cifs_share_file_dir_info(self, share_name, file_path):
        """
        Get specific path/file info
        """
        return self.smb_conn.getAttributes(share_name, file_path)

    def com_cifs_share_file_upload(self, file_path):
        """
        Upload file to smb
        """
        self.smb_conn.storeFile(os.path.join(
            self.sharename, file_path), open(file_path, 'rb'))

    def com_cifs_share_file_download(self, file_path):
        """
        Download from smb
        """
        self.smb_conn.retrieveFile(self.sharename, open(file_path, 'wb'))

    def com_cifs_share_file_delete(self, share_name, file_path):
        """
        Delete from smb
        """
        self.smb_conn.deleteFiles(os.path.join(share_name, file_path))

    def com_cifs_close(self):
        """
        Close connection
        """
        self.smb_conn.close()

    def com_cifs_walk(self, share_name, file_path='/'):
        """
        cifs directory walk
        """
        dirs, nondirs = [], []
        for name in self.smb_conn.listPath(share_name, file_path):
            if name.isDirectory:
                if name.filename not in ['.', '..']:
                    dirs.append(name.filename)
            else:
                nondirs.append(name.filename)
        yield file_path, dirs, nondirs
        for name in dirs:
            #           new_path = file_path + '\\' + name
            #            for ndx in self.com_cifs_walk(share_name, new_path):
            for ndx in self.com_cifs_walk(share_name, os.path.join(file_path, name)):
                yield ndx
예제 #44
0
def SMB_Connect(host,sharename,user,password,folder,writeable):
	'''connects to a share with the given credentials and checks if it's writeable or not
		host: hostname (FQDN)
		sharename: Name of the share
		username: username
		password: password
		writeable: if set to True, it will check if the share is writeable
	'''

	check_passed=False
	check_file=''.join(['/', folder,'/nagioscheck.txt'])
	hostname = host.split('.')
	host_ip= socket.gethostbyname(host)
	conn = SMBConnection(user, password, socket.gethostname(), hostname[0], use_ntlm_v2 = True)
	try:
		conn.connect(host_ip, 139)
	except:
		print "Connection to Host failed"
		sys.exit(status['CRITICAL'])
	
	if conn.auth_result:

		#only check if share is listed
		if not writeable:
			shares = conn.listShares()
			for share in shares:
				if sharename == share.name:
					print "Found ",share.name
					check_passed = True
					break
		else:
			#schreiben
			check_value = "File Created from nagios "+str(datetime.now())
			file_obj = tempfile.NamedTemporaryFile()
			file_obj.write(check_value)
			file_obj.flush()
			file_obj.seek(0)
			try:
				conn.storeFile(sharename,  check_file, file_obj)
			except:
				check_passed=False
			file_obj.close()

			#lesen
			file_obj = tempfile.NamedTemporaryFile()
			try:
				file_attributes, filesize = conn.retrieveFile(sharename,  check_file, file_obj)
				file_obj.seek(0)
				file_content= file_obj.read()
				if file_content == check_value:
					check_passed=True
			except:
				check_passed=False
			file_obj.close()
			conn.close()
			
			 #file loeschen
			try:
				conn = SMBConnection(user, password, socket.gethostname(), hostname[0], use_ntlm_v2 = True)
			 	conn.connect(host_ip, 139)
			 	conn.deleteFiles(sharename, check_file)
			except Exception, e:
			 	check_passed=False
			
		conn.close()