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). When None, results are returned in-memory on CrawlResult.

tablename

Timestamp table name for SQLite output (defaults to UTC YYYYMMDDTHHMMSS).

max_md5

Compute MD5 digests for files smaller than this size in bytes (None disables).

skip_size

When True and scantype="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 (0 means unlimited).

max_depth

Maximum directory depth below path to traverse (0 means 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 True and writing to an existing SQLite database, resume the latest incomplete crawl (scan_end IS NULL in CRAWL_INFO) for path — or explicitly resume tablename — skipping already-persisted directories and files.

show_progress

Show a single-line tqdm progress bar on stderr. Defaults to None (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 fout is None.

Parameters:
Return type:

CrawlResult

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 driver set 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:

list[Path]

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 (None disables).

skip_size

Skip aggregating contained file sizes onto directory entries when ret_files=False.

max_depth

Maximum recursion depth below the root (0 means 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 .csv or .xlsx crawl file.

fout

Destination .db / .sqlite path (defaults to fin with .db suffix).

crawldate

Table name in YYYYMMDDTHHMMSS format (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:

Path

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>.db crawl databases.

mindate

Minimum acceptable latest-crawl timestamp (datetime or YYYYMMDDTHHMMSS string).

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:

list[list[str]]

lanspector.crawler.create_crawl_engine(db_path)[source]#

Create a SQLAlchemy 2.x SQLite engine configured for LANspector crawls.

Uses NullPool for file-backed SQLite databases so multi-threaded callers (such as LANdash) never share a single raw SQLite connection across concurrent threads, reserving StaticPool only for :memory: databases.

Parameters:
db_path

Path to the SQLite database file (or ":memory:").

Returns:
sqlalchemy.Engine

Configured SQLAlchemy engine.

Parameters:

db_path (str | Path)

Return type:

Engine

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:

str

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_path_owner(path)[source]#

Return the account name owning path.

Parameters:
path

Filesystem path to inspect.

Returns:
str

Owner account name, "Dead:<SID>" for unresolved Windows SIDs, or "AccessDenied" when permissions prevent inspection.

Parameters:

path (str)

Return type:

str

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:
  • path (str)

  • domain (str | None)

Return type:

list[PermissionEntry]

lanspector.platform.get_fileshare_permissions(path)[source]#

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:

list[SharePermissionEntry]

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:

DataFrame

lanspector.platform.ntfs_to_bitmask(permission)[source]#

Map a human-readable NTFS or POSIX permission string to a power-of-two bitmask.

Parameters:
permission

Permission label (e.g. "Read(RX)", "Change", "Full Control(All)").

Returns:
int

Bitmask integer enabling additive/bitwise aggregation in pivot tables.

Parameters:

permission (object)

Return type:

int

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 None when 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.

Parameters:
series

Numeric permission bitmask column.

Returns:
pandas.Series

Integer Series where each non-zero entry is reduced to its highest power-of-two bit (capped at PERM_BIT_FULL).

Parameters:

series (Series)

Return type:

Series

lanspector.platform.clean_long_path(path)[source]#

Prefix long Windows paths (>255 chars) with \\?\ or \\?\UNC\.

Parameters:
path

Filesystem path to normalize.

Returns:
str

Long-path-safe path string on Windows, or unchanged path if already short/prefixed.

Parameters:

path (str)

Return type:

str

lanspector.platform.extract_domain_host_share_subdir(path)[source]#

Parse a UNC or local path into (domain, host, share, subdir) components.

Parameters:
path

UNC path (e.g. \\host.domain.local\share\folder) or local path.

Returns:
tuple[str, str, str, str]

Four-tuple of (domain, host, share, subdir).

Parameters:

path (str)

Return type:

tuple[str, str, str, str]

lanspector.platform.is_hostname(host)[source]#

Return True if host is a bare hostname without domain dots.

Parameters:
host

Hostname or FQDN string.

Returns:
bool

True when host contains no internal dot separator.

Parameters:

host (str)

Return type:

bool

lanspector.platform.is_ip_address(address)[source]#

Return True if address is a valid IPv4 address string.

Parameters:
address

Candidate IPv4 address.

Returns:
bool

True when address matches dotted-quad IPv4 format.

Parameters:

address (str)

Return type:

bool

lanspector.platform.open_read_noatime(path, *, binary=True, encoding=None, errors=None)[source]#

Open path for reading without updating atime when the OS supports O_NOATIME.

On Linux filesystems mounted with relatime or strictatime, reading files for MD5 hashing or PII scanning with plain open() updates atime on disk. Using os.O_NOATIME preserves original access timestamps when permitted, falling back gracefully to open() if O_NOATIME is unavailable or disallowed.

Parameters:
path

Filesystem path to open for reading.

binary

Open in binary mode ("rb") when True, 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:

IO[Any]

lanspector.platform.smb_socket_connect(server, port=445, timeout=2.0)[source]#

Test TCP connectivity to server on SMB port (default 445).

Parameters:
server

Hostname, FQDN, or IPv4 address.

port

TCP port to probe (defaults to 445).

timeout

Socket connection timeout in seconds.

Returns:
bool

True if the TCP handshake succeeded, False otherwise.

Parameters:
Return type:

bool

lanspector.platform.strip_long_path_prefix(path)[source]#

Remove Win32 \\?\UNC\ or \\?\ prefixes from path.

Parameters:
path

Path potentially starting with a Win32 extended-length prefix.

Returns:
str

Standard path without extended-length prefix.

Parameters:

path (str)

Return type:

str

lanspector.platform.subdir_fqdn_to_hostname(subdir)[source]#

Strip the domain suffix from the server portion of a UNC path if present.

Parameters:
subdir

UNC path such as \\filesrv01.corp.example\data\reports.

Returns:
tuple[bool, str]

(was_fqdn, updated_path) indicating whether an FQDN was shortened.

Parameters:

subdir (str)

Return type:

tuple[bool, str]

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 True and nltk models 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:

list[PiiFinding]

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 if nltk and its corpora are already installed locally.

Returns:
list[PiiFinding]

Detected PII keyword and/or proper-name matches.

Parameters:
Return type:

list[PiiFinding]

lanspector.pii.count_pii_name_matches(path, fname)[source]#

Count PII keyword matches appearing in a path and/or filename.

Parameters:
path

Directory path string.

fname

Filename string (optional).

Returns:
int

Number of regex keyword matches found.

Parameters:
  • path (str | None)

  • fname (str | None)

Return type:

int

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:

str

Windows SMB fileshare and Active Directory domain discovery utilities.

lanspector.shares.list_all_shares_in_domain(domains, test_connectivity=False, get_share_permissions=False, skip_admin_shares=True, max_workers=8)[source]#

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:

list[dict[str, Any]]

lanspector.shares.list_shares(servers=None, domain=None, records=None, sharetype=None, get_share_permissions=True, skip_admin_shares=True, max_workers=8, checkpoint_file=None)[source]#

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:

list[dict[str, Any]]

lanspector.shares.crawl_all_shares_on_fileserver(server, out_dir='.', skip_admin_shares=True, generate_summary=True, limit=500)[source]#

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 .xlsx audit 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[Path]

lanspector.shares.list_servers_in_domain(domain='', server='')[source]#

List Windows computers registered in Active Directory domain.

Parameters:
domain

Active Directory domain name (empty string uses the current domain).

server

Optional domain controller hostname.

Returns:
list[dict[str, str]]

List of {"domain": ..., "server": ...} dicts (empty on non-Windows).

Parameters:
Return type:

list[dict[str, str]]

lanspector.shares.port_scan(server, port=445, timeout=2.0)[source]#

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, and connection keys.

Parameters:
Return type:

dict[str, Any]