How Can I tell if my Port Scanner is Working? - python

I'm making a port scanner that checks if ports are open or closed but I am convinced that it does not work as it lists every port as being closed, even ports I've specifically opened just to check if it is working. Can anyone see anything wrong with my code?
if userChoice == "1":
# code for option 1
print("You selected Port Scan Tool")
loop = 0
subprocess.call('cls', shell=True)
remoteServer = input("Enter a remote host to scan: ")
start=input("Enter starting port number: ")
start = int(start)
end=input("Enter ending port number: ")
end = int(end)
remoteServerIP = socket.gethostbyname(remoteServer)
# Print a nice banner with information on which host we are about to scan
print ("-" * 60)
print("Please wait, scanning remote host", remoteServerIP)
print("-" * 60)
# Check what time the scan started
t1 = datetime.now()
timestr = time.strftime("%d.%m.%Y-%H.%M.%S")# creates time stamp on text file
try:
textFileLocation = timestr + " - Port Scan Results.txt"# creates and names text file
for port in range(start, end): # lets user select range
sock = (socket.socket(socket.AF_INET, socket.SOCK_STREAM))
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print("Port {}: \t Open".format(port))
#print("Port {}: \t Closed".format(port))
#print("Port {} \t Closed".format(port))
textFileLocation = timestr + " - Port Scan Results.txt"
textFile = open(textFileLocation, "a")
textToWrite = "Open: Port %d\n" % port
textFile.write(textToWrite)
textFile.close()
else:
print("Port {}: \t Closed".format(port))
textFileLocation = timestr + " - Port Scan Results.txt"
textFile = open(textFileLocation, "a")
textToWrite = "Closed: Port %d\n" % port
textFile.write(textToWrite)
textFile.close()
sock.close()

This only tests whether there is any program listening on said port.
To see whether this works or not, first remove try block to see which error is returned. Then use correct error in exception handling, i.e. if your machine is not on the network try will fail as well as when being unable to connect.
Also you will have to introduce timeouts so that socket doesn't hang trying to connect.
To see if your code is doing anything to the target machine, activate firewall there and set it up to notify you if anyone is doing just what you did. Your code might also fail if your router/switcher is preventing port scanning on your network. You should check its firewall settings too.
You are also missing the except block in your code, and try is in wrong place anyway.
You have to test each connection:
for x in range(...):
try:
s = socket.socket(...)
s.connect(...)
s.close()
except: pass
Although you should use for instance:
except socket.SocketError as error:
and then check for error number etc. in variable error where exception will be stored.
Oh, BTW, socket.socket.connect() returns None, so your check would always be False.
This is not C, its Python.
>>> ...
>>> result = sock.connect(...)
>>> print result
None
Try-except will tell you whether connection passed or failed with a lot more info.

Related

Python Port Scanner Not Showing Open Ports

I'm following a Python tut on writing a port scanner, it runs, but it seemed to skip over a port that should theoretically be open. I'm running a web browser so port 80 should be up, but when I ran it against my network it just skipped over it. Also tried it against 443, but it's not showing any HTTPS ports either.
import sys #allows us to enter cmd line arguments & other things
import socket #Sockets and the socket API are used to send messages across a network. They provide a form of inter-process communication (IPC).
from datetime import datetime
#next we need to define our target
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #translate host name to IPV4
else:
print (“invald amt of arguments.”)
print (“syntax: python3 scanner.py <ip>”)
sys.exit()
#add a pretty banner
print (“-” * 50)
print (“scanning target” + target)
print(“Time started: “ +str(datetime.now()))
print (“-” * 50)
try:
for port in range (50,85):
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1) #is a float
result = s.connect_ex((target,port)) #returns error indicator
print ((“checking port {}”).format(port)) #returns error indicator
if result ==0:
print (“port {} is open”.format(port))
s.close()
except KeyboardInterrupt:
(“\Exiting Program”)
sys.exit()
except socket.gaierror:
print (“host name could not be resolved”)
sys.exit()
except socket.error:
print (“could not connect to server”)
sys.exit()**
If You replace all smart quoutes with straight quoutes,
indent the TRUE-block of the if-statement inside the for-loop and
remove the escape character ("\") in the exception handler,
then Your code runs fine.

How can I get my port scanner to work

I am trying to make a port scanner that searches a port that is input against all odd numbered IP address in the range of 10-255.
My current code isn't working, and I am receiving this error;
error str, bytes or bytearray expected, not int
I thought s.connect((int(ipaddress.ip_address(my_net[i])), port)) would fix this but it did not.
Am I missing something?
My current code is below:
import socket
import ipaddress
import subprocess
import sys
from datetime import datetime
#define the subnet to scan
subnet=input("which subnet are you scanning, please enter in x.x.x ")
my_net =[]
count =0
for i in range(11,255):
if i%2!=0:
my_net.insert(count,(subnet+"." +str(i)))
print("Your selected network is " , subnet , "below are the usable Ip addresses")
#the user is to select the port that will be scanned as a part of the test
port = input("Enter the number of the port you would like to scan ")
# Print a banner with information on which host we are about to scan
print ("-" * 60)
print ("Please wait, scanning network" , subnet ,".0/24")
print ("-" * 60)
#check time now#
t1 = datetime.now()
#output. Confirm if the port is open or closed
for i in range(len(my_net)):
try:
socket.setdefaulttimeout (2)
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((int(ipaddress.ip_address(my_net[i])), port))
banner=s.recv(1024)
print(banner)
except Exception as e:
print("error " , e)
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
print ('Scanning Completed in: ', total)
I think you'll find that the ip address has to be a string. For instance '127.0.0.1' not an int, the port is an int though.

Window Opens and Closes Immediately

I wrote a program in Python 2.7. It's working great in the IDLE Shell, but when I try to open it in the Python Command Line, it open and closes immediately. Like, in a split second.
Please help.
import socket
import time
TARGET_PROMPT = "What website do you want to find the IP address of?\n\n"
def ping():
target = raw_input(TARGET_PROMPT)
start = time.time()
print("\nTrying to connect...")
try:
ip_address = socket.gethostbyname(target)
end = time.time()
connection_time = end - start
print("Connection established.")
print("IP address found: " + ip_address + "\n")
except Exception as e:
print("Connection failed.\n")
while True:
ping()
Edit: I deleted and reinstalled Python, and now it seems to be working fine.

i am trying to develop a port scanner in python but my code is not giving any open port give me some suggestions about that?

This is my code it's just starting the scan but it is not completing ,where is the error in it. i need output as port number and port side by side.when i run in command prompt it gives like that,please give suggetions on that
from socket import *
import sys,time
from datetime import datetime
host =''
max_port=100
min_port=1
def scan_host(host,port,r_code=1):
try:
s=socket(AF_INET,SOCK_STREAM)
code=s.connect_ex((host,port))
if code==0:
r_code=code
s.close()
except Exception,e:
pass
return r_code
try:
host=raw_input("Enter Host address:")
except KeyboardInterrupt:
print("\n Application shtdown")
sys.exit(1)
hostip=gethostbyname(host)
print("\n Host:%s IP:%s" %(host,hostip))
print("Scanning Started At %s...\n" %(time.strftime("%H:%M:%S")))
start_time=datetime.now()
for port in range(min_port,max_port):
try:
response=scan_host(host,port)
if response ==0:
print("Port %d: Open" %(port))
except Exception,e:
pass
stop_time=datetime.now()
total_time_duration=stop_time -start_time
print("\n Scanning Finished At %s ..." % (time.strftime("%H:%M:%S")))
print("Scanning Duration:%s..." %(total_time_duration))
print("Have a nice day ...Sergeant Exploiter (Sploit)")
Before using the following port scanner, you may want to check a few things first:
Is the firewall on your computer blocking the port scanner?
Is the device your computer connected to blocking certain ports?
Is the computer you are trying to scan blocking ports with its firewall?
Do you know the correct name of the host that you are trying to scan?
Can you create a server on one computer and connect to it with a client on the other?
If none of the above points are cause for your problem, the program shown below may work for you:
#! /usr/bin/env python3
import argparse
import collections
import itertools
import multiprocessing
import operator
import socket
PURPOSE = 'Scan for open ports on a computer.'
PORTS = range(1 << 16)
POOL_SIZE = 1 << 8
TIMEOUT = 0.01
def main():
"""Get computer to scan, connect with process pool, and show open ports."""
parser = argparse.ArgumentParser(description=PURPOSE)
parser.add_argument('host', type=str, help='computer you want to scan')
host = parser.parse_args().host
with multiprocessing.Pool(POOL_SIZE, socket.setdefaulttimeout, [TIMEOUT]) \
as pool:
results = pool.imap_unordered(test, ((host, port) for port in PORTS))
servers = filter(operator.itemgetter(0), results)
numbers = map(operator.itemgetter(1), servers)
ordered = sorted(numbers)
print(f'Ports open on {host}:', *format_ports(ordered), sep='\n ')
field_names = 'family', 'socket_type', 'protocol', 'canon_name', 'address'
AddressInfo = collections.namedtuple('AddressInfo', field_names)
del field_names
def test(address):
"""Try connecting to the server and return whether or not it succeeded."""
host, port = address
for info in itertools.starmap(AddressInfo, socket.getaddrinfo(host, port)):
try:
probe = socket.socket(info.family, info.socket_type, info.protocol)
except OSError:
pass
else:
try:
probe.connect(info.address)
except OSError:
pass
else:
probe.shutdown(socket.SHUT_RDWR)
return True, port
finally:
probe.close()
return False, port
def format_ports(ports):
"""Convert port numbers into strings and show all associated services."""
if ports:
for port in ports:
try:
service = socket.getservbyport(port)
except OSError:
service = '?'
yield f'{port:<5} = {service}'
else:
yield 'None'
if __name__ == '__main__':
main()

Simple python port scanner (with questions)

i'm new to python programming and here is a fisrt code i've done
so,here is a port scanner i've done , it works fine on localhost ,
but when i try to scan a website , after waiting 10 minutes there is nothing
what is wrong with my code.
here is the code:
from socket import *
print "Simple port scanner"
print "-------------------"
print ""
adress = raw_input("Enter adress (or localhost): ")
ip = gethostbyname(adress)
print adress,"has the IP:",ip
alpha = int(raw_input("Port (min):"))
omega = int(raw_input("Port (max):"))
def scanner(ip,min_port, max_port):
count = 0
for ports in range(alpha, omega):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((ip, ports))
if(result == 0) :
print 'Port %d: is OPEN' % (ports,)
count = count + 1
s.close()
print "Scanning finshed !"
print ""
print "Found",count,"open ports"
print ""
print "Beggin to scan..."
scanner(ip,alpha,omega)
Here is the output for localhost:
Simple port scanner
-------------------
Enter adress (or localhost): localhost
localhost has the IP: 127.0.0.1
Port (min):0
Port (max):100
Beggin to scan...
Port XX: is OPEN
Port XX: is OPEN
Scanning finshed !
Found 2 open ports
and the output for google (for example)
and there is the problem , there is NOTHING :(
Simple port scanner
-------------------
Enter adress (or localhost): google.com
google.com has the IP: 74.125.195.100
Port (min):24
Port (max):82
Beggin to scan...
Thank you for helping me .
thank you for your answer Lawrence Benson ,
i have try it with some othe IP's (no more google , but my website and friend website to stay legal) but same error , have you an idea to improve this script ?
If you change s.connect_ex() to s.connect(), an Execption will be raised if an error occurs. connect_ex returns a error value which needs to be interpreted. There are many errors, e.g. timeout or connection refused.
If I test it on my server, many ports are actively refused. So if I print
print "Port %d is closed" % ports
I can see that all ports are refused.
The best approach would be to go through the error messages you get with connect() and find out how to handle those, especially because you are new to python.
Additionally, you can set a timeout after which your socket gives up on trying to connect.
s.settimeout(3)
Thank you,
I have made some changes and now it works :) I have changed ".connect_ex" to ".connect", add try/except, and two settimeouts.
Here is the code again (modified):
from socket import *
print "Simple port scanner"
print "-------------------"
print ""
adress = raw_input("Enter adress (or localhost): ")
ip = gethostbyname(adress)
print adress,"has the IP:",ip
alpha = int(raw_input("Port (min):"))
omega = int(raw_input("Port (max):"))
def scanner(ip,alpha, omega):
count = 0
for ports in range(alpha, omega):
try:
print "Scanning port :%d" % (ports,)
s = socket(AF_INET, SOCK_STREAM)
s.settimeout(3)
s.connect((ip, ports))
s.settimeout(3)
print "Port %d: is OPEN" % (ports,)
count = count + 1
except:
print "Port %d is CLOSED" % (ports,)
s.close()
print "Scanning finshed !"
print ""
print "Found %d open ports" % (count)
print ""
print "Beggin to scan..."
scanner(ip,alpha,omega)
And the output:
Enter adress (or localhost): xxx.xxx.org
xxx.xxx.org has the IP: xx.xx.xx.xx
Port (min):440
Port (max):445
Beggin to scan...
Scanning port :440
Port 440 is CLOSED
Scanning port :441
Port 441 is CLOSED
Scanning port :442
Port 442 is CLOSED
Scanning port :443
Port 443: is OPEN
Scanning port :444
Port 444 is CLOSED
Scanning finshed !
Found 1 open ports
I would suggest having a function to check the state of a port.
#-*-coding:utf8;-*-
#qpy:3
#qpy:console
import socket
import os
# This is used to set a default timeout on socket
# objects.
DEFAULT_TIMEOUT = 0.5
# This is used for checking if a call to socket.connect_ex
# was successful.
SUCCESS = 0
def check_port(*host_port, timeout=DEFAULT_TIMEOUT):
''' Try to connect to a specified host on a specified port.
If the connection takes longer then the TIMEOUT we set we assume
the host is down. If the connection is a success we can safely assume
the host is up and listing on port x. If the connection fails for any
other reason we assume the host is down and the port is closed.'''
# Create and configure the socket.
sock = socket.socket()
sock.settimeout(timeout)
# the SO_REUSEADDR flag tells the kernel to reuse a local
# socket in TIME_WAIT state, without waiting for its natural
# timeout to expire.
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Like connect(address), but return an error indicator instead
# of raising an exception for errors returned by the C-level connect() 
# call (other problems, such as “host not found,” can still raise exceptions).
# The error indicator is 0 if the operation succeeded, otherwise the value of
# the errnovariable. This is useful to support, for example, asynchronous connects.
connected = sock.connect_ex(host_port) is SUCCESS
# Mark the socket closed.
# The underlying system resource (e.g. a file descriptor)
# is also closed when all file objects from makefile() are closed.
# Once that happens, all future operations on the socket object will fail.
# The remote end will receive no more data (after queued data is flushed).
sock.close()
# return True if port is open or False if port is closed.
return connected
con = check_port('www.google.com', 83)
print(con)

Categories

Resources