Terminal_2 / Terminal Code
Beta123isgreat's picture
Create Terminal Code
50700a5 verified
Raw History Blame Contribute Delete
13.5 kB
#!/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()