Example #1
0
    def discover_smb_shares(self):
        """
            scan the local network for active smb shares
        """
        # do some host discovery

        nm = NmapProcess(settings.LOCAL_NET, options="-sT -p 139 -n")
        net_bios = NetBIOS(broadcast=True)

        # might get a problem on windows... but tool is supposed to run under linux =) so its fine
        if nm.sudo_run() == 0:
            # get the scan report
            print(nm.stdout)
            report = NmapParser.parse(nm.stdout)
            interesting_hosts = []
            # find the hosts that are online and have an open port that indicates smb
            for host in report.hosts:
                if host.status == "up":
                    if len(host.get_open_ports()) != 0:
                        # check whether it is a host we might access with smb
                        hostname = net_bios.queryIPForName(host.address)[0]
                        if hostname is None:
                            continue
                        interesting_hosts.append({
                            "address": host.address,
                            "hostname": hostname})
        else:
            raise NoInterestingHostsFound

        return interesting_hosts
Example #2
0
 def run(self):
     print "Starting thread for " + self.ip
     net = NetBIOS()
     net_name = str(net.queryIPForName(self.ip)).strip("['").strip("']")
     net.close()
     conn = SMBConnection(self.user,
                          self.pwd,
                          'cobwebs',
                          net_name,
                          domain=self.domain,
                          use_ntlm_v2=False)
     if conn.connect(self.ip, port=139, timeout=10):
         print(
             "Connecting to %s was successful! How about a nice game of spidering %s%s?"
             % (self.ip, self.share, self.subfolder))
     else:
         print("Connection error: %s" % (self.ip))
     if self.recursive > 0:
         recurse(conn, self.ip, self.share, self.subfolder, self.pattern,
                 int(self.recursive))
     else:
         filelist = conn.listPath(self.share, self.subfolder)
         dir_list(filelist, self.ip, self.subfolder, self.pattern)
     conn.close()
     print "Exiting thread for " + self.ip
Example #3
0
def dowload_latest_image(sysConf):
    serverIP = sysConf.imgServer['IP']
    netbios = NetBIOS()
    serverName = netbios.queryIPForName(serverIP)
    conn = SMBConnection(sysConf.imgServer['USER'],
                         sysConf.imgServer['PASSWORD'],
                         my_name="BMC_Tester",
                         remote_name=serverName[0],
                         domain="COMPAL")
    if (False == conn.connect(serverIP)):
        return None
    platformImage = "BMC/Daily_Build/" + sysConf.platform
    path = conn.listPath(sysConf.imgServer['ROOT'], platformImage)
    sortedFile = sorted(path, key=attrgetter('create_time'))
    lastFile = sortedFile[len(sortedFile) - 1]
    imagePath = os.getcwd() + "/download"

    if not os.path.exists(imagePath):
        os.mkdir(imagePath)

    image = open(imagePath + "/" + lastFile.filename, "wb")
    print("\tDownloading %s to %s ....." %
          (lastFile.filename, imagePath + "/" + lastFile.filename))
    conn.retrieveFile(sysConf.imgServer['ROOT'],
                      platformImage + "/" + lastFile.filename, image)
    image.close()
    return lastFile.filename
Example #4
0
    def _test_connectivity(self, param):

        config = self.get_config()

        ip = config['ip']
        port = int(param.get('port', 137))
        timeout = int(param.get('timeout', 30))

        action_result = ActionResult(dict(param))
        self.add_action_result(action_result)

        self.save_progress("Looking up IP : {0} to test connectivity".format(ip))
        nb = NetBIOS()
        hosts = nb.queryIPForName(ip, port, timeout)
        if hosts is None:
            self.save_progress("Request timed out")
            self.save_progress("Test Connectivity Failed")
            return action_result.set_status(phantom.APP_ERROR)

        if hosts:
            self.save_progress("Got {0} hosts".format(len(hosts)))
            self.save_progress("Test Connectivity Passed")
            return action_result.set_status(phantom.APP_SUCCESS)

        self.save_progress("Lookup did not return any results, but connectivity passed")

        return action_result.set_status(phantom.APP_SUCCESS)
Example #5
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
Example #6
0
    def performTest(self):
        if(not self.smb):
            randomUser = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
            randomPass = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
            print("%sPerforming test request to benchmark failed attempt...%s" % (Y,W))

            if(not self.ntlm):
                self.test_response = self.performRequest(randomUser, randomPass)
            else:
                self.test_response = self.performNTLMRequest(randomUser, randomPass)

            self.test_hexDigest = self.getHashFromResponse(self.test_response)

            if(self.test_response.status_code == 400):
                print("%sTest request returned status code " % (R) + str(self.test_response.status_code) + "%s" % (W))
                if(input("Are you sure you want to continue? (y/N) ") != 'y'):
                    sys.exit("Unsatisfactory HTTP response code.")
            else:
                print("%sTest request did not return 400, moving on.%s\n" % (G,W))
        else:
            print("%sAttempting to reach machine for SMB login...%s" % (Y,W))
            n = NetBIOS()
            ip = n.queryIPForName(self.ip)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                s.connect((self.ip, 445))
                s.shutdown(2)
                print("%sMachine is available on port 445, moving on.%s\n" % (G,W))
            except:
                print("%sCan't reach machine on port 445" % (R) + str(self.test_response.status_code) + "%s" % (W))
                if(input("Are you sure you want to continue? (y/N) ") != 'y'):
                    sys.exit("Double check IP and port 445 open.")
                return False
Example #7
0
def getServerName(IP):
    try:
        server = NetBIOS()
        servername = server.queryIPForName(IP)
        return servername[0]
    except:
        print(Fore.RED+"You need to porvide the remote computer or server name")
        exit(0)
Example #8
0
def get_netbios_name(remote_addr):
    nb = NetBIOS()
    names = nb.queryIPForName(remote_addr)
    nb.close()
    if len(names) == 0:
        raise NameError('No NetBIOS name found for {}'.format(remote_addr))
    elif len(names) > 1:
        logging.warn('More than one NetBIOS name for {}'.format(remote_addr))
    return names[0]
Example #9
0
def ip2hostname(ip):
    nb = NetBIOS(broadcast=True, listen_port=0)
    try:
        hostname = nb.queryIPForName(str(ip), port=137, timeout=10)
        hostname = hostname[0]
    except:
        print 'hostname get fail please use -n'
        exit(0)
    return str(hostname)
Example #10
0
def getBIOSName(timeout=30):
    try:
        bios = NetBIOS()
        srv_name = bios.queryIPForName('172.25.73.100', timeout=timeout)
    except:
        print("Looking up timeout, check remote_smb_ip again!!", sys.stderr)
    finally:
        bios.close()
        return srv_name
Example #11
0
def get_netbios_name(remote_addr, timeout=DEFAULT_TIMEOUT):
    nb = NetBIOS()
    names = nb.queryIPForName(remote_addr, timeout=timeout)
    nb.close()
    if names is None or len(names) == 0:
        raise NameError('No NetBIOS name found for {}'.format(remote_addr))
    elif len(names) > 1:
        logging.warn('More than one NetBIOS name for {}'.format(remote_addr))
    return names[0]
Example #12
0
File: smbutil.py Project: MSTU/grid
def getBIOSName(remote_smb_ip, timeout=30):
	try:
		bios = NetBIOS()
		srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
	except:
		print >> sys.stderr, "Looking up timeout, check remote_smb_ip again!!"
	finally:
		bios.close()
		return srv_name
Example #13
0
File: smbutil.py Project: MSTU/grid
def getBIOSIp(remote_smb_name, timeout=30):
	try:
		bios = NetBIOS()
		server_ip_list = bios.queryName(remote_smb_name, timeout=timeout)
	except:
		print >> sys.stderr, "Looking up timeout, check remote_smb_name again!!"
	finally:
		bios.close()
		return server_ip_list
Example #14
0
def getBIOSName(remote_smb_ip, timeout=30):
    try:
        bios = NetBIOS()
        srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
    except:
        print(sys.stderr, "Looking up timeout, check remote_smb_ip again!!")
    finally:
        bios.close()
        return srv_name
Example #15
0
 def getServerName(self, remote_smb_ip, timeout=30):
     bios = NetBIOS()
     srv_name = None
     try:
         srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
     except:
         log.err("Couldn't find SMB server name, check remote_smb_ip again!!")
     finally:
         bios.close()
         return srv_name
Example #16
0
def getBIOSName(remote_smb_ip, timeout=5):
    try:
        bios = NetBIOS()
        srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
    except:
        print 'getBIOSName: timeout too short?'
    finally:
        bios.close()
        #print 'bios name = ' + srv_name[0]
        return srv_name[0]
Example #17
0
 def getServerName(self, remote_smb_ip, timeout=30):
     bios = NetBIOS()
     srv_name = None
     try:
         srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
     except:
         log.err(
             "Couldn't find SMB server name, check remote_smb_ip again!!")
     finally:
         bios.close()
         return srv_name
Example #18
0
def reverse_host(host, timeout=1, save=True):
    n = NetBIOS()
    try:
        host.hostname = n.queryIPForName(host.ip_address, timeout=timeout)[0]
    except:
        pass
    n.close()
    host.reverse_latest_time = timezone.datetime.now()
    if save:
        host.save()
    return host
Example #19
0
def reverse_host(host, timeout=1, save=True):
    n = NetBIOS()
    try:
        host.hostname = n.queryIPForName(host.ip_address, timeout=timeout)[0]
    except:
        pass
    n.close()
    host.reverse_latest_time = timezone.datetime.now()
    if save:
        host.save()
    return host
Example #20
0
def get_netbios_name(hostname):
    if hostname in ["127.0.0.1", "localhost"]:
        return "localhost"
    n = NetBIOS()
    resp = n.queryIPForName(hostname)
    if resp:
        return resp[0]
    else:
        # Default to first part of hostname
        # eg: smbsrv01.example.com -> smbsrv01
        dns_name = socket.gethostbyaddr(hostname)[0]  # "nslookup"
        return dns_name.split(".")[0]
Example #21
0
File: libsmb.py Project: w1s0/addon
def get_server_name_ip(server):
    if re.compile("^\d+.\d+.\d+.\d+$").findall(server) or re.compile("^([^\.]+\.(?:[^\.]+\.)?(?:\w+)?)$").findall(server):
        server_ip = server
        server_name = None
    else:
        server_ip = None
        server_name = server.upper()

    if not server_ip: server_ip = NetBIOS().queryName(server_name)[0]
    if not server_name: server_name = NetBIOS().queryIPForName(server_ip)[0]

    return server_name, server_ip
Example #22
0
    def get_BIOSName(self, host, timeout=30):
        try:
            bios = NetBIOS()
            srv_name = bios.queryIPForName(host, timeout=timeout)

        except Exception as e:
            logger.error("Looking up timeout, check remote_smb_ip again. %s" %
                         str(e))

        finally:
            bios.close()
            return srv_name
Example #23
0
	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
Example #24
0
def getBIOSName(remote_smb_ip, timeout=30):
    # 通过IP地址,查找smb服务器的名称
    srv_name = None

    bios = NetBIOS()
    try:
        srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
    except:
        print "查找samba服务器的名称时超时。"
    finally:
        bios.close()

    return srv_name
Example #25
0
def clean_up(ip, share, subfolder, user, pwd, domain):
	net = NetBIOS()
	net_name = str(net.queryIPForName(ip)).strip("['").strip("']")
	net.close()
	conn = SMBConnection(user, pwd, 'cobwebs', net_name, domain=domain, use_ntlm_v2=True, is_direct_tcp=True)
	if conn.connect(ip, port=445, timeout=10):
		print(Fore.GREEN+"[+] Connection to %s Successful! Cleaning up SCF's Now!" % ip + Style.RESET_ALL)
	else:
		print(Fore.RED+"[!] Connection to %s Failed!" % ip + Style.RESET_ALL)

	delete_file(conn, ip, subfolder, share)

	conn.close()
Example #26
0
	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
Example #27
0
def get_server_name_ip(server):
    import re
    if re.compile("^\d+.\d+.\d+.\d+$").findall(server):
        server_ip = server
        server_name = None
    else:
        server_ip = None
        server_name = server.upper()

    if not server_ip: server_ip = NetBIOS().queryName(server_name)[0]
    if not server_name: server_name = NetBIOS().queryIPForName(server_ip)[0]

    return server_name, server_ip
Example #28
0
 def __resolve__(self, server:str):  # str | None
     # If no valid IP adres, try to obtain it
     # First as netBIOS on LAN
     nb = NetBIOS(broadcast=True, listen_port=0)
     # Send a query on the network and hopes that if machine matching the name will reply with its IP address.
     res = nb.queryName(server, ip='', port=NETBIOS_PORT, timeout=NETBIOS_TIMEOUT)
     if isinstance(res, list) and len(res) > 0 and isinstance(res[0], str) and self.isIP4(res[0]):
         return res[0]
     # Try to DNS resolve
     try:
         return socket.gethostbyname(server)
     except socket.gaierror as sge:
         # Nope, didn't work
         return None
Example #29
0
def getBIOSName(remote_smb_ip, timeout=5):
    # Devuelvo el nombre NetBios de una máquina remota
    from nmb.NetBIOS import NetBIOS
    Aux = 'ERROR'
    try:
        bios = NetBIOS()
        srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
        Aux = srv_name[0]
    except:
        print 'No es posible conocer el nombre NETBIOS del servidor ' + remote_smb_ip + ' en el tiempo ' + str(
            timeout)
    finally:
        bios.close()
    return Aux
    def __init__(self, session, iface, plugin_path):
        Screen.__init__(self, session)
        self.skin_path = plugin_path
        self.session = session
        self.iface = iface or 'eth0'
        for service in eNetworkManager.getInstance().getServices():
            key = self.getServiceIF(service)
            if key:
                self.iface = key
                break
        self.networklist = []
        self.expanded = []
        self.cache_ttl = 604800  #Seconds cache is considered valid, 7 Days should be ok
        self.cache_file = eEnv.resolve(
            "${sysconfdir}/enigma2/networkbrowser.cache"
        )  #Path to cache directory
        self._nrthreads = 0
        self._netbios = NetBIOS(broadcast=False)
        self._ipv4 = iNetworkInfo.getConfiguredInterfaces()[self.iface].ipv4
        self._myhostname = self._lookupHostname(self._ipv4.address, local=True)

        self["key_red"] = StaticText(_("Close"))
        self["key_green"] = StaticText(_("Mounts"))
        self["key_yellow"] = StaticText(_("Rescan"))
        self["key_blue"] = StaticText(_("Expert"))
        self["infotext"] = StaticText(_("Press OK to mount!"))

        self["shortcuts"] = ActionMap(
            ["ShortcutActions", "WizardActions"], {
                "ok": self.go,
                "back": self.close,
                "red": self.close,
                "green": self.keyGreen,
                "yellow": self.keyYellow,
                "blue": self.keyBlue,
            })

        self.list = []
        self.statuslist = []
        self.listindex = 0
        self["list"] = List(self.list)
        self["list"].onSelectionChanged.append(self._onSelectionChanged)

        self.onLayoutFinish.append(self.startRun)
        self.onShown.append(self.setWindowTitle)
        self.onClose.append(self.cleanup)
        self.Timer = eTimer()
        self.Timer_conn = self.Timer.timeout.connect(self.TimerFire)
Example #31
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))
Example #32
0
def get_server_name_ip(server):
    if re.compile("^\d+.\d+.\d+.\d+$").findall(server) or re.compile("^([^\.]+\.(?:[^\.]+\.)?(?:\w+)?)$").findall(server):
        server_ip = server
        server_name = None
    else:
        server_ip = None
        server_name = server.upper()

    if not server_ip: server_ip = NetBIOS(broadcast=False).queryName(server_name, timeout=5)
    if isinstance(server_ip, (list, tuple)) and len(server_ip) > 0: server_ip = server_ip[0]
    if not server_ip: server_ip = ''
    if not server_name: server_name = NetBIOS(broadcast=False).queryIPForName(server_ip, timeout=5)
    if isinstance(server_name, (list, tuple)) and len(server_name) > 0: server_name = server_name[0]
    if not server_name: server_name = ''

    return server_name, server_ip
 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 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
Example #35
0
def get_name(target, timeout=5):
    logger.blue('Getting NetBIOS Name for {}'.format(logger.BLUE(target)))
    logger.verbose('Timeout for NetBIOS resolution: '+str(timeout))
    bios = NetBIOS()
    try:
        tmpnetbios_name = bios.queryIPForName(target, timeout=timeout)
        netbios_name = str(tmpnetbios_name[0])
    except:
        netbios_name = None
    bios.close()
    if netbios_name == None:
        logger.red_indent('Failed to get NetBIOS Name')
        return None
    else:
        logger.green_indent('Got NetBIOS Name: {}'.format(
            logger.GREEN(netbios_name)))
        return str(netbios_name)
Example #36
0
 def run(self):
    print "Starting thread for " + self.ip
    net = NetBIOS()
    net_name = str(net.queryIPForName(self.ip)).strip("['").strip("']")
    net.close()
    conn = SMBConnection(self.user, self.pwd, 'cobwebs', net_name, domain=self.domain, use_ntlm_v2 = False)
    if conn.connect(self.ip, port=139, timeout=10):
       print ("Connecting to %s was successful! How about a nice game of spidering %s%s?" % (self.ip, self.share, self.subfolder))
    else:
       print ("Connection error: %s" % (self.ip))
    if self.recursive > 0:
       recurse(conn,self.ip,self.share,self.subfolder,self.pattern,int(self.recursive))    
    else:
       filelist = conn.listPath(self.share, self.subfolder)
       dir_list(filelist,self.ip,self.subfolder,self.pattern)
    conn.close()
    print "Exiting thread for " + self.ip
Example #37
0
def run(options):
    ip = options['ip']
    port = options['port']
    username = options['username']
    password = options['password']

    test = random.choice(config.SMB_FILES)
    expected = test['checksum']

    try:
        n = NetBIOS()
        hostname = n.queryIPForName(ip)[0]
        n.close()

        conn = SMBConnection(username, password, '', hostname, config.DOMAIN)
        conn.connect(ip, port)
        t = tempfile.TemporaryFile()
        conn.retrieveFile(test['sharename'], test['path'], t)
    except (SMBTimeout, socket.timeout):
        logger.debug('Timeout')
        return False
    except NotReadyError:
        logger.debug(ERROR_STRINGS['NotReadyError'] % (username, password))
        return False
    except (NotConnectedError, UnsupportedFeature, ProtocolError, OperationFailure) as e:
        name = e.__class__.__name__
        if name in ERROR_STRINGS:
            logger.debug(ERROR_STRINGS[name] % e)
        else:
            logger.debug('%s: %s' % (name, e))
        return False

    sha1 = hashlib.sha1()
    t.seek(0)
    sha1.update(t.read())
    t.close()
    checksum = sha1.hexdigest()

    if checksum == expected:
        return True
    else:
        logger.debug('Check failed: output: %s | expected: %s' % (checksum, expected))
        return False
Example #38
0
def get_name(target, timeout=2):
    logger.live_info('[{}]:\tATTEMPTING NETBIOS NAME'.format(logger.BLUE(target)))

    # logger.verbose('Timeout for NetBIOS resolution: '+str(timeout))
    logger.verbose('[{}]:\tNETBIOS TIMEOUT: {}'.format(logger.YELLOW(target),logger.YELLOW(str(timeout))))
    bios = NetBIOS()
    try:
        tmpnetbios_name = bios.queryIPForName(target, timeout=timeout)
        netbios_name = str(tmpnetbios_name[0])
    except:
        netbios_name = None

    bios.close()
    if netbios_name == None:
        logger.live_bad('[{}]:\tNETBIOS NAME: {}'.format(logger.RED(target),logger.RED('FAILED')))
        return None
    else:
        logger.green('[{}]:\tNETBIOS NAME: {}'.format(logger.GREEN(target),logger.GREEN(netbios_name)))
        return str(netbios_name)
Example #39
0
    def connect(self, ip, port = 139, sock_family = socket.AF_INET, timeout = 60):
        """
        Establish the SMB connection to the remote SMB/CIFS server.

        You must call this method before attempting any of the file operations with the remote server.
        This method will block until the SMB connection has attempted at least one authentication.

        :return: A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise.
        """

        # Was an IP address provided?

        try:
            if socket.inet_pton(socket.AF_INET, ip):
                # IP address provided
                n = NetBIOS()
                names = n.queryIPForName(ip)
                if names:
                    self.remote_name = names[0]
        except:
            # Hostname provided
            self.remote_name = ip
        
        if self.sock:
            self.sock.close()
        self.auth_result = None
        self.sock = socket.socket(sock_family)
        self.sock.settimeout(timeout)
        self.sock.connect(( ip, port ))

        self.is_busy = True
        try:
            if not self.is_direct_tcp:
                self.requestNMBSession()
            else:
                self.onNMBSessionOK()
            while self.auth_result is None:
                self._pollForNetBIOSPacket(timeout)
        finally:
            self.is_busy = False

        return self.auth_result
	def __init__(self, session, iface,plugin_path):
		Screen.__init__(self, session)
		self.skin_path = plugin_path
		self.session = session
		self.iface = iface or 'eth0'
		for service in eNetworkManager.getInstance().getServices():
			key = self.getServiceIF(service)
			if key:
				self.iface = key
				break
		self.networklist = []
		self.expanded = []
		self.cache_ttl = 604800 #Seconds cache is considered valid, 7 Days should be ok
		self.cache_file = eEnv.resolve("${sysconfdir}/enigma2/networkbrowser.cache") #Path to cache directory
		self._nrthreads = 0
		self._netbios = NetBIOS(broadcast=False)
		self._ipv4 = iNetworkInfo.getConfiguredInterfaces()[self.iface].ipv4
		self._myhostname = self._lookupHostname(self._ipv4.address, local=True)

		self["key_red"] = StaticText(_("Close"))
		self["key_green"] = StaticText(_("Mounts"))
		self["key_yellow"] = StaticText(_("Rescan"))
		self["key_blue"] = StaticText(_("Expert"))
		self["infotext"] = StaticText(_("Press OK to mount!"))
		
		self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
		{
			"ok": self.go,
			"back": self.close,
			"red": self.close,
			"green": self.keyGreen,
			"yellow": self.keyYellow,
			"blue": self.keyBlue,
		})

		self.list = []
		self.statuslist = []
		self.listindex = 0
		self["list"] = List(self.list)
		self["list"].onSelectionChanged.append(self._onSelectionChanged)

		self.onLayoutFinish.append(self.startRun)
		self.onShown.append(self.setWindowTitle)
		self.onClose.append(self.cleanup)
		self.Timer = eTimer()
		self.Timer_conn = self.Timer.timeout.connect(self.TimerFire)
Example #41
0
target_ip = None
target_nb_name = None
try:
    socket.inet_aton(target)
    print('Target is an IP address')
    target_ip = target
except OSError as e:
    print('Target is not an IP address, trying DNS resolution')
    try:
        target_ip = socket.gethostbyname(target)
        print('Target is DNS resolvable')
    except socket.gaierror as e:
        print('Target is not DNS resolvable, assuming NB name')
        target_nb_name = target

nb = NetBIOS()

if target_ip is None:
    print('Looking up IP from target NetBIOS name ' + target_nb_name)
    ips = nb.queryName(target_nb_name)
    print('Got IPs:' + str(ips))
    if ips is None or len(ips) < 1:
        raise RuntimeError('Cannot connect to host ' + target + '; looking up NetBIOS IP failed')
    target_ip = ips[0]

if target_nb_name is None:
    print('Looking up NetBIOS name from target IP: ' + target_ip)
    nb_names = nb.queryIPForName(target_ip)
    print('Got NB names: ' + str(nb_names))
    if nb_names is None or len(nb_names) < 1:
        raise RuntimeError('Cannot connect to host ' + target + '; looking up NetBIOS name failed')
Example #42
0
def test_broadcast():
    global conn
    conn = NetBIOS()
    assert conn.queryName('MICHAEL-I5PC', timeout = 10)
Example #43
0
def queryNam():
        n = NetBIOS(broadcast=True, listen_port=0)
        ip = n.queryIPForName("192.168.40.26", port=137, timeout=1)
        return ip
Example #44
0
    def smb_open(self, req):
        global USE_NTLM, MACHINE_NAME

        host = req.get_host()
        if not host:
            raise urllib.error.URLError('SMB error: no host given')
        host, port = splitport(host)
        if port is None:
            port = 139
        else:
            port = int(port)

        # username/password handling
        user, host = splituser(host)
        if user:
            user, passwd = splitpasswd(user)
        else:
            passwd = None
        host = unquote(host)
        user = user or ''
        passwd = passwd or ''
        myname = MACHINE_NAME or self.generateClientMachineName()

        n = NetBIOS()
        names = n.queryIPForName(host)
        if names:
            server_name = names[0]
        else:
            raise urllib.error.URLError('SMB error: Hostname does not reply back with its machine name')

        path, attrs = splitattr(req.get_selector())
        if path.startswith('/'):
            path = path[1:]
        dirs = path.split('/')
        dirs = list(map(unquote, dirs))
        service, path = dirs[0], '/'.join(dirs[1:])

        try:
            conn = SMBConnection(user, passwd, myname, server_name, use_ntlm_v2 = USE_NTLM)
            conn.connect(host, port)

            headers = email.message.Message()
            if req.has_data():
                data_fp = req.get_data()
                filelen = conn.storeFile(service, path, data_fp)

                headers.add_header('Content-length', '0')
                fp = BytesIO(b"")
            else:
                fp = self.createTempFile()
                file_attrs, retrlen = conn.retrieveFile(service, path, fp)
                fp.seek(0)

                mtype = mimetypes.guess_type(req.get_full_url())[0]
                if mtype:
                    headers.add_header('Content-type', mtype)
                if retrlen is not None and retrlen >= 0:
                    headers.add_header('Content-length', '%d' % retrlen)

            return addinfourl(fp, headers, req.get_full_url())
        except Exception as ex:
            raise urllib.error.URLError('smb error: %s' % ex).with_traceback(sys.exc_info()[2])
class NetworkBrowser(Screen):
	skin = """
		<screen name="NetworkBrowser" position="center,120" size="820,520" title="Network Neighbourhood">
		<ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40" alphatest="on"/>
		<ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40" alphatest="on"/>
		<ePixmap pixmap="skin_default/buttons/yellow.png" position="410,5" size="200,40" alphatest="on"/>
		<ePixmap pixmap="skin_default/buttons/blue.png" position="610,5" size="200,40" alphatest="on"/>
		<widget source="key_red" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>
		<widget source="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>
		<widget source="key_yellow" render="Label" position="410,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>
		<widget source="key_blue" render="Label" position="610,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>
		<eLabel	position="10,50" size="800,1" backgroundColor="grey"/>
		<widget source="infotext" render="Label" position="10,55" size="800,420" zPosition="1" font="Regular;22" halign="center" valign="center"/>
		<widget source="list" render="Listbox" position="10,55" size="800,420" zPosition="2" enableWrapAround="1" scrollbarMode="showOnDemand">
			<convert type="TemplatedMultiContent">
				{"template": [
				MultiContentEntryPixmapAlphaTest(pos = (10,5),size = (50,50),png = 1),# index 1 is the expandable/expanded/verticalline icon
				MultiContentEntryText(pos = (70,4),size = (700,26),font=2,flags = RT_HALIGN_LEFT,text = 2),# index 2 is the Hostname
				MultiContentEntryText(pos = (180,5),size = (610,25),font=0,flags = RT_HALIGN_LEFT,text = 3),# index 3 is the sharename
				MultiContentEntryText(pos = (180,26),size = (610,18),font=1,flags = RT_HALIGN_LEFT,text = 4),# index 4 is the sharedescription
				MultiContentEntryPixmapAlphaTest(pos = (65,5),size = (50,50),png = 5),# index 5 is the nfs/cifs icon
				MultiContentEntryPixmapAlphaTest(pos = (125,5),size = (50,50),png = 6),# index 6 is the isMounted icon
				],
				"fonts": [gFont("Regular",22),gFont("Regular",18),gFont("Regular",24)],
				"itemHeight": 60
				}
			</convert>
		</widget>
	</screen>"""

	def __init__(self, session, iface,plugin_path):
		Screen.__init__(self, session)
		self.skin_path = plugin_path
		self.session = session
		self.iface = iface or 'eth0'
		for service in eNetworkManager.getInstance().getServices():
			key = self.getServiceIF(service)
			if key:
				self.iface = key
				break
		self.networklist = []
		self.expanded = []
		self.cache_ttl = 604800 #Seconds cache is considered valid, 7 Days should be ok
		self.cache_file = eEnv.resolve("${sysconfdir}/enigma2/networkbrowser.cache") #Path to cache directory
		self._nrthreads = 0
		self._netbios = NetBIOS(broadcast=False)
		self._ipv4 = iNetworkInfo.getConfiguredInterfaces()[self.iface].ipv4
		self._myhostname = self._lookupHostname(self._ipv4.address, local=True)

		self["key_red"] = StaticText(_("Close"))
		self["key_green"] = StaticText(_("Mounts"))
		self["key_yellow"] = StaticText(_("Rescan"))
		self["key_blue"] = StaticText(_("Expert"))
		self["infotext"] = StaticText(_("Press OK to mount!"))
		
		self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
		{
			"ok": self.go,
			"back": self.close,
			"red": self.close,
			"green": self.keyGreen,
			"yellow": self.keyYellow,
			"blue": self.keyBlue,
		})

		self.list = []
		self.statuslist = []
		self.listindex = 0
		self["list"] = List(self.list)
		self["list"].onSelectionChanged.append(self._onSelectionChanged)

		self.onLayoutFinish.append(self.startRun)
		self.onShown.append(self.setWindowTitle)
		self.onClose.append(self.cleanup)
		self.Timer = eTimer()
		self.Timer_conn = self.Timer.timeout.connect(self.TimerFire)

	def getServiceIF(self, service):
		key = None
		if service.state() == eNetworkManager.STATE_ONLINE:
			iface = NetworkInterface(service)
			key = iface.ethernet.interface
		return key

	def cleanup(self):
		del self.Timer

	def startRun(self):
		self.expanded = []
		self.setStatus('update')
		self["infotext"].setText("")
		self.vc = valid_cache(self.cache_file, self.cache_ttl)
		if self.cache_ttl > 0 and self.vc != 0:
			self.process_NetworkIPs()
		else:
			self.Timer.start(3000)

	def TimerFire(self):
		self.Timer.stop()
		self.process_NetworkIPs()

	def setWindowTitle(self):
		self.setTitle(_("Browse network neighbourhood"))

	def keyGreen(self):
		self.session.open(AutoMountManager, None, self.skin_path)

	def keyYellow(self):
		if (os_path.exists(self.cache_file) == True):
			remove(self.cache_file)
		self.startRun()

	def keyBlue(self):
		self.session.openWithCallback(self.scanIPclosed,ScanIP)

	def scanIPclosed(self,result):
		if result[0]:
			# scan subnet outside ipv4.address/24
			if result[1] == "address":
				print "[Networkbrowser] got IP:",result[0]
				self.setStatus('update')
				net = IPNetwork('%s/24' % result[0])
				localnet = IPNetwork('%s/%s' % (self._ipv4.address, self._ipv4.netmask))
				if localnet.__contains__(net):
					self._startScan(self.iface, net.cidr)
				else:
					for host in net.iter_hosts():
						self._nrthreads += 1
						reactor.callInThread(self.getNetworkIPs, str(host))
			# add offline host
			elif result[1] == "nfs":
				self.networklist.append(NetworkItemHost(result[0], result[0], ['nfs']))
				write_cache(self.cache_file, self.networklist)
				self.updateNetworkList()

	def setStatus(self,status = None):
		if status:
			self.statuslist = []
			if status == 'update':
				statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/update.png"))
				self.statuslist.append(( ['info'], statuspng, _("Searching your network. Please wait..."), None, None, None, None ))
				self['list'].setList(self.statuslist)
			elif status == 'error':
				#TODO nicer pixmap
				statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/error.png"))
				self.statuslist.append(( ['info'], statuspng, _("No network devices found!"), None, None, None, None ))
				self['list'].setList(self.statuslist)

	def process_NetworkIPs(self):
		self.inv_cache = 0
		self.vc = valid_cache(self.cache_file, self.cache_ttl)
		if self.cache_ttl > 0 and self.vc != 0:
			Log.i('Loading network cache from %s' %(self.cache_file))
			try:
				self.networklist = load_cache(self.cache_file)
				if len(self.networklist) > 0:
					self.updateNetworkList()
				else:
					self.setStatus('error')
			except:
				self.inv_cache = 1
		if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
			Log.i('Getting fresh network list')

			net = IPNetwork('%s/%s' % (self._ipv4.address, self._ipv4.netmask))
			if net.prefixlen < 24:
				net.prefixlen = 24

			self.networklist = []
			self._startScan(self.iface, net.cidr)

	def _startScan(self, iface, cidr):
			cmd = "arp-scan -gqNx --retry=1 --interface=%s %s" % (iface, cidr)
			Log.i("Command: %s" % cmd)
			self._arpscan_container = eConsoleAppContainer()
			self._arpscan_appClosed_conn = self._arpscan_container.appClosed.connect(self._onArpScanClosed)
			self._arpscan_dataAvail_conn = self._arpscan_container.dataAvail.connect(self._onArpScanData)

			self._arpscan_hosts = []
			self._arpscan_container.execute(cmd)

	def _onArpScanData(self, data):
		for line in data.splitlines():
			try:
				(address, mac) = line.split()
			except:
				Log.w('Unexpected line: %s' % line)
			else:
				self._arpscan_hosts.append(address)

	def _onArpScanClosed(self, retval):
		Log.i("arp-scan closed, retval=%d" % retval)
		for host in self._arpscan_hosts:
			self._nrthreads += 1
			reactor.callInThread(self.getNetworkIPs, host)

	def _probeTcpPort(self, host, port):
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.settimeout(1)
		try:
			sock.connect((host, port))
		except:
			Log.w("Connection to %s:%d failed" % (host, port))
			found = False
		else:
			Log.i("Detected service on %s:%d" % (host, port))
			found = True
		sock.close()
		return found

	def getNetworkIPs(self, host):
		Log.i("Detecting availablility of NFS or SMB services on host %s" % host)
		item = None
		services = []

		if self._probeTcpPort(host, 445) or self._probeTcpPort(host, 139):
			Log.i("Found SMB server on %s" % host)
			services.append("smb")

		if rpcinfo.progping('udp', host, 'nfs') or rpcinfo.progping('tcp', host, 'nfs'):
			Log.i("Found NFS server on %s" % host)
			services.append("nfs")

		if services:
			hostname = self._lookupHostname(host)
			item = NetworkItemHost(hostname, host, services)

		Log.i(item)
		reactor.callFromThread(self._onNetworkIPsReady, item)

	def _onNetworkIPsReady(self, item):
		self._nrthreads -= 1
		Log.i("Waiting for %d more threads" % self._nrthreads)
		if item:
			self.networklist.append(item)
		self._updateUI(self._nrthreads == 0)

	def _updateUI(self, finished=True):
		write_cache(self.cache_file, self.networklist)
		if len(self.networklist) > 0:
			self.updateNetworkList()
		elif finished:
			self.setStatus('error')

	def _onError(self, *args, **kwargs):
		Log.w()

	def _lookupHostname(self, addr, local=False):
		names = self._netbios.queryIPForName(addr, timeout=1)
		if names:
			return sorted(names)[0]

		try:
			fqdn = socket.getnameinfo((addr, 0), socket.NI_NAMEREQD)[0]
		except:
			pass
		else:
			hostname = fqdn.split('.', 1)[0]
			if hostname:
				return hostname

		if local:
			hostname = socket.gethostname()
			if hostname:
				return hostname

		return addr

	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

	def updateNetworkList(self):
		self.list = []
		network = {}
		for item in self.networklist:
			network[item.host] = item
		Log.i(network)
		for ip in sorted(network.keys()):
			host = network[ip]
			self.list.append(self._buildNetworkHostEntry(host))
			if ip in self.expanded:
				shares = self.getNetworkShares(ip, host.name.strip())
				#close empty to avoid permanent reloading
				if not shares:
					self.expanded.remove(ip)
				for share in shares:
					self.list.append(self._buildNetworkShareEntry(share))

		self["list"].setList(self.list)
		self["list"].setIndex(self.listindex)

	def _buildNetworkHostEntry(self, item):
		name = item.host
		if item.name != item.host:
			name = "%s (%s)" %(name, item.name)
		icon = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/host.png"))
		return (item, icon, name, None, None, None, None)

	def _buildNetworkShareEntry(self, share):
		verticallineIcon = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/verticalLine.png"))
		if share.type == NetworkItem.TYPE_NFS:
			newpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/i-nfs.png"))
		else:
			newpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/i-smb.png"))

		isMounted = False
		mounts = iAutoMount.getMounts()
		for sharename, sharedata in mounts.items():
			if sharedata['ip'] == share.host:
				if share.type == NetworkItem.TYPE_NFS and sharedata['mounttype'] == 'nfs':
					if share.path == sharedata['sharedir'] and sharedata["isMounted"]:
						isMounted = True
				elif share.type == NetworkItem.TYPE_SMB and sharedata['mounttype'] == 'cifs':
					if share.path == sharedata['sharedir'] and sharedata["isMounted"]:
						isMounted = True
		if isMounted:
			isMountedpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/ok.png"))
		else:
			isMountedpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkBrowser/icons/cancel.png"))

		return (share, verticallineIcon, None, share.path, share.comment, newpng, isMountedpng)

	def _onSelectionChanged(self):
		current = self["list"].getCurrent()
		self.listindex = self["list"].getIndex()
		if current:
			current = current[0]
			if not isinstance(current, NetworkItem):
				return
			if current.type == NetworkItem.TYPE_HOST:
				if current.host in self.expanded:
					self["infotext"].setText(_("Press OK to collapse this host"))
				else:
					self["infotext"].setText(_("Press OK to expand this host"))
			else:
				self["infotext"].setText(_("Press OK to mount this share!"))

	def go(self):
		item = self["list"].getCurrent()[0]
		if item is None or not isinstance(item, NetworkItem):
			return
		self.hostcache_file = "%s%s.cache" %(eEnv.resolve("${sysconfdir}/enigma2/"), item.name) #Path to cache directory
		if item.type == NetworkItem.TYPE_HOST: # host entry selected
			if item.host in self.expanded:
				self.expanded.remove(item.host)
				self.updateNetworkList()
				return
			else:
				if os_path.exists(self.hostcache_file):
					print '[Networkbrowser] Loading userinfo cache from ',self.hostcache_file
					try:
						self.hostdata = load_cache(self.hostcache_file)
						self.passwordQuestion(False)
						return
					except:
						Log.w("error loading host cache!")
			if "smb" in item.services:
				self.session.openWithCallback(self.passwordQuestion, MessageBox, text=_("Do you want to enter a username and password for this host?\n"), default=False )
			else:
				self.passwordQuestion(False)
		else:
			self.openMountEdit(item)

	def passwordQuestion(self, ret = False):
		item = self["list"].getCurrent()[0]
		if ret:
			self.session.openWithCallback(self.UserDialogClosed, UserDialog, self.skin_path, item.name)
			return
		if item.type == NetworkItem.TYPE_HOST: # host entry selected
			if item.host in self.expanded:
				self.expanded.remove(item.host)
			else:
				self.expanded.append(item.host)
			self.updateNetworkList()
		else:
			self.openMountEdit(item)

	def UserDialogClosed(self, *ret):
		if ret is not None and len(ret):
			self.go()

	def openMountEdit(self, item):
		if item and item.type != NetworkItem.TYPE_HOST:
			mounts = iAutoMount.getMounts()
			self.sharecache_file = None
			if item.type == NetworkItem.TYPE_NFS: # share entry selected
				data = iAutoMount.DEFAULT_OPTIONS_NFS
			if item.type == NetworkItem.TYPE_SMB: # share entry selected
				data = iAutoMount.DEFAULT_OPTIONS_CIFS
				self.sharecache_file = eEnv.resolve("${sysconfdir}/enigma2/") + item.name.strip() + '.cache' #Path to cache directory
				if os_path.exists(self.sharecache_file):
					print '[Networkbrowser] Loading userinfo from ',self.sharecache_file
					try:
						self.hostdata = load_cache(self.sharecache_file)
						data['username'] = self.hostdata['username']
						data['password'] = self.hostdata['password']
					except:
						pass
			data['active'] = True
			data['ip'] = item.host
			data['sharename'] = item.name
			data['sharedir'] = item.path
			for sharename, sharedata in mounts.items():
				if sharedata['ip'] == item.host and sharedata['sharedir'] == item.path:
					data = sharedata
					break
			Log.i(data)
			self.session.openWithCallback(self.MountEditClosed,AutoMountEdit, self.skin_path, data)

	def MountEditClosed(self, returnValue = None):
		if returnValue == None:
			self.updateNetworkList()
Example #46
0
    def smb_open(self, req):
        global USE_NTLM, MACHINE_NAME

        host = req.get_host()
        if not host:
            raise urllib2.URLError('SMB error: no host given')
        host, port = splitport(host)
        if port is None:
            port = 139
        else:
            port = int(port)

        # username/password handling
        user, host = splituser(host)
        if user:
            user, passwd = splitpasswd(user)
        else:
            passwd = None
        host = unquote(host)
        user = user or ''

        domain = ''
        if ';' in user:
            domain, user = user.split(';', 1)

        passwd = passwd or ''
        myname = MACHINE_NAME or self.generateClientMachineName()

        n = NetBIOS()
        names = n.queryIPForName(host)
        if names:
            server_name = names[0]
        else:
            raise urllib2.URLError('SMB error: Hostname does not reply back with its machine name')

        path, attrs = splitattr(req.get_selector())
        if path.startswith('/'):
            path = path[1:]
        dirs = path.split('/')
        dirs = map(unquote, dirs)
        service, path = dirs[0], '/'.join(dirs[1:])

        try:
            conn = SMBConnection(user, passwd, myname, server_name, domain=domain, use_ntlm_v2 = USE_NTLM)
            conn.connect(host, port)

            if req.has_data():
                data_fp = req.get_data()
                filelen = conn.storeFile(service, path, data_fp)

                headers = "Content-length: 0\n"
                fp = StringIO("")
            else:
                fp = self.createTempFile()
                file_attrs, retrlen = conn.retrieveFile(service, path, fp)
                fp.seek(0)

                headers = ""
                mtype = mimetypes.guess_type(req.get_full_url())[0]
                if mtype:
                    headers += "Content-type: %s\n" % mtype
                if retrlen is not None and retrlen >= 0:
                    headers += "Content-length: %d\n" % retrlen

            sf = StringIO(headers)
            headers = mimetools.Message(sf)

            return addinfourl(fp, headers, req.get_full_url())
        except Exception, ex:
            raise urllib2.URLError, ('smb error: %s' % ex), sys.exc_info()[2]