This is an IP address problem where I need to implement a function is_valid_IP that takes an arbitrary string and determines if it represents a valid IPv4 or IPv6 address.
IPv4_STRING = "127.0.0.1"
IPv4_INVALID_STRING = "300.0.0.1"
IPv6_STRING = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
IPv6_INVALID_STRING = "2001:0db8:85a3:0000:0000:8a2e:0370:7334:7334"
INVALID_IP_STRING = "Some arbitrary string"
def is_valid_IPv4_octet(octet: str):
for element in ip_list:
if int(element) < 0 or int(element) > 255 :
return False
return True
def is_valid_IPv4(ip: str):
if ip.count('.') != 3:
return False
quit()
ip_list = list(map(str, ip.split('.')))
return is_valid_IPv4_octet(ip_list)
def is_valid_IPv6_hextet(hextet: str):
for element in ip_list:
if int(element,16) < 0 or int(element,16)>65535 :
return False
return True
def is_valid_IPv6(ip: str):
if ip.count(':')!=7:
return False
quit()
ip_list=list(map(str,ip.split(':')))
return is_valid_IPv6_hextet(ip_list)
def is_valid_IP(ip: str):
if( is_valid_IPv4() or is_valid_IPv6() == True):
print("Valid IP Address")
else:
print("Invalid IP Address")
print(
f"{IPv4_STRING} is a valid IP Address:",
is_valid_IP(IPv4_STRING))
print(
f"{IPv4_INVALID_STRING} is a valid IP Address:",
is_valid_IP(IPv4_INVALID_STRING),
)
print(
f"{IPv6_STRING} is a valid IP Address:",
is_valid_IP(IPv6_STRING))
print(
f"{IPv6_INVALID_STRING} is a valid IP Address:",
is_valid_IP(IPv6_INVALID_STRING),
)
print(
f"{INVALID_IP_STRING} is a valid IP Address:",
is_valid_IP(INVALID_IP_STRING),
)
The IDE gives me
Traceback (most recent call last):
File "C:\Users\jerry\PycharmProjects\pythonProject1\main.py", line 43, in <module>
is_valid_IP(ip)
File "C:\Users\jerry\PycharmProjects\pythonProject1\main.py", line 38, in is_valid_IP
if( is_valid_IPv4() or is_valid_IPv6() == True):
TypeError: is_valid_IPv4() missing 1 required positional argument: 'ip'
Can someone tell me why? I've been surfing a bit, the general opinion is i need to put something in the bracket of the function. But in this case there is somehting inside...So i dont really know where went wrong.
You are missing the arguments here:
def is_valid_IP(ip: str):
#added ip
if( is_valid_IPv4(ip) or is_valid_IPv6(ip) == True):
print("Valid IP Address")
else:
print("Invalid IP Address")
Also since the functions already return True or False you can get rid of the == True
def is_valid_IP(ip: str):
if( is_valid_IPv4(ip) or is_valid_IPv6(ip)):
print("Valid IP Address")
else:
print("Invalid IP Address")
def is_valid_IP(ip: str):
if( is_valid_IPv4() or is_valid_IPv6() == True):
print("Valid IP Address")
else:
print("Invalid IP Address")
here you are calling 2 functions is_valid_IPv4 and is_valid_IPv6. These 2 need an input which is ip.
Related
I would like to check an argument which user types on python.
I wrote a method to check if the argument is half-width character. You may not familiar if you are an English speaker, but some languages use the 2-word widths for 1 word. So I just wanted to write a method to check if a user is not using a unique language.
The method name is "has_digit(password)"
here is my entire code
from sys import argv
import re
if 1 >= len(argv):
print("Please type an argument")
exit()
else:
print("Checking password strength")
password = argv[1]
if has_digit(password) == True and has_lower_letter(password) == True and has_upper_letter(password) == True:
print("This password is strong")
else:
print("This passwor is weak. Please choose another password")
def has_digit(password):
"""
パスワードに半角数字が含まれるかをチェックします。
Args:
チェック対象のパスワード
Returns:
半角数字を含んでいればTrue
"""
m = re.search(r'[0-9]', password)
return True if m else False
def has_lower_letter(password):
"""
パスワードに英字小文字が含まれるかをチェックします。
Args:
チェック対象のパスワード
Returns:
英字小文字を含んでいればTrue
"""
m = re.search(r'[a-z]', password)
return True if m else False
def has_upper_letter(password):
"""
パスワードに英字大文字が含まれるかをチェックします。
Args:
チェック対象のパスワード
Returns:
英字大文字を含んでいればTrue
"""
m = re.search(r'[A-Z]', password)
return True if m else False
error message
File "pw_check.py", line 12, in <module>
if has_digit(password) == True and has_lower_letter(password) == True and has_upper_letter(password) == True:
NameError: name 'has_digit' is not defined
How can I fix this error?
Thank you in advance.
It's just how python parses your file. Your function should be defined before you call it, like :
from sys import argv
import re
def has_digit(password):
"""
パスワードに半角数字が含まれるかをチェックします。
Args:
チェック対象のパスワード
Returns:
半角数字を含んでいればTrue
"""
m = re.search(r'[0-9]', password)
return True if m else False
def has_lower_letter(password):
"""
パスワードに英字小文字が含まれるかをチェックします。
Args:
チェック対象のパスワード
Returns:
英字小文字を含んでいればTrue
"""
m = re.search(r'[a-z]', password)
return True if m else False
def has_upper_letter(password):
"""
パスワードに英字大文字が含まれるかをチェックします。
Args:
チェック対象のパスワード
Returns:
英字大文字を含んでいればTrue
"""
m = re.search(r'[A-Z]', password)
return True if m else False
if 1 >= len(argv):
print("Please type an argument")
exit()
else:
print("Checking password strength")
password = argv[1]
if has_digit(password) == True and has_lower_letter(password) == True and has_upper_letter(password) == True:
print("This password is strong")
else:
print("This passwor is weak. Please choose another password")
I am trying to loop to ask a password until the user enters a valid password then break out of it.
How do I implement this method with a try/except? Is there a better way of doing this? I am a beginning so any help is appreciated!
def is_secure(s):
# This function will check if the passed string s is a valid password
# Return true if string is valid password
# Returns false if string is not a valid password
min_len = 6
max_len = 15
if len(s) < min_len or len(s) > max_len:
return False
else:
return True
while True:
try:
password = str(input("Enter new password:"))
if is_secure(password):
print("Password is secure")
break
except ValueError:
print("False")
else:
print("Password is insecure")
This code should work:
while True:
password = str(input("Enter new password:"))
if is_secure(password):
break
print("Invalid password")
print("Password is secure")
You are trying to handle exceptions that are not thrown anywhere. Another solution would be to throw the exception, instead of printing "invalid password":
raise Exception("Invalid password")
Something like this should hopefully work.
class InsecurePasswordError(Exception):
def __init__(self, message):
super().__init__(message)
class Password:
def __init__(self, pwd: str):
self.pwd = pwd
#property
def pwd(self):
return self._pwd
#pwd.setter
def pwd(self, value):
if len(value) <= 8:
raise InsecurePasswordError('The length of the password is not sufficient!')
elif .....: # Add more conditions
....
else:
self._pwd = value
# And now in your code....
while True:
try:
i = input("Enter new password:")
password = Password(i)
except InsecurePasswordException as e:
print(e)
else:
print("Password is secure")
I want user enter IP subnet which is formatted x.x.x.x/y. But if user enters anything different this format, there should be warning as below. But below code is not working as I want.
What is your suggestion?
def test():
while True:
val = raw_input("enter IP:")
try:
IP=ipaddress.ip_network(str(val),True)
except:
if val == "":
print " Enter subnet:"
else:
print " IP should be formatted X.X.X.X/Y"
test()
basically I need the user to enter an ip address.
All I need to do is check that it's valid (0-255; 4 octets).
lets say a user enters 192.168.10.1,
how can I break it down to 192, 168, 10, 1?
Do this:
while True:
ip = raw_input("Please enter an ip address")
ip_split = ip.split(".")
if len(ip_split) != 4:
print "Must have 4 numbers"
elif not all(number.isdigit() for number in ip_split):
print "Must be numbers"
elif not all(0 <= int(number) <= 255 for number in ip_split):
print "Numbers must be in 0-255 range"
else:
ips = [int(number) for number in ip_split]
break
You can use the split method:
your_string.split(separator)
In your case:
ip = "191.168.10.1"
values_list = ip.split(".")
I have this 2 regexes to check this
import re
ip4 = re.compile(r'^(?:(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)$')
ip6 = re.compile(r'^(?:[\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$')
You can do it in several ways. This could be a solution:
ip = "192.168.10.666"
octates = ip.split('.',4)
flag = True
for each_octate in octates:
num = int(each_octate)
if num>=0 and num<=255:
continue
else:
flag = False
break
if flag == True:
print "IP is correct!"
else:
print "IP is incorrect"
you can take the ip address in as a string and then from there split the str by "." and then check each member for that criteria.
ip = input("Enter Ip address: ")
address = ip.split('.')
if len(address) == 4:
for num in address:
if 255 >= num >= 0:
pass
else:
print("Invalid Ip Address!")
else:
print("Invalid Ip Address!")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been trying to run this little port scanner-ish program for a while and I still don't know why it's giving me this error: [EDIT: I renamed the IP string into IPadd since it might have been confusing the two edited and now it says this error]
File "thing.py", line 63, in portScan
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
TypeError: 'int' object is not callable
this is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from socket import *
import urllib2
import sys
def portScan(target):
validate = 0
print("Simple Port Scanner v1.0")
print("Available port scans")
print("[1] TCP Connect")
print("[2] SYN")
print("[3] ACK")
print("[4] FIN")
#print("[5] XMAS")
print("\n COMMON PORTS: 20, 21, 23, 80")
getport = raw_input("What port will you scan?: ")
port = int(getport)
while validate != 1:
type = input("What kind of scan do you want to do?: ")
print "Selected", type
validate = 1
try:
IPadd = gethostbyname(target)
print(IP) #trace
except:
print("ERROR: Cannot resolve connection... Exiting program")
if type == 1:
tcpconn = socket(AF_INET, SOCK_STREAM)
tcpconn.settimeout(0.255)
#for port in range(20, 25):
isopen = tcpconn.connect_ex((IPadd, port))
if isopen == 0:
print ("TCP Connect: Port " + getport + " is Open")
else:
print ("TCP Connect: Port " + getport + " is Closed")
tcpconn.close()
elif type == 2:
print ("SYN")
synconn = socket(AF_INET, SOCK_STREAM)
synconn.settimeout(0.255)
elif type == 3:
print ("ACK")
elif type == 4:
dst_ip = IPadd
src_port = RandShort()
dst_port= port
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=10)
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
print "Open|Filtered"
elif(fin_scan_resp.haslayer(TCP)):
if(fin_scan_resp.getlayer(TCP).flags == 0x14):
print "Closed"
elif(fin_scan_resp.haslayer(ICMP)):
if(int(fin_scan_resp.getlayer(ICMP).type)==3 and int(fin_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
print "Filtered"
print ("FIN")
else:
print("Invalid input")
validate = 0
def getTarget():
target = raw_input("Enter target Host name/IP Address: ")
'''
#Validation of ip address still not working
#chk = socket(AF_INET, SOCK_STREAM)
try:
socket.inet_aton(target)
except socket.error:
print("IP address is invalid. QUITTING")
chk.close()
'''
return target
def main():
validate = 0
print("Launch which scan?")
print("[1] Simple Port Scanner v1.0")
print("[2] Service Fingerprinting v1.0")
print("[3] OS Fingerprinting v1.0")
print("[x] Exit")
while validate != 1:
firstMenu = raw_input("Choice: ")
if firstMenu == "1":
print("\n")
validate = 1
name = getTarget()
portScan(name)
elif firstMenu == "2":
print("yep")
validate = 1
elif firstMenu == "3":
print("this")
validate = 1
elif firstMenu == "x":
print("Closing...")
validate = 1
else:
print("Invalid choice")
main()
That part where there is supposed to be some error runs fine when I run that part on another .py file so I don't understand what's causing this and it's just frustrating
You are assigning a string to IP:
try:
IP = gethostbyname(target)
print(IP) #trace
but you are also trying to use the scapy IP() object:
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=10)
The string masks the object. Rename the string to ip (lowercase), everywhere in the portScan() function:
try:
ip = gethostbyname(target)
print(ip) #trace
# ...
#for port in range(20, 25):
isopen = tcpconn.connect_ex((ip, port))
# ...
elif type == 4:
dst_ip = ip
Instead of the rather ridiculous line:
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
use:
if fin_scan_resp is None:
although you really should not use type as a local variable as it masks the built-in function.