I am learning hacking from this tutorial on youtube. Around 1:11:30 (timestamp), he tries to check for open ports on the ip of his own router and on http://testphp.vulnweb.com. He gets 4 ports as open for each. When I run my code I only get port 80 open on my router and none on http://testphp.vulnweb.com.
This is my Code:
import socket
from IPy import IP
def check_ip(address):
try:
IP(address)
return address
except ValueError:
return socket.gethostbyname(address)
def scan(target):
ip_address = check_ip(target)
print(f"\n[-_0 Scanning Target] {str(target)}")
for port in range(1, 100):
scan_port(ip_address, port)
def scan_port(ipaddress_, port_):
try:
sock = socket.socket()
sock.settimeout(0.5)
sock.connect((ipaddress_, port_))
print(f'[+] Port {str(port_)} is open')
except:
pass
targets = input("[+] Enter Target(s) to scan (split multiple targets with , ): ")
if ',' in targets:
for target in targets.split(','):
scan(target.strip(' '))
else:
scan(targets)
And this is the output:
[+] Enter Target(s) to scan (split multiple targets with , ): 192.168.1.1 , testphp.vulnweb.com
[-_0 Scanning Target] 192.168.1.1
[+] Port 80 is open
[-_0 Scanning Target] testphp.vulnweb.com
So, where am I going wrong? Is it a problem with my connection? my code? or is this normal, and if it is then why is the guy on youtube getting a different result?
Any help is greatly appreciated!
Related
I was trying to scan ports through socket but it's show all ports closed. Here is my code:
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = input(" Please Input Ip address To Scan ")
#port = input(" ENter The Port ")
def portscanner(host):
for port in range(1,150):
if sock.connect_ex((host,int(port))):
print(f"{port} Is Closed")
else:
print("port is open")
portscanner(host)
Try creating a connection inside the forloop. And make sure that the input is in valid form.
You can do that using
try and catch near the sock.connect_ex to check whether you are actually sending valid host or not.
To make things faster you can use settimeout(0.25) inside the for loop too.
I meant to do this -
for port in range(start, end):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(.25)
result = sock.connect_ex((host, port))
if result == 0:
print(port,'port is open')
sock.close()
I'm running a port scanner on my home network. If I run it against devices on my home network, it only works on other Linux machines (physical machines not VMs). By "works" I mean it finds what few ports are actually open (ssh, mysql, sunrpc, and a couple others).
When scanning Windows and other miscellaneous iot devices it just hangs and never finishes. I can't seem to figure out where it gets stuck.
I think this might be the most relevant part of the code:
for port in range(begin, end):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
status = s.connect_ex((self.target_ip, port))
except Exception:
continue
finally:
s.close()
if status != 0:
continue
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
print("SERVICE: %-15s\tPORT: %-8d" % (service, port))
I modified your code so that I could simulate a run on my machine and it seems like it hangs because that very last print statement is not reached. But this is because your continue line within the if status != 0 always comes back as "not 0", at least on my Windows 10 Pro machine.
for port in range(begin, end):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
status = s.connect_ex((self.target_ip, port))
print("DEBUG: ", status) # add this
except Exception as err:
print("Error: ", err) # add this
continue
finally:
s.close()
if status != 0:
print("DEBUG: status was not 0") # add this
# if this line is reached, we start at the top of the loop
# skipping the try except and print below entirely.
continue
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
print("SERVICE: %-15s\tPORT: %-8d" % (service, port))
Could you give this a shot and see if will shine some light on what might be wrong or let us know what kind of output you get. I was not able to currently run this on any Linux machine or IoT devices. I assume you are able to read the console output on each of your devices to have determined that it seemed like it was "hanging".
Edit 1: More context for the hanging issue
Let me give you some examples of what happens with this script on my network.
CASE 1: '192.168.1.0'
This address exists, but generally isn't used or assigned to anything. Hangs for about 20 seconds per port for me.
CASE 2: '192.168.1.1'
This is usually the router on the network. Responds immediately. Hangs for about 1 second per port that is scanned.
CASE 3: '192.168.1.3'
This device is in the network range, but no device is actively using it. Hangs for about 20 seconds per port (just like case 1).
So the long "hang" isn't that it is not working. It can basically mean the IP is wrong or there is no device being reached so the timeout limit is being reached for that socket connection attempt instead of raising an exception it just moves on.
Edit 2
Before iterating over a huge range of IP addresses and a wide range of ports per each IP address being tested. Sometimes it can be helpful to test assumptions 1 at a time by defining more control over a few ports and a specific IP address.
This is what I converted your code into to do that. If the conn is not 0 I am just considering that port closed no matter which error code came back for this case. We only care about the ones that respond with 0 because that indicates the operation succeeded.
import socket
# Lets test just a few custom ports.
ports = [21, 22, 80, 8080]
# And test a specific IP address to test, 1 at a time.
ip = '192.168.1.1' # change this if needed
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for port in ports:
# loop through our small custom port range.
try:
conn = sock.connect_ex((ip, port))
if conn == 0:
print("Port [{}] open.".format(port))
else:
print("Port [{}] closed.".format(port))
except Exception as err:
print(err)
continue
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
print("SERVICE: %-15s\tPORT: %-8d" % (service, port))
sock.close()
So I made a port scanner and I want to give description to the ports. So like printing the port with the description. I was thinking my best bad is to make the description on a file and then print it but I don't know how to do that. Or on the file I could put the port and then the description separate them with a ":", search for that port on the file and get the description.
def scan_port(port):
try:
timeout = 10.0
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
result = sock.connect_ex((remoteHost,port))
identify_port()
if result == 0:
print(colored("[+] Port {}: Open".format(port), 'green'))
sock.close()
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.
So I'm working on a simple port scanner in python for a class (not allowed to use the python-nmap library), and while I can get it to work when passing a single IP address, I can't get it to work using a range of IPs.
This is what I have:
#!/usr/bin/env python
from socket import *
from netaddr import *
# port scanner
def port_scan(port, host)
s = socket(AF_INET, SOCK_STREAM)
try:
s = s.connect((host, port))
print "Port ", port, " is open"
except Exception, e:
pass
# get user input for range in form xxx.xxx.xxx.xxx-xxx.xxx.xxx.xxx and xx-xx
ipStart, ipEnd = raw_input ("Enter IP-IP: ").split("-")
portStart, portEnd = raw_input ("Enter port-port: ").split("-")
# cast port string to int
portStart, portEnd = [int(portStart), int(portEnd)]
# define IP range
iprange = IPRange(ipStart, ipEnd)
# this is where my problem is
for ip in iprange:
host = ip
for port in range(startPort, endPort + 1)
port_scan(port, host)
So when I run the code, after adding print statements below
host = ip
print host # added
and then again after
port_scan(port, host)
print port # added
I end up with the following output:
root#kali:~/Desktop/python# python what.py
Enter IP-IP: 172.16.250.100-172.16.250.104
Enter port-port: 20-22
172.16.250.100
20
21
22
172.16.250.101
20
21
22
...and so on
Thanks in advance everyone!
I appreciate any help that I can get!
code picture for reference, slightly different
output picture for reference
The problem turned out to be an issue with using the netaddr.IPRange, as suggested by #bravosierra99.
Thanks again everyone!