How can I set a value error exception in python - python

I have the following code:
while True:
try:
HOST = input(float(('Enter host IP'))
except ValueError:
print('Error. That is not a valid IP address.')
continue
I require the user to input an IP address. I wanted to set an error so that if he uses a letter he gets an error. How can I do that and why isn't my code working?

Try something like this
while True:
try:
HOST = input('Enter host IP: ')
if len(HOST.split(".")) != 4:
raise ValueError
for char in HOST:
if char not in "0123456789.":
raise ValueError
except ValueError:
print('Error. That is not a valid IP address.')
continue
else:
break

There is no need for the try/except. You just need an IP validation. This code should be working.
import re
while True:
HOST = input("Enter IP adress: ")
if re.match(
r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
HOST,
):
print(f"{inp} is valid IP adress")
break
else:
print("Enter valid IP adress")

I will begin by pointing out a few problems with your submitted code. First of all, your code will never exit the while loop, since you have provided no break out. Secondly, a valid IP address takes the form of something along the lines of 192.168.2.10 for IPV4 or "2001:0db8:0a0b:12f0:0000:0000:0000:0001" for IPV6, and which can never be interpreted as a float, so you will always generate a value error response. In order to validate an IP addfress correctly checkout the following check if a string matches an IP address pattern in python?.
import ipaddress
Host = None
while True:
try:
Host = ipaddress.ip_address(input('Enter host IP'))
break
except:
print('Error. That is not a valid IP address.')
continue

Related

My portScanner program fails after entering any IP address

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.

Python program for NSlookup result

I want to build a Python program to check the NSlookup result.
In my program, I want to output like:-
If I input google then it will show “not unique” as output, but
when I provide input like Rajat then the output will be unique because rajat.com is not a valid site (invalid URL no IP is linked with this URL)
Below is my code.in this code will show not unique when I input google but throw an error when I input Rajat.
So I just want to know how to handle this error or how we can get the output as unique when the program throws an error.
import socket
dns=input("Enter DNS: ")
result= socket.gethostbyname(dns+".com")
if not result:
print("Unique")
else:
print("Not Unique")
The gethostbyname() function raises the socket.gaierror exception if the given hostname is not found, so you have an opportunity to catch it and perform what you want:
import socket
dns=input("Enter DNS: ")
try:
result= socket.gethostbyname(dns + ".com")
except socket.gaierror:
print("Unique")
else:
print("Not Unique"))
Note:
In my humble opinion the better messages would be something as “Not used” / “Used” or
“Not found” / “Found”. Yours are a little confusing.
You can use try-except to catch an error. In this code snippet we try to connect to the given domain and if the connection is successful (the website exists) it prints Not unique, if not, it prints Unique.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = input("Enter DNS: ")
try:
s.connect((dns + ".com", 80))
except Exception as e:
print("Unique")
else:
print("Not unique")

Distinguish between an IP address and FQDN

Do you know if there is any pattern/logic that could be used to distinguish between an IP address and an FQDN in python? I have a script that process user input which could be ip or fqdn and i would like to to ip validation checks if ip, and no validation check in case it is fqdn.
addy = "1.2.3.4"
a = addy.split('.')
match = re.search('^(([0-9]|[0-9][0-9]|[0-9][0-9][0-9]))$', a[0])
if match is not None:
if is_valid_ipv4(addy) == True:
# code continues
what is case addy is fqdn? I wish to call is_valid_ipv4 if input string is only an IP address. Do I need a pattern for FQDN? How to distinguish between IP and FQDN?
Python knows about IP addresses. Meanwhile, this answer gives a pretty good regexp for validating FQDNs.
import ipaddress
import re
addy = "192.0.2.1"
fqdn_re = re.compile('(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}\.?$)')
try:
ip_addy = ipaddress.ip_address(addy)
if ip_addy.version == 4:
print("IPv4 address")
elif ip_addy.version == 6:
print("IPv6 address")
except ValueError:
if fqdn_re.search(addy):
print("FQDN address")
else:
print("Invalid address")
Personally, I'd use regex. In Python you can use the re package.
Write a pattern for each (IP and FQDN) and see which gets a match (re.match()).
Here are some useful links:
Bulding a regex for an IP address
Test your regex patterns

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.

python: check if IP or DNS

how can one check if variable contains DNS name or IP address in python ?
This will work.
import socket
host = "localhost"
if socket.gethostbyname(host) == host:
print "It's an IP"
else:
print "It's a host name"
You can use re module of Python to check if the contents of the variable is a ip address.
Example for the ip address :
import re
my_ip = "192.168.1.1"
is_valid = re.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", my_ip)
if is_valid:
print "%s is a valid ip address" % my_ip
Example for a hostname :
import re
my_hostname = "testhostname"
is_valid = re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname)
if is_valid:
print "%s is a valid hostname" % my_hostname
I'd check out the answer for this SO question:
Regular expression to match DNS hostname or IP Address?
The main point is to take those two regexs and OR them together to get the desired result.
print 'ip' if s.split('.')[-1].isdigit() else 'domain name'
This does not verify if either one is well-formed.

Categories

Resources