Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

anonftp_scanner.py

Tags: port threads host
#-*-coding:utf8;-*-
#qpy:3
#qpy:console

'''
A simple anonymous FTP server scanner.
'''


import socket
import ftplib
import struct
import random
import threading
import ipaddress
import time
from datetime import datetime


HOSTS = {} # Used to store live hosts.
VULN = [] # Used to store anon ftp servers.
ADDRESSES = set() # Used to store generated addresses.

class Config(object):
# This will be applied to socket.connect
# and ftplib.
timeout = 0.5
max_threads = 300
# Stop scanning after we have found this many hosts.
limit = 1
# How many hosts to scan at once.
scan_size = 10000
port = 21
ftp_debuglevel = 2


def private(ip):
''' Check if an ip address is private. '''
return ipaddress.ip_address(ip).is_private


def generate_addresses(n_addresses):
''' Generate non local IPv4 addresses. '''
addresses = set()
while len(addresses) != n_addresses:
ip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
if not private(ip) and ip not in ADDRESSES:
addresses.add(ip)
ADDRESSES.union(addresses)
return addresses


def check_port(ip, port, timeout=Config.timeout):
''' Determin if a port is open by trying to connect to it '''
sock = socket.socket()
sock.settimeout(timeout)
try:
sock.connect((ip, port))
HOSTS[ip] = port
return True
except socket.error:
return False


def wait(threads):
'''Call the join method on a list of threads.'''
for thread in threads:
if thread.is_alive():
thread.join()


def start_threads(threads):
''' Call the start method on a list of threads. '''
for thread in threads:
if threading.active_count() thread.start()
print(threading.active_count())

def anon_login(host):
''' Attempt an anonymous login to a ftp server. '''
try:
ftp = ftplib.FTP(host, timeout=Config.timeout)
ftp.set_debuglevel(Config.ftp_debuglevel)
ftp.login('anonymous', '[email protected]')
ftp.getwelcome()
ftp.dir()
VULN.append(host)
except Exception as error:
pass


def scan(scan_size=Config.scan_size, port=Config.port):
print('Scanning {} random hosts.'.format(scan_size))
threads = []
for host in generate_addresses(scan_size):
args = host, port
if threading.active_count() thread = threading.Thread(target=check_port, args=args)
threads.append(thread)
start_threads(threads)
wait(threads)


def scanner(scan_size=Config.scan_size, port=Config.port):
threads = []
scan(scan_size, port)
print('Probing {} hosts.'.format(len(HOSTS)))
[anon_login(host) for host in HOSTS]


start_time = datetime.now()
while len(VULN) scanner(Config.scan_size, Config.scan_size)
for ip in VULN:
print(ip)

elapsed = datetime.now() - start_time
print(elapsed)


This post first appeared on Ricky's Python Notes, please read the originial post: here

Share the post

anonftp_scanner.py

×

Subscribe to Ricky's Python Notes

Get updates delivered right to your inbox!

Thank you for your subscription

×