My portScanner program fails after entering any IP address - python

this is my code:
import socket
target = input("enter ip addressd to scan: " )
portrange = input ("enter port range 5-200: " )
lowport = int(portrange.split("-")[0])
highport = int(portrange.split("-")[1])
print ('scanning host', target, 'from port',lowerport , 'to port', highport )
for port in range(lowport,highport):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
status = s.connect_ex(target, port)
if (status == 0):
print ('**port', port, ' -open**')
else:
print('port--',port,' --closed')
s.close()
I keep getting this error when executing the code from my terminal and entering an IP address
Traceback (most recent call last):
File "portScan.py", line 3, in <module>
target = input ("enter ip address to scan: " )
File "<string>", line 1
SyntaxError: invalid syntax
help???

You're probably using python2. The Python v2 input function doesn't do what you seem to think it should do. From pydoc2.7 input:
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
Notice the eval(). That causes Python to evaluate whatever was input as if it is valid Python code. This behavior was changed in Python v3 so that it no longer eval's the input.
Don't use Python v2. Use Python v3. If you absolutely have to use that ancient version you should be using raw_input. Also, there are other, more serious, problems with your program. Port scanners have been written many, many, times. Don't reinvent the wheel.

Try This After correcting your code :
import socket
target = input("enter ip addressd to scan: " )
portrange = input("enter port range 5-200: " )
lowerport = int(portrange.split("-")[0])
highport = int(portrange.split("-")[1])
print ('scanning host', target, 'from port',lowerport , 'to port', highport )
for port in range(lowerport,highport):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
status = s.connect_ex((target,port))
if (status == 0):
print ('**port', port, ' -open**')
else:
print('port--',port,' --closed')
s.close()
your errors was in typing:
input() not input ()
and the variable lowerport sometimes you name it lowerport and sometimes lowport
finally:
status = s.connect_ex(target, port)
need to be like this s.connect_ex((target, port))
because it use tuples not strings
I hope that will be helpful for you.

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.

TypeError when trying to pass output of one function to another function

I'm trying to make a chat room/text message tool with python. I need to connect to the server with the .connect() method. Every time I go somewhere outside of my house and connect to wifi, my private ip address changes, so I want my code to adapt to that situation by passing os.system("ipconfig getifaddr <wireless interface>") to the .connect() method.
I found out this isn't correct after running my code, which raised a TypeError. I know this isn't correct because the os.system() function executed and printed my ip address to the console instead of passing that output to the function. I'm assuming that the function returned 0 to the function, indicating that nothing went wrong with the command, which is not my intention. I want the ip address to be passed to the function.
It's somewhat similar to bash, like this: ipconfig getifaddr <wireless interface> > file.txt where the output of the command is redirected to a file called file.txt
Here is my code:
client.py
import socket
import threading
import subprocess
nickname = input("Choose a nickname: ")
subprocess.run("./ipaddress.sh")
with open("ip_addr.txt", 'r') as f:
file = f.readline()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((file, 48812))
def receive():
while True:
try:
message = client.recv(1024).decode('ascii')
if message == 'NICK':
pass
else:
print(message)
except:
print("An error occurred!")
client.close()
break
def write():
while True:
message = f'{nickname}: {input("")}'
client.send(message.encode('ascii'))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
I don't know if I also have to make changes in the server file but if I do here is the code for you to see as well:
server.py
import threading
import socket
import subprocess
subprocess.run("./ipaddress.sh")
with open("ip_addr.txt", 'r') as f:
file = f.readline()
host = file
port = 48812
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f"{nickname} left the chat".encode('ascii'))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print(f"Connected with{str(address)}")
client.send("NICK".encode("ascii"))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f"Nickname of client is {nickname}\n")
broadcast(f'{nickname}joined the chat!\n'.encode('ascii'))
client.send("Connected to the server!\n".encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
print("Server is listening...")
receive()
And here is the full traceback:
Traceback (most recent call last):
File "/Users/matthewschell/PycharmProjects/TCP Chat Room/server.py", line 14, in <module>
server.bind((host, port))
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
EDIT: Instead of using os.system(), like others don't recommend, I've used subprocess instead. It fixed the exception that os.system() raised but now it raises another exception. See the full traceback above. Also see the edited code above. Notice the new with statement to open a file created by a bash script containing the ip address in both files.
Your guess was correct os.system() returns the exit code of the subprocess, which is an integer (0 is success). What do you’re looking for is stdout from the subprocess and the best way to get that is to use the Python “subprocess” module instead of os.system.
>>> outcome = subprocess.run('/bin/date', capture_output=True)
>>> outcome.returncode
0
>>> outcome.stdout
b'Thu 11 Feb 2021 18:30:57 GMT\n'
>>>

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()

How Can I tell if my Port Scanner is Working?

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.

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