Create IP and Port Scanner Python - python

I am having trouble creating an port scanner that scans IP addresses and ports at the same time. The port scanning part of the code works fine but I cannot add the IP addresses in correctly and make the loops work in sync. I am asking the user to input the first 3 octets, then the code will use the fourth octet to scan and move the number forward. The output is supposed to look like:
IP 127.0.0.1 Port 22 is closed
IP 127.0.0.1 Port 23 is closed
IP 127.0.0.1 Port 24 is closed
IP 127.0.0.2 Port 22 is closed
IP 127.0.0.2 Port 23 is closed
IP 127.0.0.2 Port 24 is closed
....etc
Here is the code so far:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = 'google.com'
portstart = int(input("Enter starting port number to scan: "))
portend = int(input("Enter end port number to scan: "))
octets = input("Enter the first 3 octets of an IP to scan:")
fourthoctet = 1
for portnum in range (portstart, portend):
try:
s.connect((server,portnum))
print("port",portnum,"is open")
except:
print("port",portnum,"is closed")
for fourthoctet in range (1,256):
print("IP", octets,".",fourthoctet)

Judging by your desired output, shouldn't your loop look like this instead?
for fourthoctet in range (1,256):
for portnum in range (portstart, portend):
print("IP", octets,".",fourthoctet, end=" ")
try:
s.connect((server,portnum))
print("port",portnum,"is open")
except:
print("port",portnum,"is closed")

Related

Scapy Port Scanner with CIDR/IP Range or Single IP/Domain input

I have the following code to scan a single host on the given range of ports. I want to modify this so that the input will also accept CIDR slash notation(e.g. google.com/34 or 8.8.8.8/34) (i.e. in addition to a single domain name or IP address).
How can I do this?
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import sys
from scapy.all import *
# Define end host and TCP port range
hostInput = input("Enter a remote host to scan: ")
host = socket.gethostbyname(hostInput)
port_range = [21,22,23,25,53,80,110,135,137,138,139,443,1433,1434,8080]
# Send SYN with random Src Port for each Dst port
for dst_port in port_range:
src_port = random.randint(1025,65534)
resp = sr1(
IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=1,
verbose=0,
)
if resp is None:
print(f"{host}:{dst_port} is filtered (silently dropped).")
elif(resp.haslayer(TCP)):
if(resp.getlayer(TCP).flags == 0x12):
# Send a gratuitous RST to close the connection
send_rst = sr(
IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags='R'),
timeout=1,
verbose=0,
)
print(f"{host}:{dst_port} is open.")
elif (resp.getlayer(TCP).flags == 0x14):
print(f"{host}:{dst_port} is closed.")
elif(resp.haslayer(ICMP)):
if(
int(resp.getlayer(ICMP).type) == 3 and
int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]
):
print(f"{host}:{dst_port} is filtered (silently dropped).")
You can try using
host = Net(hostInput)
Net is the util class Scapy uses to handle IPv4 addresses formats. If you pass it to a packet, sr( will send a packet to each host.
However I'm not sure how plug and play this is going to be: the use of sr1 restricts the output to a single packet, so you're probably going to have to change that to sr (which gives you a list of all answers)

Python socket - issues taking ip, takes it as a string

Been trying to solve this simple script, without luck. The error I got is the following:
python renato_script.py
Enter HOSTNAME ip: 10.0.0.2
Enter TCP/UDP port: 443
Traceback (most recent call last):
File "renato_script.py", line 8, in
if s.connect_ex((ip, port)):
TypeError: an integer is required (got type str)
import socket
ip = input( "Enter HOSTNAME ip: ")
port = input ("Enter TCP/UDP port: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if s.connect_ex((ip, port)):
print ("Port", port, "is closed")
else:
print ("Port", port, "is open")
According to https://docs.python.org/3/library/socket.html, the AF_INET address family needs a tuple which contains a string ip address and a integer port. Your code passes a tuple which contains a string ip address and string port. Fixing that is very simple, just cast the port to int, like this:
port = int(raw_input("Enter TCP/UDP port: "))
edit: when using python 2, you have to use raw_input() rather than input()

Socket programming port help python

I am trying to implement socket programming and want to configure the communication port number for both the server and client to a specific port. I specify the same port number on both the the client and server side but still when the program run's it takes a random port number. How do I fix the port number/make it static?
Server Side Code
import socket
s=socket.socket()
port=12345
s.bind(("192.168.0.111",port))
s.listen(5)
while True:
c, addr = s.accept()
print("got connection from ",addr)
sendingMessage = "Thank you for connecting"
c.send(bytes(sendingMessage, 'UTF-8'))
data = c.recv(16)
receivedData=data.decode("utf-8","ignore")
print (receivedData)
c.close()
if receivedData=="stop":
break
Client Side Code
import socket
port=12345
s=socket.socket()
s.connect(("192.168.43.111",port))
sendingMessage = input("Enter your message : ")
s.send(bytes(sendingMessage, 'UTF-8'))
data = s.recv(32)
receivedData=data.decode("utf-8","ignore")
print (receivedData)
s.close
If you want the client side to also use port 12345, you must also bind the client side port number. The port number given in the s.connect is the remote port to which you're connecting. IOW, your code should look something like this in the client:
s = socket.socket()
s.bind(('', port))
s.connect(("192.168.43.111", port))
You can also specify an IP address in the bind but typically you don't need to as the local IP address will be established by the route to the remote host.

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)

Python network programming(bind to external address)

I am a newbie to python, and just few days back I started trying my hands on network programming(I am a newbie there too)
Now I found a neat client server program which was running quite simply on my computer, but when I replaced the local addresses, and told my friend to run the client script, it just wont respond.
My global I.P address : 120.59.XX.XXX
My Ipv4 address as returned by ipconfig : 192.168.1.2 (I am connected to internet through a router)
My gateway address : 192.168.1.1
Port used : 1060 (I tested this port locally and it wasn't in use)
#server.py
import socket
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
server.bind(('192.168.1.2', PORT))
print 'Listening at', server.getsockname()
while True:
data, address = server.recvfrom(MAX)
print 'The client at', address, 'says', repr(data)
server.sendto('Your data was %d bytes' % len(data), address)
Client Code :
#client.py
import socket
import sys
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
PORT = 1060
MAX = 65536
client.sendto('Hello Server!', ('120.59.XX.XXX', PORT))
data, address = client.recvfrom(MAX)
print 'The server', address, 'says', repr(data)
I started server.py on my computer and told my friend to start client.py, I allowed incoming connections to python through firewall, also I added 1060 port to windows incoming connections list.
Still it is not responding, and I am unable to decipher why(I have a dynamic IP address, but for the current session it remains constant and hence should work, also 1060 is a well known port and shouldn't be a problem right?)
You need to add a port forwarding rule in your router! something like from port 1060 forward to 192.168.1.2 port 1060.
You need a port-forward on the router, which would forward connections to router's external (global) address on port 1060 to your desktop IP 192.168.1.2 port 1060.

Categories

Resources