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
Try the following:
usernames = []
secure_users = ['jason','test','admin']
with open('config_file.txt', "r") as f:
for line in f:
usernames.append(line.split()[1])
print([user for user in secure_users if user in usernames])
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']
Using Regex.
Ex:
import re
find_keyword = 'username'
the_list = []
with open('config_file.txt') as f:
for line in f:
m = re.search(r"\b{}\b \b(.*?)\b ".format(find_keyword), line.strip()) #Search for key and word after that.
if m:
the_list.append(m.group(1))
print(the_list)# ->['Hilton', 'gooduser', 'jason']
add a list named diff in your code like :
diff = []
then Just add below 2 lines after your code line print(the_list[pos].split()):
if the_list[pos] not in secure_users:
diff.append(the_list[pos])
then print diff to see the single list:
print(diff)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.