IP Subnet from user via input/raw_input in python? - python

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

Related

why WinError 10053 occur optionally?

I'm creating a program that activates the timer after receiving the time, ID, and password through the socket.
and when i input "minute" value, I have winError 10053.
I can't understand, why name and hour can be sent, not minute?
this is client code
declStart = input("if you want to login, enter "login" ") # GUI 생기면 버튼으로 대체
if declStart=="login":
while True:
cname = str(input('enter name :'))
if ' ' in cname:
print('Spaces are not allowed.')
continue
client_sock.send(cname.encode())
is_possible_name = client_sock.recv(1024).decode()
if is_possible_name == 'yes':
client_sock.send('!enter'.encode())
goaltime_hour = int(input('goaltime(hour): '))
client_sock.send((str(goaltime_hour)).encode())
goaltime_min = int(input('goaltime(min): '))
client_sock.send((str(goaltime_min)).encode())
goaltime_sec = int(input('goaltime(sec): '))
client_sock.send((str(goaltime_sec)).encode())
elif is_possible_name == 'overlapped':
print('[SYSTEM] The name already exists.')
elif len(client_sock.recv(1024).decode()) == 0:
print('[SYSTEM] The server has been disconnected.')
client_sock.close()
os._exit(1)
while True:
if goaltime_hour <= 0 and goaltime_min <= 0:
print('Please enter the time')
continue
elif (str(type(goaltime_hour)) != "<class 'int'>") or (str(type(goaltime_min)) != "<class 'int'>"):
print("Please enter the int")
continue
else: break
pw = input("enter password")
client_sock.send((str(pw)).encode())
print("login completed. \n ")
break
server
class timeuser:
name: str=None
goaltime_hour: int=None
goaltime_min: int=None
goaltime_sec: int=None
currsecond: int=0
while True:
count = count + 1
conn, addr = server_sock.accept()
client=timeuser()
while True:
username = conn.recv(1024).decode()
if not username in member_name_list:
conn.send('yes'.encode())
break
else:
conn.send('overlapped'.encode())
client.name = username
clientHour = int(conn.recv(1024).decode()) # 시간수신
client.goaltime_hour = clientHour
clientMin = int(conn.recv(1024).decode()) # 분수신
client.goaltime_min = clientMin
clientsec = int(conn.recv(1024).decode()) # 초수신
client.goaltime_sec = clientsec
you can see entire code here :
https://github.com/whataLIN/Pysoc_myStudyTimer
I deleted All other data transmission and reception processes except hour and name, Then it worked fine.
I want to get other data with no error..
Error 10053 is "Connection reset" (WSAECONNRESET). It means the server closed its socket.
That is probably because the client sends !enter and the server tries to read it as a number and crashes. If you looked at the terminal where the server was running, you would see it crash.

validating input value but unable to try & except for other inputs too

i am trying to validate every input value but stuck here where if user put wrong value then my function stop taking other input & ask him to correct the error.
import re
import os.path
from csv import DictWriter
service ={}
class App:
def __init__(self):
pass
def services(self):
Problem is here
name=input("Enter Name: ")
name_r = re.match('^[a-zA-Z]{3,20}$',name)
if name_r:
print("true")
else:
print("Wrong Value Entered. Please Enter Correct Name")
i wanna use try & except block but exactly don't know how to use in this case.
if i put validated value in except block then rest of the input will also have have their own except block (am confused guide me) also the main problem, is there any short way to do this because if i validate each line like this so it will take so much time.
phone=input("Enter PTCL: ")
email=input("Enter Email: ")
mobile=input("Enter Mobile: ")
address=input("Enter Address: ")
service_type=input("Enter Problem Type: ")
date_time=input("Enter Date & Time: ")
msg=input("Enter Message: ")
Below Code is fine
#getting input values
service['name'] = name_r
service['ptcl'] = phone
service['mobile'] = mobile
service['date_time'] = date_time
service['service_type'] = service_type
service['address'] = address
service['msg'] = msg
service['email'] = email
file_exists = os.path.isfile(r"sevices.csv")
with open(r"sevices.csv",'a',newline='') as for_write:
writing_data = DictWriter(for_write,delimiter=',',fieldnames=["Name","Email","PTCL","Mobile","Service Type","Date & Time","Address","Message"])
if not file_exists:
writing_data.writeheader()
writing_data.writerow({
'Name': service['name'],
'Email':service['email'],
'PTCL':service['ptcl'],
'Mobile':service['mobile'],
'Service Type':service['service_type'],
'Date & Time':service['date_time'],
'Address':service['address'],
'Message':service['msg']
})
o1= App()
o1.services()
The easiest way to accomplish what you want is to create a while loop that exits on an accepted input.
while True:
name=input("Enter Name: ")
name_r = re.match('^[a-zA-Z]{3,20}$',name)
if name_r:
break
else:
print("Wrong Value Entered. Please Enter Correct Name")

Password - Login not working Python

I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue

Simple python assignment

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!")

Problems with text file appending in python

I am having python problems.
I have made a program to ask a user for their email address and it appends it to a text file, after doing some checks, everything is working fine, but it ends up with nothing in the text file, even though no errors show up.
My code is:
def main():
print("Hello and welcome to customer email program!")
count=0
while count < 1:
email=str(input("Email Address: "))
if "#" in email:
if email.islower == True:
count=2
with open("emails.txt", "a") as myfile:
myfile.write(email)
print("File added to databse")
else:
email=email.lower()
count=2
with open("emails.txt", "a") as myfile:
myfile.write(email)
else:
print("That is not an email address, please try again.")
main()
Any help would be greatly appreciated.
I think you should open the file and then CLOSE the file after you append to it:
def main() :
print("Hello and welcome to customer email program!")
done = False
while not done :
email = str(input("What's your email address? "))
if "#" in email :
if not email.lower() == email :
email = email.lower()
done = True
f = open("emails.txt" "a")
f.write(email)
f.close()
else :
print("Please type in a valid email address, "+email+" isn't a valid email address")
main()
Does this fit your needs?

Categories

Resources