Python Port Scanner Stuck In Loop - python

I've been following a guide on how to make a simple port scanner, I am trying to scan my own IP but it gets stuck in a loop and prints no ports. It's hard to figure out at it gives no errors and gets stuck in a loop.
Any help would be greatly appreciated.
import socket
import subprocess
import sys
from datetime import datetime
#clears the shell screen
subprocess.call('clear', shell=True)
#ask for input
remoteServer = raw_input("Please enter a host to scan:")
remoteServerIP = socket.gethostbyname(remoteServer)
#print a banner saying we are scanning
print "-" * 60
print "now scanning your host...", remoteServerIP
print "-" * 60
#Check what time the scan started
t1 = datetime.now()
# Using the range function to specify which ports (1 - 1025)
#Errors.
try:
for port in range(1, 1025):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
#if the socket is listening it will print out the port
print("Port{}:\t Open".format(port))
sock.close()
except KeyboardInterrupt:
print "You pressed ctrl+c"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved to IP. Exiting'
sys.exit()
except socket.error:
print "couldn't connect to server"
sys.exit()
# checking the time again
t2 = datetime.now()
#calculates the differnce of time, to see how long it took to run the script
total = t2 - t1
#printing the info to screen
print "scanning compelte in :", total

You can use sock.timeout(0.1) so it will no wait for connection.
I put print port to see which port is scanned.
You can try with 8.8.8.8 - without sock.timeout(0.1) it hang on first port.
Maybe you have good secured computer and it blocks connections to close ports.
import sys
from datetime import datetime
import socket
#ask for input
remoteServer = raw_input("Please enter a host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
#print a banner saying we are scanning
print "-" * 60
print "now scanning host ...", remoteServerIP
print "-" * 60
#Check what time the scan started
t1 = datetime.now()
# Using the range function to specify which ports (1 - 1025)
#Errors.
try:
for port in range(1, 1025):
print port
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(0.1)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
#if the socket is listening it will print out the port
print("Port {:4d}: Open".format(port))
sock.close()
except KeyboardInterrupt:
print "You pressed ctrl+c"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved to IP. Exiting'
sys.exit()
except socket.error:
print "couldn't connect to server"
sys.exit()
# checking the time again
t2 = datetime.now()
#calculates the differnce of time, to see how long it took to run the script
total = t2 - t1
#printing the info to screen
print "scanning compelte in:", total
BTW:
You can compare your results with results from tools like nmap
See scapy - python module to work with network packages. (book: Black Hat Python)

At least on my machine (Ubuntu 16.something) it does work. Output:
Please enter a host to scan:localhost
------------------------------------------------------------
now scanning your host... 127.0.0.1
------------------------------------------------------------
Port21: Open
Port22: Open
Port25: Open
Port80: Open
Port139: Open
Port443: Open
Port445: Open
Port631: Open
scanning compelte in : 0:00:00.047478
However, it only scans ports 1-1024, while ports go up to 65535.
To make it scan all the ports, change for port in range(1, 1025): to for port in range(1, 65536):

Related

Port Scanner written in python does not display output normally

So I tried to write a port scanner in python3
Here is my code:
import sys #allows us to enter command line arguments, among other things
import socket
from datetime import datetime
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #Translate a hostname to IPv4
else:
print("Invalid amount of arguments.")
print("Syntax: python3 scanner.py <ip>")
sys.exit()
#Add a 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)
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
if result == 0:
print("Port {} is open".format(port))
s.close()
except KeyboardInterrupt:
print("\nExiting program.")
sys.exit()
except socket.gaierror:
print("Hostname could not be resolved.")
sys.exit()
except socket.error:
print("Couldn't connect to server.")
sys.exit()
using Kali Linux 2020.2, with the newest version of python,
I executes python3 scanner.py google.com
It is expected that the scanner will display "Checking port 50", "Checking port 51" one by one during the scanning process.
And if it find any one of the ports is open, it shows "Port xx is open" after the "Checking port xx"
However, my scanner was stuck as the initial banner.
And eventually when it has completed the scanning, it displays all the output in one go.
Can anyone please tell me how can I solve this problem?
Just switch the following lines in your code:
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
becomes:
print("Checking port {}".format(port))
result = s.connect_ex((target,port)) #returns error indicator

Threaded python SSH port scanner doesn't work

So I'm trying to make a program that scans the SSH port for IPs in a list. Because the process is painfully long I'm trying to use threading (I can use multiprocessing if it is more suitable for the program) to make everything faster but I'm running in a problem where the program says "Trying IP" (that's what it's meant to say every time it scans an IP) a lot of times without giving a result and then it gives the results (significantly fewer results than IP scans) and having other weird patterns. It should say Trying IP and then the result but it doesn't and even the result is always failing even if it does find IPs with the SSH port open. At some point I was curious if it misses IPs with SSH so I searched for an IP range that should have a lot of them and it only caught 2000 of them even if the guy who posted the class said he got 45000, yeah I know, maybe something happened and an insane amount of people closed SSH but no, I downloaded something called a "scanning archive" made by some Romanian hackers that had a SSH port scanner in it and when I scanned the same IP range I caught 6600.
So can someone help me figure out what is wrong with the code and tell me how to improve it?
import socket
import threading
from queue import Queue
from datetime import datetime
time_start = datetime.now()
SSH_ips = []
def scan(ip_number):
ip_try = ip_list[ip_number]
port = 22
try:
print("Trying IP")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip_try,port))
if result == 0:
SSH_ips.append(ip_try)
print("Found %d" % (ip_try))
else:
print("Didn't work")
except:
pass
def gulag():
while True:
worker = q.get()
scan(worker)
q.task_done()
q = Queue()
for x in range(15000):
t = threading.Thread(target=gulag)
t.daemon = True
t.start()
for worker in range(0, 65026):
q.put(worker)
q.join()
time_finish = datetime.now()
time_elapsed = time_finish - time_start
ip_list_lenght = len(SSH_ips)
SSH_ips.sort()
print("Found %s IPs in %s." % (ip_list_lenght, time_elapsed));
print(SSH_ips)
... what is wrong with the code and tell me how to improve it?
try:
print("Trying IP")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...
except:
pass
Please don't just pass on exception but actually check why it failed. It is likely that you run against the limit of open file descriptors and thus creation of a new socket failed. In this case of course no connection will be attempted to this IP address.
result = sock.connect_ex((ip_try,port))
if result == 0:
SSH_ips.append(ip_try)
print("Found %d" % (ip_try))
else:
print("Didn't work")
Similar here check why exactly connect_ex failed instead of just assuming that it failed because there is no open port on the other end.

How can I send information from client side to server side using PIR-sensor [WinError 10057]

We are two students working on a school project. The task is to connect a PIR-sensor (motion sensor) to a raspberry pi and whenever the sensor is detecting motion it should send a string to a text document on our AD/DNS server running Windows Server 2019. We are coding in Python and the code we use for the client (Raspberry Pi running the PIR-sensor) is using the following code:
import RPi.GPIO as GPIO
import time
import datetime
import socket
GPIO.setmode(GPIO.BCM)
pir = 24
GPIO.setup(pir, GPIO.IN)
print ("Sensor initializing...")
time.sleep(2)
print ("active")
print ("press ctrl+c to end program")
mouvement = "Motion detected at "
while True:
if GPIO.input(pir) == True:
now = datetime.datetime.now()
fb = open("/home/pi/Projekt/pirsensor.txt", "a+")
#print (mouvement)
print(now.strftime("%Y-%m-%d %H:%M:%S "))
fb.write(mouvement)
fb.write(now.strftime("%Y-%m-%d %H:%M:%S "))
fb.write("\n")
fb.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.3', 5007))
s.send(mouvement)
s.send(now.strftime ("%Y-%m-%d %H: %M: %S "))
s.send("\n")
s.close()
#time.sleep(2)
#time.sleep(0.1)
GPIO.cleanup()
print (" program ended")
and the code we are using for the Windows Server 2019 is the following:
from socket import *
port = 5007
file = ''
class Server:
gate = socket(AF_INET, SOCK_STREAM)
host = '192.168.1.3'
def __init__(self, port):
self.port = port
self.gate.bind((self.host, self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
print("Lyssnar på anslutningar, via port: ", self.port)
add = self.gate.accept()
self.reciveFileName()
self.reciveFile()
def reciveFileName(self):
while True:
data = self.gate.recv(1024)
self.file = data
def reciveFile(self):
createFile = open("new_"+self.file, "wb")
while True:
data = self.gate.recv(1024)
createFile.write(data)
createFile.close()
server= Server(port)
listen()
Both devices are running on the same LAN network and have static IP-adresses. We are able to ping each other and able to send the information from the Raspberry pi with the PIR-sensor to the Windows Server 2019 machine. However, we have a problem. When we run the code on the Raspberry pi and wait for our server to recieve the data we get the following error:
[WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
See image of the error
We are stuck on this error and don't know how to fix it. We have been searching the web but we only find threads from 2006 and none of them are of any help. It's also worth noting that we have tried disabling the firewall. We also have no experience with coding in Python.
It could be because the a new socket is being created every time the while loop iterates. It would be better to declare & connect your socket outside the loop, and only send the data from inside the loop:
mouvement = "Motion detected at "
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.3', 5007))
while True:
if GPIO.input(pir) == True:
now = datetime.datetime.now()
fb = open("/home/pi/Projekt/pirsensor.txt", "a+")
#print (mouvement)
print(now.strftime("%Y-%m-%d %H:%M:%S "))
fb.write(mouvement)
fb.write(now.strftime("%Y-%m-%d %H:%M:%S "))
fb.write("\n")
fb.close()
s.send(mouvement)
s.send(now.strftime ("%Y-%m-%d %H: %M: %S "))
s.send("\n")
#time.sleep(2)
#time.sleep(0.1)
s.close()
GPIO.cleanup()
print (" program ended")
This should give your socket sufficient time to initialize, connect, send, and close. Another benefit of this it the loop shouldn't block while waiting to connect, making the program run faster.

python - print out ports with their names

I have the following code written in 2.7 python:
#...import stuff
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
print "Please wait, scanning remote Host", remoteServerIP
try:
for port in xrange(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print "port {}: open".format(port)
sock.close
except KeyboardInterrupt:
print "\nexiting..."
sys.exit()
Output:
Enter a remote host to scan: www.myexamplesite.com
Please wait, scanning remote Host xxx.xxx.xx.xx
port 21: open
port 22: open
...
But the problem is that I also want to know which ports are used and for what they are used just like:
#... as usual
port 1 httpserver
port 2 chat server
...
but this is only printing the ports from 1 to 1024
is there a function/way to do this?
socket.getservbyport() will translate port numbers into the service expected to be running on that port (via /etc/services), but won't actually communicate over the port to find out what is really running.

Port Scanner 3.5 Python Print Issue After Going Through set range

import socket
import sys
from datetime import datetime
#Ask the user for input, the form of a remote host entire in the IP address of the target machine
remoteServer =input ("Enter a remote host to scan:")
remoteServerIP =socket.gethostbyname(remoteServer)
#Print a block of text with information on which host we are about to scan.
#While scanning display a message so the user knows the program is working and isn't frozen
print ("_"*60)
print ("Please wait, currently scanning remote host", remoteServerIP)
print ("_"*60)
#Show/check the time scan started
t1 = datetime.now()
#range function to specify ports, this case I have set the pogram to go through ports 1 to 150
# port in range works like so
try:
for port in range (1, 150):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print ("Port {}: Open".format(port))
sock.close()
# Press Ctrl C to leave the application
except KeyboardInterrupt:
print ("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Couldn't connect to server")
sys.exit()
# 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
# Printing the information to screen
print ('Scanning Completed in: ', total)
My boss has told me to start learning about Metasploitable2 and Kali Linux as such I have attempted to create a port scanner it seems to work fine for most of the part however. after if has finished scanning the ports within it's set range it close completely rather then print ('Scanning Completed in: ', total) with listed findings. What have I done wrong here? And I 'm well aware this is script slow I'm going to attempt to make it multithreaded later on.

Categories