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!
Related
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!
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 trying to write a python program that will ping sweep a given network (192.168.0.0/24) for example. And then store the alive hosts in an array. From that array, I want to port scan them using a function I wrote. However, I have no idea what I'm doing wrong.
Here is a condensed version of the script not using the alive hosts, just the entire subnet (its the same idea):
#!/usr/bin/env python
import socket
import ipaddress
def portscan(host):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
for port in range(75,85):
result = sock.connect_ex((host, port))
if result == 0: #the error indictator returns 0 if the operation succeeds.
print "port ",port," is open on ", host
# else:
# print "port ",port," is closed"
sock.close()
logging.debug(i)
except:
print "no connection on port",port, "from host",host
def main():
subnet = ipaddress.ip_network(u'192.168.0.0/29')
for i in subnet:
print i
portscan(i)
if __name__ == "__main__":
main()
The above just returns:
192.168.0.0
no connection on port 75 from host 192.168.0.0
192.168.0.1
no connection on port 75 from host 192.168.0.1
192.168.0.2
no connection on port 75 from host 192.168.0.2
192.168.0.3
no connection on port 75 from host 192.168.0.3
192.168.0.4
no connection on port 75 from host 192.168.0.4
192.168.0.5
no connection on port 75 from host 192.168.0.5
192.168.0.6
no connection on port 75 from host 192.168.0.6
192.168.0.7
no connection on port 75 from host 192.168.0.7
[Finished in 0.0s]
I've also wrote a script that runs a portscan on one specific host, and it works totally fine:
#!/usr/bin/env python
import socket
import sys
server = '192.168.0.1'
def portscanner():
try:
for port in range(1,445):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((server, port))
if result == 0: #the error indictator returns 0 if the operation succeeds.
print "port",port," is open on",server
# else:
# print "port ",port," is closed"
sock.close()
except KeyboardInterrupt:
print " CTRL+C Interruption. Exiting..."
sys.exit()
portscanner()
the hard coded ip returns:
port 80 is open on 192.168.0.1
port 443 is open on 192.168.0.1
[Finished in 20.3s]
I've wrote so many different variations off this to get it to work. But I'm consistently getting it wrong!
I'm also very new to Python, so be gentle!
TL;DR:
iterate through a bunch of IP addresses and call a portscan function on each IP address.
try:
for port in range(75,85):
Your for loop is inside the try block -- as soon as one of the connection attempts fails, it jumps directly to the except clause and skips all of the other ports in the loop. Since most systems won't have port 75 open, this will make the "scan" fail.
Move the for loop outside the try, like you have it in your other script.
I am trying to do wireless communications between a PC (macbook) and a Raspberry Pi 2 using python's socket module (python 2.7). The server is the PC and the client is the Pi.
When I run the code (server first then client) both scripts get stuck on the socket.accept() and socket.connect() methods respectfully.
What is funny is that when I do the reverse (Pi being the server and PC being the client) the code works fine, with data been sent correctly.
The scripts below are meant to loop forever whilst incrementing a counter sent over (I increment the port's after each succesful transfer to avoid '[Errno 48] Address already in use' (probably terrible practice I know))
My client script:
import socket
import sys
def read(port):
s = socket.socket()
host = '10.19.92.44' #(IP address of PC (server))
s.connect((host,port))
try:
msg = s.recv(1024)
s.close()
except socket.error, msg:
sys.stderr.write('error %s'%msg[1])
s.close()
print 'close'
sys.exit(2)
return msg
if __name__ == '__main__':
port = 1025
while True:
print 'hey, checking TCP socket'
data = read(port)
print 'i just read %s' % data
print 'port num is: %d' % port
port = port + 1
My server script:
import socket
import time
def send(data, port):
s = socket.socket()
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from',addr
c.send(data)
c.close()
if __name__ == '__main__':
port = 1025
num = 1
while True:
print 'hey, sending data'
words = 'helloWorld'
data = words + str(num)
print 'send data: %s' % data
send(data,port)
port = port + 1
num = num + 1
As I mentioned when I swap roles (and replace the server IP address in the client script to the Pis 172.17.33.125) the code works fine...
Any ideas/suggestions?
Thank you very much
I don't have an immediate answer, but I have a couple of ideas.
Your PC and Pi seem to be in different networks. The PC's address is 10.19.92.44, while Pi's is 172.17.33.125. There's a probability that 10.19.92.44 isn't the address you need. In order to find out what is the correct PC IP address to use in the application:
Issue networksetup -listallhardwareports to figure out the name of your wifi interface (should be like en0, en1).
Issue ifconfig, find the wifi interface. The IP address attached to this interface is the one you need.
Another option is to install wireshark on the PC, set up a working system (server-Pi, client-PC) and use wireshark to capture the traffic between the PC and Pi. Wireshark makes it easy to figure out IP addresses of both parties. I would advise to have this program installed whenever you want to debug a complicated networking issue.
I'm trying to create the ability for a client to enter the IP address/port of a server and connect to it. In order to do this, I need the server's public IP address/port. Is there a good way to do this? What I've tried so far is...
ip_address = urllib.request.urlopen(<my web server>).read()
with the web server just containing the php script:
<?php echo $_SERVER["REMOTE_ADDR"]?>
And just storing the port from the
s.bind(('', port))
Connecting to this ip address and port times out. Is there a better way to do this?
EDIT:
OK so basically I'm trying to establish a connection over the internet, without knowing exactly what my router is going to be doing. I can use a webserver with any code if necessary, as I have access to permanent webspace. This is what I have right now.
Server:
import urllib.request
import threading
import socket
socket_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 0))
s.listen(10)
def listener(socket):
while(1):
data = socket.recv(1024)
print (data)
def accepter():
while(1):
socket, addr = s.accept()
socket_list.append(socket)
threading.Thread(target = listener, args = (socket,)).start()
ip_address = (urllib.request.urlopen("<MY WEB SERVER HERE>").read()).decode('utf-8')
print (ip_address)
print (s.getsockname()[1])
threading.Thread(target = accepter, args = ()).start()
Client:
import socket
print ("Enter IP Address")
ip_address = input()
print ("Enter Port")
port = int(input())
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect((ip_address, port))s2.send("Connected!")
s2.close()
When I run the client I'm entering the IP address and port that are outputted by the server. Needless to say, this doesn't work.
I thought this was a good question you can do it like this if you didn't want to have your server set up like you have:
""" Easy IP Getter """
import json
import urllib2
info = json.loads(urllib2.urlopen("http://jsonip.com").read())
ip = info["ip"]
print ip
It depends on an outside service however which isn't the best, if they stop working you stop working.