I'm trying to extract usernames from a config file into a list and compare the usernames against another secure list of usernames. The config file looks like this this:
username Hilton privilege 15 password 0 $xxxxxxxxxxxxx
username gooduser password 0 $xxxxxxxxxxxxx
username jason secret 5 $xxxxxxxxxxxxx
The problem with the output is not a single list! (each user is in a list)
['Hilton']
['gooduser']
['jason']
I am reading the file into one single list. Then located the 'username' position and used enumerate to find the position
the_list = []
with open('config_file.txt', "r") as f:
the_list = f.read().split()
print(the_list)
find_keyword = 'username'
secure_users = ['jason','test','admin']
for i,x in enumerate(the_list): # search in the list
if x=='username': # for this keyword 'username'
pos = i + 1 # position of every username
print(the_list[pos].split()) # print all users.
#Compare secure_users[] vs the_list[] here
the expected output is a list like >> ['Hilton','gooduser','jason']
So that I can compare it against the secure_users list
Made some modification to your code,
the_list = []
with open('config_file.txt', "r") as f:
the_list = f.read().split()
print(the_list)
find_keyword = 'username'
secure_users = ['jason','test','admin']
users_list = []
for i,x in enumerate(the_list): # search in the list
if x=='username': # for this keyword 'username'
pos = i + 1 # position of every username
users_list.append(the_list[pos].split()[0]) # print all users
print(users_list)
Output:
['username', 'Hilton', 'privilege', '15', 'password', '0', '$xxxxxxxxxxxxx', 'username', 'gooduser', 'password', '0', '$xxxxxxxxxxxxx', 'username', 'jason', 'secret', '5', '$xxxxxxxxxxxxx']
['Hilton', 'gooduser', 'jason']
Another solution:(Best way)
with open('config_file.txt', 'r') as f:
data = f.read().split()
user_names = [data[i+1] for i,line in enumerate(data) if 'username' in line ]
Output:
['Hilton', 'gooduser', 'jason']