Spaces:
Running
Running
File size: 13,456 Bytes
50700a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | #!/usr/bin/env python3
"""
NetScope: a terminal for legitimate, read-only network inspections.
Only check hosts you own or are authorized to test. This tool does not
exploit anything, brute-force anything, or access credentials — it just
reads public information a server already hands out (DNS records, HTTP
headers, TLS certificate metadata, etc.), the same way a browser does.
15 commands: dns, whois, headers, ssl, ping, traceroute, robots, redirects,
status, geoip, port, securityscore, export, help, clear.
Install: pip install -r requirements.txt
Run: python netscope.py
"""
import json
import re
import shlex
import socket
import ssl
import subprocess
import sys
import time
from datetime import datetime, timezone
from urllib.parse import urlparse
import requests
try:
import dns.resolver
except ImportError:
dns = None
try:
import whois as whois_lib
except ImportError:
whois_lib = None
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RED = "\033[31m"
CYAN = "\033[36m"
MAGENTA = "\033[35m"
TIMEOUT = 6
last_report = {} # populated by commands, used by `export`
def c(text, color):
return f"{color}{text}{RESET}"
def ok(msg):
print(c(msg, GREEN))
def warn(msg):
print(c(msg, YELLOW))
def err(msg):
print(c(msg, RED))
def info(msg):
print(c(msg, CYAN))
def header(title):
print(c(f"\n== {title} ==", BOLD + MAGENTA))
def normalize_host(target):
"""Strip scheme/path so 'https://example.com/x' -> 'example.com'."""
if "://" in target:
return urlparse(target).hostname or target
return target.split("/")[0]
def normalize_url(target):
if "://" not in target:
target = "https://" + target
return target
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
def cmd_dns(args):
if not args:
err("Usage: dns <domain>")
return
domain = normalize_host(args[0])
header(f"DNS records for {domain}")
if dns is None:
warn("dnspython is not installed (pip install dnspython). Falling back to A record only.")
try:
ip = socket.gethostbyname(domain)
print(f"A {ip}")
except socket.gaierror as e:
err(f"Lookup failed: {e}")
return
resolver = dns.resolver.Resolver()
resolver.lifetime = TIMEOUT
last_report["dns"] = {}
for rtype in ("A", "AAAA", "MX", "NS", "TXT"):
try:
answers = resolver.resolve(domain, rtype)
vals = [a.to_text() for a in answers]
last_report["dns"][rtype] = vals
for v in vals:
print(f"{rtype:<6} {v}")
except Exception:
pass
def cmd_whois(args):
if not args:
err("Usage: whois <domain>")
return
domain = normalize_host(args[0])
header(f"WHOIS for {domain}")
if whois_lib is None:
warn("python-whois is not installed (pip install python-whois).")
return
try:
w = whois_lib.whois(domain)
fields = ["registrar", "creation_date", "expiration_date", "name_servers", "status"]
last_report["whois"] = {}
for f in fields:
val = w.get(f) if hasattr(w, "get") else getattr(w, f, None)
if val:
last_report["whois"][f] = str(val)
print(f"{f:<16} {val}")
except Exception as e:
err(f"WHOIS lookup failed: {e}")
def cmd_headers(args):
if not args:
err("Usage: headers <url>")
return
url = normalize_url(args[0])
header(f"HTTP headers for {url}")
try:
r = requests.get(url, timeout=TIMEOUT, allow_redirects=True)
last_report["headers"] = dict(r.headers)
for k, v in r.headers.items():
print(f"{c(k, CYAN)}: {v}")
except requests.RequestException as e:
err(f"Request failed: {e}")
def cmd_ssl(args):
if not args:
err("Usage: ssl <host[:port]>")
return
target = args[0]
host, _, port = target.partition(":")
host = normalize_host(host)
port = int(port) if port else 443
header(f"TLS certificate for {host}:{port}")
try:
ctx = ssl.create_default_context()
with socket.create_connection((host, port), timeout=TIMEOUT) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as tls:
cert = tls.getpeercert()
proto = tls.version()
subject = dict(x[0] for x in cert.get("subject", []))
issuer = dict(x[0] for x in cert.get("issuer", []))
not_after = cert.get("notAfter")
expires = datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc)
days_left = (expires - datetime.now(timezone.utc)).days
last_report["ssl"] = {"protocol": proto, "subject": subject.get("commonName"),
"issuer": issuer.get("commonName"), "days_left": days_left}
print(f"Protocol : {proto}")
print(f"Subject CN : {subject.get('commonName')}")
print(f"Issuer CN : {issuer.get('commonName')}")
color = GREEN if days_left > 30 else (YELLOW if days_left > 0 else RED)
print(f"Expires in : {c(str(days_left) + ' days', color)}")
except Exception as e:
err(f"TLS check failed: {e}")
def cmd_ping(args):
if not args:
err("Usage: ping <host>")
return
host = normalize_host(args[0])
header(f"Ping {host}")
flag = "-n" if sys.platform.startswith("win") else "-c"
try:
result = subprocess.run(["ping", flag, "4", host], capture_output=True,
text=True, timeout=TIMEOUT * 4)
print(result.stdout.strip() or result.stderr.strip())
except FileNotFoundError:
err("System 'ping' command not found.")
except subprocess.TimeoutExpired:
err("Ping timed out.")
def cmd_traceroute(args):
if not args:
err("Usage: traceroute <host>")
return
host = normalize_host(args[0])
header(f"Traceroute to {host}")
tool = "tracert" if sys.platform.startswith("win") else "traceroute"
try:
result = subprocess.run([tool, host], capture_output=True, text=True, timeout=30)
print(result.stdout.strip() or result.stderr.strip())
except FileNotFoundError:
err(f"System '{tool}' command not found.")
except subprocess.TimeoutExpired:
err("Traceroute timed out.")
def cmd_robots(args):
if not args:
err("Usage: robots <domain>")
return
url = normalize_url(args[0]).rstrip("/") + "/robots.txt"
header(f"robots.txt for {url}")
try:
r = requests.get(url, timeout=TIMEOUT)
if r.status_code == 200:
print(r.text.strip() or "(empty file)")
else:
warn(f"No robots.txt found (status {r.status_code}).")
except requests.RequestException as e:
err(f"Request failed: {e}")
def cmd_redirects(args):
if not args:
err("Usage: redirects <url>")
return
url = normalize_url(args[0])
header(f"Redirect chain for {url}")
try:
r = requests.get(url, timeout=TIMEOUT, allow_redirects=True)
chain = r.history + [r]
for i, resp in enumerate(chain):
print(f"{i+1}. [{resp.status_code}] {resp.url}")
except requests.RequestException as e:
err(f"Request failed: {e}")
def cmd_status(args):
if not args:
err("Usage: status <url>")
return
url = normalize_url(args[0])
header(f"Status check for {url}")
try:
start = time.time()
r = requests.get(url, timeout=TIMEOUT, allow_redirects=True)
ms = round((time.time() - start) * 1000)
color = GREEN if r.status_code < 300 else (YELLOW if r.status_code < 400 else RED)
print(f"Status : {c(r.status_code, color)}")
print(f"Time : {ms} ms")
print(f"Server : {r.headers.get('Server', 'unknown')}")
except requests.RequestException as e:
err(f"Request failed: {e}")
def cmd_geoip(args):
if not args:
err("Usage: geoip <ip-or-domain>")
return
target = normalize_host(args[0])
header(f"Geolocation for {target}")
try:
r = requests.get(f"http://ip-api.com/json/{target}", timeout=TIMEOUT)
data = r.json()
if data.get("status") != "success":
warn(f"Lookup failed: {data.get('message', 'unknown error')}")
return
last_report["geoip"] = data
for field in ("query", "country", "regionName", "city", "isp", "org"):
if data.get(field):
print(f"{field:<12} {data[field]}")
except requests.RequestException as e:
err(f"Request failed: {e}")
def cmd_port(args):
if len(args) < 2:
err("Usage: port <host> <port> (single check — only test hosts you're authorized for)")
return
host = normalize_host(args[0])
try:
port = int(args[1])
except ValueError:
err("Port must be a number.")
return
header(f"Connectivity check: {host}:{port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(TIMEOUT)
try:
result = sock.connect_ex((host, port))
if result == 0:
ok(f"Port {port} is open / accepting connections.")
else:
warn(f"Port {port} is closed or filtered.")
except socket.gaierror as e:
err(f"Could not resolve host: {e}")
finally:
sock.close()
def cmd_securityscore(args):
if not args:
err("Usage: securityscore <url>")
return
url = normalize_url(args[0])
header(f"Security header review for {url}")
checks = {
"Strict-Transport-Security": "Forces browsers to use HTTPS",
"Content-Security-Policy": "Limits what scripts/resources can load",
"X-Content-Type-Options": "Stops MIME-type sniffing",
"X-Frame-Options": "Blocks clickjacking via iframes",
"Referrer-Policy": "Controls what referrer data is leaked",
}
try:
r = requests.get(url, timeout=TIMEOUT, allow_redirects=True)
present = [h for h in checks if h in r.headers]
missing = [h for h in checks if h not in r.headers]
score = round(len(present) / len(checks) * 100)
last_report["securityscore"] = {"score": score, "missing": missing}
print(f"Score: {c(str(score) + '/100', GREEN if score >= 70 else YELLOW if score >= 40 else RED)}\n")
for h in present:
print(f"{c('[present]', GREEN)} {h} — {checks[h]}")
for h in missing:
print(f"{c('[missing]', RED)} {h} — {checks[h]}")
except requests.RequestException as e:
err(f"Request failed: {e}")
def cmd_export(args):
filename = args[0] if args else "netscope_report.json"
if not last_report:
warn("Nothing to export yet — run a few commands first.")
return
with open(filename, "w") as f:
json.dump(last_report, f, indent=2, default=str)
ok(f"Saved {len(last_report)} section(s) to {filename}")
def cmd_clear(_args):
print("\033c", end="")
COMMANDS = {
"dns": (cmd_dns, "Resolve A, AAAA, MX, NS, TXT records for a domain"),
"whois": (cmd_whois, "Look up domain registration info"),
"headers": (cmd_headers, "Fetch and show a URL's real HTTP response headers"),
"ssl": (cmd_ssl, "Inspect a live TLS certificate (issuer, expiry, protocol)"),
"ping": (cmd_ping, "Send real ICMP pings and show latency"),
"traceroute": (cmd_traceroute, "Trace the real network path to a host"),
"robots": (cmd_robots, "Fetch a site's real robots.txt"),
"redirects": (cmd_redirects, "Follow and show a URL's real redirect chain"),
"status": (cmd_status, "Get a URL's live HTTP status code and response time"),
"geoip": (cmd_geoip, "Approximate geolocation of an IP or domain"),
"port": (cmd_port, "Check if one TCP port is open (authorized hosts only)"),
"securityscore": (cmd_securityscore, "Score a site's real security headers"),
"export": (cmd_export, "Save this session's findings to a JSON file"),
"clear": (cmd_clear, "Clear the screen"),
}
def cmd_help(_args):
header("NetScope — 15 commands")
for name, (_, desc) in COMMANDS.items():
print(f" {c(name, CYAN):<24} {desc}")
print(f" {c('help', CYAN):<24} Show this list")
print(c("\nOnly point this at hosts you own or are authorized to test.", DIM))
COMMANDS["help"] = (cmd_help, "Show this list")
def main():
print(c("NetScope", BOLD + MAGENTA), "— real, read-only network inspections.")
print(c("No exploits. No credential access. Authorized targets only.\n", DIM))
while True:
try:
raw = input(c("netscope> ", GREEN)).strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not raw:
continue
parts = shlex.split(raw)
name, args = parts[0].lower(), parts[1:]
if name in ("exit", "quit"):
break
if name not in COMMANDS:
err(f"Unknown command: {name}. Type 'help' to see all 15 commands.")
continue
try:
COMMANDS[name][0](args)
except Exception as e:
err(f"Error: {e}")
if __name__ == "__main__":
main() |