Crawler, Platform & PII#
Filesystem crawler and SQLite/CSV/Excel persistence engine for LANspector.
- lanspector.crawler.crawl(path, scantype='fd', permissions=True, fout=None, tablename=None, max_md5=None, skip_size=False, chunksize=900, crawl_acls=True, summarize=False, sunburst_html=None, limit=0, max_depth=0, detect_pii_content=False, use_ner=False, resume=False, show_progress=None)[source]#
Crawl path, harvesting filesystem metadata, ACLs, and optional PII findings.
- Parameters:
- path
Root directory or UNC fileshare path to crawl.
- scantype
Objects to yield:
"d"(directories only),"f"(files only), or"fd"(both directories and files).- permissions
When
True, harvest effective NTFS or POSIX permissions for each object.- fout
Destination output path (
.db,.sqlite,.sqlite3,.csv,.xlsx). WhenNone, results are returned in-memory onCrawlResult.- tablename
Timestamp table name for SQLite output (defaults to UTC
YYYYMMDDTHHMMSS).- max_md5
Compute MD5 digests for files smaller than this size in bytes (
Nonedisables).- skip_size
When
Trueandscantype="d", skip summing file sizes inside directories.- chunksize
Number of objects buffered per database write batch (defaults to
DEFAULT_CHUNKSIZE).- crawl_acls
When writing to SQLite on Windows, also resolve Active Directory group membership.
- summarize
When writing to SQLite, generate a formatted Excel audit workbook after crawling.
- sunburst_html
Optional path to export an interactive Plotly HTML storage sunburst chart.
- limit
Stop crawling after harvesting this many objects (
0means unlimited).- max_depth
Maximum directory depth below path to traverse (
0means unlimited).- detect_pii_content
Inspect supported files (
.txt,.csv,.xlsx) for PII keywords.- use_ner
Enable optional NLTK proper-name detection when
detect_pii_content=True.- resume
When
Trueand writing to an existing SQLite database, resume the latest incomplete crawl (scan_end IS NULLinCRAWL_INFO) for path — or explicitly resume tablename — skipping already-persisted directories and files.- show_progress
Show a single-line
tqdmprogress bar on stderr. Defaults toNone(automatically enabled on interactive TTY terminals and disabled in piped/CI logs).
- Returns:
- CrawlResult
Structured crawl outcome including table name, output paths, and in-memory DataFrames when
foutisNone.
- Parameters:
- Return type:
- lanspector.crawler.crawl_driver(settings)[source]#
Execute parallel crawls for every target listed in
settings.driver.Each non-blank, non-comment line in the driver file may be: - A local directory or UNC fileshare path - A fileserver hostname (Windows: crawls all non-admin shares on that host) -
DN: <DomainName>(Windows: discovers domain servers and crawls their shares)- Parameters:
- settings
Crawl configuration with
driverset to a readable text file path.
- Returns:
- list[pathlib.Path]
List of target database paths discovered (and crawled unless
dryrun=True).
- Parameters:
settings (CrawlSettings)
- Return type:
- lanspector.crawler.yield_filesystem(path, ret_files=True, ret_dirs=True, permissions=True, detect_pii_content=False, use_ner=False, max_md5=None, skip_size=False, max_depth=0, skip_entries=None, _depth=0)[source]#
Recursively yield metadata, permissions, and PII findings below path.
- Parameters:
- path
Directory path to traverse.
- ret_files
Yield individual file entries when
True.- ret_dirs
Yield directory entries when
True.- permissions
Harvest effective NTFS/POSIX permissions when
True.- detect_pii_content
Inspect supported files for PII indicators when
True.- use_ner
Enable optional NLTK proper-name NER during PII scanning.
- max_md5
Maximum file size in bytes for computing MD5 digests (
Nonedisables).- skip_size
Skip aggregating contained file sizes onto directory entries when
ret_files=False.- max_depth
Maximum recursion depth below the root (
0means unlimited).- skip_entries
Optional set of
(normalized_dir_path, fname_or_none)pairs already persisted in an interrupted crawl; matching objects are skipped without re-reading ACLs/MD5/PII while subdirectories are still traversed to finish any unvisited paths.- _depth
Internal current recursion depth counter.
- Yields:
- tuple[CrawlEntry, list[PermissionEntry] | None, list[PiiFinding]]
Three-tuple of
(entry, permissions, pii_findings)for each visited object.
- Parameters:
- Return type:
Iterator[tuple[CrawlEntry, list[PermissionEntry] | None, list[PiiFinding]]]
- lanspector.crawler.convert_to_sqlite(fin, fout=None, crawldate=None, overwrite=False)[source]#
Convert a CSV or Excel crawl file into a LANspector SQLite database.
- Parameters:
- fin
Input
.csvor.xlsxcrawl file.- fout
Destination
.db/.sqlitepath (defaults to fin with.dbsuffix).- crawldate
Table name in
YYYYMMDDTHHMMSSformat (defaults to current UTC timestamp).- overwrite
Replace existing table if already present in fout.
- Returns:
- pathlib.Path
Path to the created or updated SQLite database.
- Parameters:
- Return type:
- lanspector.crawler.crawl_by_existing_dbs(location, mindate, cmd_base=None, dryrun=False)[source]#
Find crawl databases older than mindate and optionally re-crawl them.
- Parameters:
- location
Directory containing existing
<server>_<share>.dbcrawl databases.- mindate
Minimum acceptable latest-crawl timestamp (datetime or
YYYYMMDDTHHMMSSstring).- cmd_base
Base CLI command list (defaults to
[sys.executable, "-m", "lanspector", "crawl"]).- dryrun
When
True, return the planned commands without launching subprocesses.
- Returns:
- list[list[str]]
Subprocess command lists for stale databases.
- Parameters:
- Return type:
- lanspector.crawler.create_crawl_engine(db_path)[source]#
Create a SQLAlchemy 2.x SQLite engine configured for LANspector crawls.
Uses
NullPoolfor file-backed SQLite databases so multi-threaded callers (such as LANdash) never share a single raw SQLite connection across concurrent threads, reservingStaticPoolonly for:memory:databases.
- lanspector.crawler.md5sum(filename, blocksize=1048576, max_block=None)[source]#
Calculate the MD5 hex digest of filename.
- Parameters:
- filename
Path to the file to hash.
- blocksize
Read buffer size in bytes.
- max_block
Optional cap on the number of blocks read.
- Returns:
- str
Lowercase hexadecimal MD5 digest (or empty string if unreadable).
- Parameters:
- Return type:
OS-abstracted ownership, ACL harvesting, NTFS bitmasks, and path/network helpers.
On Windows (when pywin32 is installed), LANspector uses the Win32 Security and
NetAPI interfaces for full NTFS DACL, SMB share, and Active Directory group
harvesting. On POSIX platforms (Linux and macOS), LANspector provides a consistent
fallback built on os.lstat(), pwd, and grp so local crawling,
SOX permission-diff analysis, Excel reporting, and testing run identically everywhere.
- lanspector.platform.get_effective_permissions(path, domain=None)[source]#
Return normalized effective permissions on path.
- Parameters:
- path
Filesystem path (file or directory) to inspect.
- domain
Optional Windows domain hint passed to
LookupAccountSid.
- Returns:
- list[PermissionEntry]
Normalized ACL entries for the object (empty list on error).
- Parameters:
- Return type:
Harvest SMB share-level permissions for a UNC path.
- Parameters:
- path
Local or UNC path (e.g.
\\server\share\subdir).
- Returns:
- list[SharePermissionEntry]
Share-level ACL entries on Windows UNC paths; empty list on POSIX or local paths.
- Parameters:
path (str)
- Return type:
- lanspector.platform.get_group_membership(domain, group, acl_type='Group', resolve_nests=True, nest_name='', scan_date=None)[source]#
Resolve Active Directory group membership for group in domain.
- Parameters:
- domain
Active Directory domain or NetBIOS name.
- group
Security group or local alias name.
- acl_type
Account category (
"Group"or"Alias").- resolve_nests
Recursively expand nested groups when
True.- nest_name
Internal prefix tracking nested group ancestry.
- scan_date
Optional timestamp recorded alongside membership rows.
- Returns:
- pandas.DataFrame
Membership table (empty DataFrame on POSIX or when Win32 APIs are unavailable).
- Parameters:
- Return type:
- lanspector.platform.ntfs_to_bitmask(permission)[source]#
Map a human-readable NTFS or POSIX permission string to a power-of-two bitmask.
- lanspector.platform.bitmask_to_code(mask)[source]#
Decode an aggregated permission bitmask back into compact audit codes.
Codes follow standard LANspector notation:
R(Read),A(Add),M(Modify/Change),S(Special),F(Full Control).- Parameters:
- mask
Aggregated integer bitmask produced by
ntfs_to_bitmask().
- Returns:
- str or None
Compact permission string, or
Nonewhen no permission bits are set.
- Parameters:
mask (object)
- Return type:
str | None
- lanspector.platform.reduce_permission_hierarchy(series)[source]#
Collapse subordinate permission bits so only the highest effective bit remains.
- lanspector.platform.clean_long_path(path)[source]#
Prefix long Windows paths (>255 chars) with
\\?\or\\?\UNC\.
Parse a UNC or local path into
(domain, host, share, subdir)components.
- lanspector.platform.is_hostname(host)[source]#
Return
Trueif host is a bare hostname without domain dots.
- lanspector.platform.is_ip_address(address)[source]#
Return
Trueif address is a valid IPv4 address string.
- lanspector.platform.open_read_noatime(path, *, binary=True, encoding=None, errors=None)[source]#
Open path for reading without updating
atimewhen the OS supportsO_NOATIME.On Linux filesystems mounted with
relatimeorstrictatime, reading files for MD5 hashing or PII scanning with plainopen()updatesatimeon disk. Usingos.O_NOATIMEpreserves original access timestamps when permitted, falling back gracefully toopen()ifO_NOATIMEis unavailable or disallowed.- Parameters:
- path
Filesystem path to open for reading.
- binary
Open in binary mode (
"rb") whenTrue, otherwise text mode ("r").- encoding
Optional text encoding used when
binary=False.- errors
Optional error handler used when
binary=False.
- Returns:
- typing.IO[typing.Any]
Open readable file object.
- Parameters:
- Return type:
- lanspector.platform.smb_socket_connect(server, port=445, timeout=2.0)[source]#
Test TCP connectivity to server on SMB port (default 445).
- lanspector.platform.strip_long_path_prefix(path)[source]#
Remove Win32
\\?\UNC\or\\?\prefixes from path.
- lanspector.platform.subdir_fqdn_to_hostname(subdir)[source]#
Strip the domain suffix from the server portion of a UNC path if present.
PII keyword and optional named-entity content scanning for crawled files.
- lanspector.pii.scan_file_for_pii(path, max_rows=10, use_ner=False)[source]#
Inspect a supported file’s contents and return detected PII findings.
- Parameters:
- path
Path to the file to inspect.
- max_rows
Maximum number of lines (for text files) or rows per sheet (for Excel files) to inspect.
- use_ner
When
Trueandnltkmodels are installed locally, also detect proper person names via named-entity recognition.
- Returns:
- list[PiiFinding]
Detected PII keyword and/or proper-name matches with contextual snippets.
- Parameters:
- Return type:
- lanspector.pii.search_text_for_pii(contents, use_ner=False)[source]#
Search extracted text contents for PII keywords and optional person names.
- Parameters:
- contents
Text content extracted from a file.
- use_ner
When
True, attempt optional NLTK named-entity person detection ifnltkand its corpora are already installed locally.
- Returns:
- list[PiiFinding]
Detected PII keyword and/or proper-name matches.
- Parameters:
- Return type:
- lanspector.pii.count_pii_name_matches(path, fname)[source]#
Count PII keyword matches appearing in a path and/or filename.
- lanspector.pii.extract_file_text(path, max_rows=10, max_bytes=26214400)[source]#
Read up to max_rows of text from a supported text or Excel file.
- Parameters:
- path
Path to the file to read.
- max_rows
Maximum lines (text/CSV) or rows per worksheet (Excel) to read.
- max_bytes
Maximum file size in bytes eligible for content inspection (guards against oversized files and compressed spreadsheet zip bombs).
- Returns:
- str
Concatenated text sample, or an empty string if unsupported or unreadable.
- Parameters:
- Return type:
Discover computers across domains and enumerate their SMB shares.
- Parameters:
- domains
Single domain name (or comma-separated string) or sequence of domain names.
- test_connectivity
Filter unreachable hosts using TCP port 445 probing before listing shares.
- get_share_permissions
Include share-level ACL principals for each discovered share.
- skip_admin_shares
Skip administrative shares containing
$.- max_workers
Maximum concurrent worker threads.
- Returns:
- list[dict[str, Any]]
List of discovered share records (empty on non-Windows platforms).
- Parameters:
- Return type:
Enumerate SMB shares across one or more Windows fileservers.
- Parameters:
- servers
Single server name (or comma-separated string) or sequence of server names.
- domain
Optional domain label associated with servers.
- records
Optional sequence of
{"domain": ..., "server": ...}dicts.- sharetype
Optional Win32 share type filter (
0= disk share).- get_share_permissions
Query level-502 security descriptors and expand per-ACL rows when
True.- skip_admin_shares
Skip shares whose name contains
$.- max_workers
Maximum concurrent probing threads.
- checkpoint_file
Optional JSON checkpoint path to resume interrupted multi-server scans.
- Returns:
- list[dict[str, Any]]
List of share metadata dicts (empty on non-Windows platforms).
- Parameters:
- Return type:
Crawl every accessible share on server and save
<server>_<share>.db.- Parameters:
- server
Fileserver hostname or FQDN.
- out_dir
Directory in which to store crawl databases and Excel summaries.
- skip_admin_shares
Skip administrative shares ending in
$.- generate_summary
Generate a companion
.xlsxaudit report for each crawled share.- limit
Row limit forwarded to Excel report generation.
- Returns:
- list[pathlib.Path]
Paths to generated SQLite crawl databases.
- Parameters:
- Return type:
List Windows computers registered in Active Directory domain.
Probe TCP connectivity to server on SMB port and enrich its record.
- Parameters:
- server
Hostname/IP string or record dict containing
"server"and optional"domain".- port
TCP port to probe (default
445).- timeout
Connection timeout in seconds.
- Returns:
- dict[str, Any]
Record dictionary with
server,port,fqdn, andconnectionkeys.
- Parameters:
- Return type: