Created
March 20, 2019 08:57
-
-
Save akiross/b60ce54b5ee22f994c2e4806800d5b31 to your computer and use it in GitHub Desktop.
Search and test ssh connections on a network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a shitty script that uses nmap to find hosts with port 22 open | |
# and attempt a connection to them using some username and password, then | |
# retrieves the hostname if the login is successful. | |
# Use this script to find a ssh-able host in your (small) network when you | |
# don't know its IP or mac address. | |
# | |
# Also, I wanted to try paramiko. Which is very neat. | |
import re | |
import time | |
import paramiko | |
import warnings | |
from subprocess import run, PIPE | |
def attempt_connection(hostname, username, password, cmd=None): | |
# Suppress warnings | |
with warnings.catch_warnings(): | |
warnings.simplefilter('ignore') | |
ssh_client = paramiko.SSHClient() | |
ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy()) | |
try: | |
ssh_client.connect(hostname=hostname, | |
username=username, | |
password=password) | |
except: | |
pass | |
else: | |
if cmd is None: | |
return True | |
# Execute remote command and get its stdout | |
return ssh_client.exec_command(cmd)[1].readline() | |
return False | |
def discover_open_hosts(network): | |
discover_cmd = "sudo nmap -sS -p22 " + network | |
cmd = run(discover_cmd, shell=True, stdout=PIPE) | |
last_ip = None | |
skip = -1 | |
for line in cmd.stdout.decode().split('\n'): | |
if skip > 0: | |
skip -= 1 | |
continue | |
if skip == 0: | |
# print("Line until skip", line) | |
skip -= 1 | |
m = re.search("22.+open", line) | |
if m: | |
yield last_ip | |
continue | |
time.sleep(0.1) | |
m = re.search(r"\d+\.\d+\.\d+\.\d+", line) | |
if m: | |
last_ip = m.group(0) | |
skip = 3 # Skip the next 3 lines | |
if __name__ == '__main__': | |
for host in discover_open_hosts('192.168.3.0/24'): | |
print("Testing host", host) | |
n = attempt_connection(host, 'someuser', 'somepass', 'hostname') | |
if n: | |
print("Host", host, "accepted connection, hostname and has name", n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment