I'm new to Python (and stackoverflow :D) and in school we got the task to create (normal users and with sudo rights) and delete users on a linux system (Ubuntu 18.04 in my case). I'm using Pycharm for coding and Python 3.7 as interpreter. I have already searched for an answer but couldn't find one. So I'm not sure what exactly causes this problems so sorry for the may confusing title. I'll try to explain it as good as possible.
I want to ask a question if the user wants to create or delete an user..
def useradministration():
parameters.question_user ##input("User add (a) or delete (d)?: ").strip()
...followed by:
#a for adding an user
if parameters.question_user == 'a':
def usercreate():
parameters.question_role ##input("Role for the user: administrator (a) or normal user (n)? ").strip()
# n for normal user - creating via useradd
if parameters.question_role == 'n':
.....
# a for administrator - same as a but with usermod for sudo
elif parameters.question_role == 'a':
.....
#error if its neither n or a
else:
print("Error: wrong specification for role.")
usercreate()
#d for deleting an user
elif parameters.question_user == 'd':
def userdelete():
........
#error if its neither a or d
else:
print("Error: wrong specification for user.")
First question. An example output:
User add (a) or delete (d)?: r
Role for the user: administrator (a) or normal user (n)? u
Select username:g
Error: wrong specification for user.
It gives the right output with "Error: wrong specification for user." - but why is it still going through all the questions if the first if isn't true? Is it a problem with my script or is the input comparison not working, or something else?
User add (a) or delete (d)?: r
Error: wrong specification for user.
That would be the output I've hoped for.
Another question for the deleting part. We have to log everything into a file. My userdelete looks like this:
def userdelete():
parameters.username ##username = input("Select username:")
#try to delete if it exists, print and log it
try:
os.system("sudo userdel -r " + parameters.username)
print("User " + parameters.username + " deleted.")
logging.info("User " + parameters.username + " deleted.")
#exception for when user doesn't exist, just printing and logging it
except OSError:
print("User " + parameters.username + " doesnt exist.")
logging.critical("User " + parameters.username + " doesnt exist.")
pass
userdelete()
An example output:
User add (a) or delete (d)?: d
Role for the user: administrator (a) or normal user (n)? o
Select username:abc
User abc deleted.
userdel: user 'abc' does not exist
The script is actually deleting the user if it exists. But why is it asking the Role question and why isn't it using the except statement if the user doesn't exist (because abc doesn't exist)? Am I using it wrong in this case?
I hope someone can help me.
Thanks.
Aucun commentaire:
Enregistrer un commentaire