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()
Related
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.
I recently ventured into python in 3.7
I want to make a server / client whose client will show the path I put in input (macOS):
Server
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 1337 # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
info = conn.recv(1024)
print(info)
raw_input("Push to exit")
s.close()
Client :
import socket
import os
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = os.listdir("/Users/jhon")
s.send(str(info))
s.close()
Server start and it's listening...
python client.py Connected Traceback (most recent call last): File
"client.py", line 10, in
s.send(str(info)) TypeError: a bytes-like object is required, not 'str' (not understand this), and after client start, in server show:
Connected by ('127.0.0.1', 52155) b'' Traceback (most recent call
last): File "server.py", line 13, in
raw_input("press for exit") NameError: name 'raw_input' is not defined (venv) MBP-di-Jhon:untitled1 jhon$
You may want to change the client code to:
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = "\n".join(os.listdir("/Users/jhon"))
s.send(info.encode())
s.send(info)
s.close()
os.listdir("/Users/jhon") returns a list, we use join and encode to make it byte object, which is needed for s.send()
You ventured into 3.7 from some 2.x version without modifying the 2.x code. Read something about the differences before continuing. To help you get started:
Replace raw_input with input. (One could replace 2.x input() with eval(input()), but one should nearly always use a more specific evaluator, such as int(input()).)
In 3.x, strings are unicode, whereas sockets still require bytes. Change send and recv to
s.send(str(info).encode())
info = conn.recv(1024).decode()
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")
Im making a port scanner it through's this message here is my code but it checks one port 21 i have pasted output below
import socket
import os
host = input("Enter the host name or ip : ")
s = socket.socket()
s.settimeout(5)
p = 0;
s.close
port = [21,22,23,25,53,80,110,115,135,139,143,194,443,445,1433,3306,3389,5632,5900,6112]
while(p<=19):
try:
s.connect(('host', port[p]))
except ConnectionRefusedError:
print("Port %d is close" %(port[p]))
except socket.timeout:
print("Port %d is close" %(port[p]))
else:
print("Port %d is open" %(port[p]))
p=p+1;
s.close
On command line :
PS E:\Codes by me\Selenium py> python .\practice.py
Enter the host name or ip : 89.86.98.76
Port 21 is close # it checks one port
Traceback (most recent call last):
File ".\practice.py", line 11, in <module>
s.connect((host, port[p]))
OSError: [WinError 10022] An invalid argument was supplied
You are passing the literal string 'host' as the host. You should be passing the variable host:
s.connect((host, port[p]))
You are also not actually closing the socket each time, since you left off the parentheses in s.close(). But if you did close the socket each time, you would have to create a new socket each time, instead of trying to reuse the same socket. You can't reuse a closed socket.
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)