How to View the Contents of the Hosts File in Batch Script
Before adding, removing, or troubleshooting entries in the hosts file, you need to see what's already there. The hosts file (C:\Windows\System32\drivers\etc\hosts) is a plain text file, but it's buried deep in the system directory and requires navigating through several folders in Explorer. A Batch script can display its contents instantly in the console, filter for active entries, search for specific hostnames, and audit for suspicious modifications.
This guide will explain how to view and search the hosts file from the command line.
Method 1: Quick View - Full File Contents
The simplest way to see everything in the hosts file: comments, entries, and blank lines.
Implementation
@echo off
setlocal
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
if not exist "%HostsFile%" (
echo [ERROR] Hosts file not found: %HostsFile% >&2
endlocal
exit /b 1
)
echo [VIEW] Contents of the Windows Hosts File
echo ============================================
echo Location: %HostsFile%
echo.
type "%HostsFile%"
echo.
echo ============================================
endlocal
exit /b 0
Reading the hosts file does NOT require administrator privileges. Any user can view it with type. Only modifying the file requires elevation.
Method 2: Show Only Active Entries (Filtered View)
Filter out comments (lines starting with #) and blank lines to see only the active DNS overrides, the entries that are actually affecting name resolution on this machine.
@echo off
setlocal
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
echo [INFO] Active DNS overrides in the hosts file:
echo --------------------------------------------------
echo.
:: Count active entries (non-comment, non-empty)
set "EntryCount=0"
for /f %%n in ('findstr /v /r "^#" "%HostsFile%" ^| findstr /v /r "^$" ^| find /c /v ""') do set "EntryCount=%%n"
if %EntryCount% equ 0 (
echo (No active entries. The hosts file contains only comments.^)
echo.
echo This means no local DNS overrides are in effect.
echo All name resolution uses the configured DNS servers.
) else (
echo Found %EntryCount% active entry(ies):
echo.
:: Display active entries with line numbers for reference
findstr /v /r "^#" "%HostsFile%" | findstr /v /r "^$"
echo.
:: Categorize the entries
set "BlockCount=0"
set "RedirectCount=0"
for /f "tokens=1" %%i in ('findstr /v /r "^#" "%HostsFile%" ^| findstr /v /r "^$"') do (
echo %%i | findstr /r "^127\.0\.0\.1$ ^0\.0\.0\.0$" >nul 2>&1
if not errorlevel 1 (
set /a "BlockCount+=1"
) else (
echo %%i | findstr /r "^::1$" >nul 2>&1
if not errorlevel 1 (
rem localhost IPv6 entry - ignore
) else (
set /a "RedirectCount+=1"
)
)
)
echo Summary:
echo Blocked domains (pointing to 127.0.0.1 or 0.0.0.0^): %BlockCount%
echo Redirected domains (pointing to other IPs^): %RedirectCount%
)
echo.
echo --------------------------------------------------
endlocal
exit /b 0
Sample output:
Found 4 active entry(ies):
127.0.0.1 localhost
0.0.0.0 ads.tracker.com
0.0.0.0 malware-domain.example.com
192.168.1.50 staging.myapp.com
Summary:
Blocked domains (pointing to 127.0.0.1 or 0.0.0.0): 3
Redirected domains (pointing to other IPs): 1
What the categories mean:
- Blocked domains (127.0.0.1 or 0.0.0.0): These domains are being redirected to localhost or null, effectively blocked. This is common for ad blocking, content filtering, or security policies.
- Redirected domains (other IPs): These domains are being redirected to specific IP addresses, typically for development/staging testing or DNS propagation bypass. These deserve scrutiny, as they could also indicate malware redirection.
Method 3: Search for a Specific Hostname or IP
Check if a particular hostname or IP address is present in the hosts file: useful for troubleshooting connectivity issues or verifying that a block/redirect is in place.
@echo off
setlocal
set "SearchTerm=%~1"
if "%SearchTerm%"=="" (
echo Usage: %~nx0 ^<search_term^>
echo.
echo Searches the hosts file for a hostname or IP address.
echo.
echo Examples:
echo %~nx0 example.com
echo %~nx0 staging.myapp.com
echo %~nx0 192.168.1.50
endlocal
exit /b 1
)
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
echo [SEARCH] Looking for "%SearchTerm%" in hosts file...
echo.
:: Search with /c: to treat the entire term as a literal string
findstr /i /c:"%SearchTerm%" "%HostsFile%"
if not errorlevel 1 (
echo.
:: Count matches
for /f %%n in ('findstr /i /c:"%SearchTerm%" "%HostsFile%" ^| find /c /v ""') do set "MatchCount=%%n"
echo [FOUND] %MatchCount% matching line(s) in the hosts file.
echo.
:: Check if the match is in a comment or an active entry
findstr /v /r "^#" "%HostsFile%" | findstr /i /c:"%SearchTerm%" >nul 2>&1
if not errorlevel 1 (
echo [ACTIVE] This entry IS affecting DNS resolution on this machine.
echo.
echo The hostname "%SearchTerm%" resolves locally to the IP shown above,
echo bypassing DNS servers. To verify:
echo ping -n 1 %SearchTerm%
) else (
echo [COMMENTED] The match is in a comment line (starts with #^).
echo It is NOT affecting DNS resolution.
)
) else (
echo [NOT FOUND] No entry for "%SearchTerm%" in the hosts file.
echo.
echo This hostname resolves normally via DNS servers.
echo To check the DNS result: nslookup %SearchTerm%
)
endlocal
exit /b 0
Why /c: for the search:
Without /c:, findstr splits the search term on spaces. Searching for my server would match lines containing my OR server independently. The /c: flag treats the entire string as a single literal search term.
If a website or service is unreachable and you suspect a hosts file override:
:: Check if the hostname is in the hosts file
findstr /i /c:"problematic-site.com" %SystemRoot%\System32\drivers\etc\hosts
:: Compare hosts file resolution vs. DNS server resolution
ping -n 1 problematic-site.com
:: Shows the IP the system is ACTUALLY using (hosts file takes priority)
nslookup problematic-site.com
:: Shows the IP from DNS servers (ignores hosts file)
:: If these differ, the hosts file is overriding DNS
Remember: ping uses the hosts file, nslookup does not.
Method 4: Security Audit - Check for Suspicious Entries
Malware sometimes modifies the hosts file to redirect banking, antivirus update, or security websites to malicious servers. This method checks for entries that could indicate compromise.
@echo off
setlocal EnableDelayedExpansion
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
echo [SECURITY] Hosts file audit for %COMPUTERNAME%:
echo --------------------------------------------------
echo.
:: Basic file info
for %%f in ("%HostsFile%") do (
echo File: %HostsFile%
echo Size: %%~zf bytes
echo Modified: %%~tf
)
echo.
:: Count entries
for /f %%n in ('findstr /v /r "^#" "%HostsFile%" ^| findstr /v /r "^$" ^| find /c /v ""') do set "TotalActive=%%n"
echo Active entries: %TotalActive%
echo.
:: Check for suspicious patterns
set "Concerns=0"
:: Check 1: Entries redirecting to non-standard IPs (not 127.0.0.1, 0.0.0.0, ::1, or localhost)
echo Checking for suspicious redirections...
set "SuspiciousRedirects=0"
for /f "tokens=1-2" %%a in ('findstr /v /r "^#" "%HostsFile%" ^| findstr /v /r "^$"') do (
set "IP=%%a"
set "Host=%%b"
:: Skip standard blocking/localhost entries
echo !IP! | findstr /r "^127\.0\.0\.1$ ^0\.0\.0\.0$ ^::1$" >nul 2>&1
if errorlevel 1 (
:: This is a redirect to a non-standard IP, check if the hostname looks sensitive
echo !Host! | findstr /i "bank paypal login secure microsoft windows update google apple" >nul 2>&1
if not errorlevel 1 (
echo [ALERT] !IP! !Host! - sensitive domain redirected!
set /a "Concerns+=1"
) else (
echo [INFO] !IP! !Host! - custom redirect
)
set /a "SuspiciousRedirects+=1"
)
)
if %SuspiciousRedirects% equ 0 (
echo No non-standard redirections found.
)
echo.
:: Check 2: File size is unusually large (could indicate adware/malware entries)
for %%f in ("%HostsFile%") do set "FileSize=%%~zf"
if %FileSize% gtr 50000 (
echo [WARNING] Hosts file is unusually large (%FileSize% bytes^).
echo This may indicate bulk adware/malware entries.
set /a "Concerns+=1"
) else (
echo File size (%FileSize% bytes^) is within normal range.
)
echo.
:: Check 3: Compare modification date (if recent, may have been tampered with)
echo Last modified:
for %%f in ("%HostsFile%") do echo %%~tf
echo.
:: Summary
echo --------------------------------------------------
if %Concerns% gtr 0 (
echo [WARNING] %Concerns% potential concern(s) found.
echo Review the entries above and investigate any suspicious redirections.
) else (
echo [OK] No suspicious entries detected.
)
endlocal
exit /b 0
What to look for:
| Finding | Risk Level | Possible Cause |
|---|---|---|
| Banking/payment site redirected to a foreign IP | Critical | Malware, phishing redirect |
| Antivirus update site blocked (0.0.0.0) | High | Malware preventing security updates |
| microsoft.com or windowsupdate.com redirected | High | Malware blocking Windows Update |
| Dozens of ad/tracker domains blocked | Low | Legitimate ad-blocking (user-installed) |
| Development domains pointing to local IPs | Low | Developer testing, expected |
| Hosts file very large (>50 KB) | Medium | Bulk ad-blocking list or malware |
If the security audit finds entries redirecting banking sites, security update servers, or authentication services to unexpected IP addresses, the machine may be compromised. Do NOT simply remove the entries, the malware that added them may re-add them. Run a full antivirus scan and investigate the root cause before cleaning the hosts file.
Method 5: Compare Against a Baseline
For fleet management, compare the current hosts file against a known-good baseline to detect unauthorized changes.
@echo off
setlocal
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
set "BaselineFile=%~1"
if "%BaselineFile%"=="" (
echo Usage: %~nx0 ^<baseline_file^>
echo.
echo Compares the current hosts file against a known-good baseline.
echo.
echo Example: %~nx0 \\Server\Baselines\hosts_approved.txt
echo.
echo To create a baseline from a clean machine:
echo copy %HostsFile% \\Server\Baselines\hosts_approved.txt
endlocal
exit /b 1
)
if not exist "%BaselineFile%" (
echo [ERROR] Baseline file not found: %BaselineFile% >&2
endlocal
exit /b 1
)
echo [COMPARE] Hosts file vs. baseline:
echo --------------------------------------------------
echo.
:: Compare the files
fc "%HostsFile%" "%BaselineFile%" >nul 2>&1
if not errorlevel 1 (
echo [OK] Hosts file matches the approved baseline.
echo No unauthorized modifications detected.
) else (
echo [DIFFERENCE] Hosts file differs from the baseline:
echo.
:: Show additions (in hosts but not in baseline)
echo Entries ADDED (not in baseline^):
findstr /v /x /g:"%BaselineFile%" "%HostsFile%" | findstr /v /r "^$"
echo.
:: Show removals (in baseline but not in hosts)
echo Entries REMOVED (in baseline but not in hosts file^):
findstr /v /x /g:"%HostsFile%" "%BaselineFile%" | findstr /v /r "^$"
echo.
echo [ACTION] Review the differences above.
echo Added entries may be legitimate (new blocks or dev redirects^)
echo or unauthorized (malware, unapproved changes^).
)
echo --------------------------------------------------
endlocal
exit /b 0
Creating and maintaining a baseline:
:: On a clean, approved machine:
copy %SystemRoot%\System32\drivers\etc\hosts \\Server\Baselines\hosts_standard.txt
:: Schedule the comparison script to run weekly on all machines
:: Any deviation triggers investigation
Method 6: Fleet-Wide Hosts File Audit CSV
For auditing hosts file entries across multiple machines.
@echo off
setlocal
set "CSVFile=\\Server\Audit\hosts_audit.csv"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
if not exist "%CSVFile%" (
echo "Timestamp","Computer","EntryCount","BlockedDomains","RedirectedDomains","FileSizeBytes" > "%CSVFile%" 2>nul
)
powershell -NoProfile -Command ^
"$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss';" ^
"$hosts = Get-Content '%HostsFile%' -ErrorAction SilentlyContinue;" ^
"$active = $hosts | Where-Object { $_ -notmatch '^\s*#' -and $_.Trim() -ne '' };" ^
"$blocked = ($active | Where-Object { $_ -match '^\s*(127\.0\.0\.1|0\.0\.0\.0)' }).Count;" ^
"$redirected = ($active | Where-Object { $_ -notmatch '^\s*(127\.0\.0\.1|0\.0\.0\.0|::1)' }).Count;" ^
"$fileSize = (Get-Item '%HostsFile%').Length;" ^
"Write-Output ('\"' + $ts + '\",\"' + $env:COMPUTERNAME + '\",\"' + $active.Count + '\",\"' + $blocked + '\",\"' + $redirected + '\",\"' + $fileSize + '\"')" >> "%CSVFile%" 2>nul
echo [OK] Hosts file audit data exported for %COMPUTERNAME%.
endlocal
exit /b 0
What to look for in the fleet CSV:
- Machines with many active entries: Most workstations should have 0–2 custom entries. Dozens may indicate ad-blocking software or malware.
- Machines with redirected domains: Any non-blocking redirect (pointing to an IP other than 127.0.0.1 or 0.0.0.0) should be investigated.
- Sudden increase in entry count: Comparing weekly scans, a machine that went from 0 entries to 50 may have been compromised.
- Unusually large file size: A hosts file over 50 KB may contain a bulk block list or malware-injected entries.
How to Avoid Common Errors
Wrong Way: Opening in Notepad Without Admin (for Editing)
If you open the hosts file in Notepad without administrator privileges, you can view it but cannot save changes. Notepad may silently save to a different location or show a misleading error.
Correct Way: For viewing, use type from any command prompt (no elevation needed). For editing, launch Notepad from an elevated command prompt:
:: Elevated Notepad for hosts editing
notepad %SystemRoot%\System32\drivers\etc\hosts
Problem: File Appears to Contain Only Comments
On a clean Windows installation, the hosts file contains only comment lines (starting with #). These are informational text that Windows ignores, they are not active entries.
Solution: Use Method 2, which filters out comments. If the filtered output is empty, there are no custom DNS overrides on this machine, all name resolution uses DNS servers normally.
Problem: findstr Shows Unexpected Matches
Searching for app matches app.com, myapp.local, application-server.com, and any comment containing the word "app."
Solution: Use the /c: flag with the full hostname for precise matching:
:: Precise: matches only lines containing exactly "staging.myapp.com"
findstr /i /c:"staging.myapp.com" "%HostsFile%"
:: Imprecise: matches any line containing "staging" OR "myapp" OR "com"
findstr /i "staging myapp com" "%HostsFile%"
Best Practices and Rules
1. Audit Regularly for Security
Malware commonly modifies the hosts file to redirect banking, security, and update sites. Include hosts file review in your regular security audits (Method 4).
2. Verify After Modifications
After running any add or remove script, view the hosts file (Method 1 or 2) to confirm the change was applied correctly.
3. Maintain a Baseline
Keep a known-good copy of the hosts file and compare periodically (Method 5). Any unauthorized deviation triggers investigation.
4. Use ping Not nslookup to Test Hosts Entries
nslookup queries DNS servers directly and ignores the hosts file. ping uses the system resolver, which checks the hosts file first. Use ping to verify hosts file entries are working.
5. Document Why Entries Exist
When reviewing the hosts file, entries without comments are impossible to evaluate, you can't tell if 192.168.1.50 myapp.com is a legitimate development redirect or a leftover from two years ago. Always add comments when creating entries.
Conclusions
Viewing the hosts file is the first step in any DNS troubleshooting, security audit, or hosts file management task. By combining full-file display, filtered active-entry views, specific hostname searches, security auditing, and baseline comparison, you gain complete visibility into the local DNS overrides on any machine. This visibility is essential for diagnosing connectivity problems, detecting malware modifications, and maintaining a clean, documented hosts file.