Creating nested dictionaries using for and if loops - python

I am working on creating nested dictionaries. Can someone please help?
for key,values in hostwise.iteritems():
values.sort(key=lambda x: x.execution_time)
for plugin in values:
plugin_wise = {}
if plugin.name not in plugin_wise.keys():
plugin_wise[plugin.name] = {}
if plugin.status == 'Submitplugin':
plugin_wise[plugin.name]['Submitplugin'] = plugin.execution_time
elif plugin.status == 'Pluginsucceeded':
plugin_wise[plugin.name]['Pluginsucceeded'] = plugin.execution_time
else:
if plugin.status == 'Submitplugin':
plugin_wise.update({plugin.name: {'Submitplugin': plugin.execution_time}})
#plugin_wise[plugin.name]['Submitplugin'] = plugin.execution_time
elif plugin.status == 'Pluginsucceeded':
plugin_wise.update({plugin.name: {'Pluginsucceeded': plugin.execution_time}})
#plugin_wise[plugin.name]['Pluginsucceeded'] = plugin.execution_time
{‘UpgradeOptional’: {‘Pluginsucceeded’: ‘2020-06-06T12:00:09’}}
{‘UpgradeOptional’: {‘Submitplugin’: ‘2020-06-06T12:00:03’}}
For example. the above output is not what I am expecting...I want the way below. Any ideas please?
{‘UpgradeOptional’:
{‘Pluginsucceeded’: ‘2020-06-06T12:00:09’,‘Submitplugin’: ‘2020-06-06T12:00:03’}}

Try this.
plugin_wise[plugin.name].update({'Submitplugin': plugin.execution_time})
plugin_wise[plugin.name].update({'Pluginsucceeded': plugin.execution_time})

I think the part that you have commented out should work.

Related

PicoCTF General Skills PW Crack Level4

I'm working on the PW Crack Level4 in the PicoCTF General Skills section. I'm very new to python and CTF's in general. The challenge is to find the right pw from the included list of 100 possibles. I could have, by now, simply entered each one, lol, but that's not the point I think. So I am trying to modify the code to iterate through the list of pw's and pass each one to the part of the code that checks it.
That's where I'm stuck. The for loop seems to run through the list without passing each pw to the part of the code that should check it... I feel like the answer is on the tip of my tongue. But I'm too new to see it.
Here's my code
import hashlib
### THIS FUNCTION WILL NOT HELP YOU FIND THE FLAG --LT ########################
def str_xor(secret, key):
#extend key to secret length
new_key = key
i = 0
while len(new_key) < len(secret):
new_key = new_key + key[i]
i = (i + 1) % len(key)
return "".join([chr(ord(secret_c) ^ ord(new_key_c)) for (secret_c,new_key_c) in zip(secret,new_key)])
###############################################################################
flag_enc = open('level4.flag.txt.enc', 'rb').read()
correct_pw_hash = open('level4.hash.bin', 'rb').read()
def hash_pw(pw_str):
pw_bytes = bytearray()
pw_bytes.extend(pw_str.encode())
m = hashlib.md5()
m.update(pw_bytes)
return m.digest()
pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]
def level_4_pw_check():
for x in pos_pw_list: # for loop to iterate through the pos_pw_list
user_pw = input(x)
# print(user_pw) # printing user_pw just to make sure the loop is working - it is
user_pw_hash = hash_pw(user_pw)
if( user_pw_hash == correct_pw_hash ):
print("Welcome back... your flag, user:")
decryption = str_xor(flag_enc.decode(), user_pw)
print(decryption)
return
print("That password is incorrect")
level_4_pw_check()
# The strings below are 100 possibilities for the correct password.
# (Only 1 is correct)
pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]
I'm not too experienced myself, but I think I know what you're doing wrong. I'll try to give you a small tip that will probably help you solve the problem without giving you the answer full out.
I think where you're going wrong is that you're still asking for input. Since you're comparing a list of possible passwords to the actual possible password, you don't need to ask for input anywhere in your code.
I hope this helps you out!
SO I stumbled upon the answer.... it appears to be a indent error (sorry, I don't fully grasp python). But once I properly indented my modified code I got the answer!
def level_4_pw_check():
for x in pos_pw_list: # for loop to iterate through the pos_pw_list
user_pw = x
user_pw_hash = hash_pw(user_pw)
print(user_pw) # printing user_pw just to make sure the loop is working - it is
if( user_pw_hash == correct_pw_hash ):
print("Welcome back... your flag, user:")
decryption = str_xor(flag_enc.decode(), user_pw)
#decryption = xor(flag_enc.decode(), user_pw)
print(decryption)
return
print("That password is incorrect")

Parsing Security Matrix Spreadsheet - NoneType is not Iterable

Trying to Nest no's and yes's with their respective applications and services.
That way when a request comes in for a specific zone to zone sequence, a check can be run against this logic to verify accepted requests.
I have tried calling Decision_List[Zone_Name][yes_no].update and i tried ,append when it was a list type and not a dict but there is no update method ?
Base_Sheet = range(5, sh.ncols)
Column_Rows = range(1, sh.nrows)
for colnum in Base_Sheet:
Zone_Name = sh.col_values(colnum)[0]
Zone_App_Header = {sh.col_values(4)[0]:{}}
Zone_Svc_Header = {sh.col_values(3)[0]:{}}
Zone_Proto_Header = {sh.col_values(2)[0]:{}}
Zone_DestPort_Header = {sh.col_values(1)[0]: {}}
Zone_SrcPort_Header = {sh.col_values(0)[0]: {}}
Decision_List = {Zone_Name:{}}
for rows in Column_Rows:
app_object = sh.col_values(4)[rows]
svc_object = sh.col_values(3)[rows]
proto_object = sh.col_values(3)[rows]
dst_object = sh.col_values(2)[rows]
src_object = sh.col_values(1)[rows]
yes_no = sh.col_values(colnum)[rows]
if yes_no not in Decision_List[Zone_Name]:
Decision_List[Zone_Name][yes_no] = [app_object]
else:
Decision_List[Zone_Name]=[yes_no].append(app_object)
I would like it present info as follows
Decision_List{Zone_Name:{yes:[ssh, ssl, soap], no:
[web-browsing,facebook]}}
I would still like to know why i couldnt call the append method on that specific yes_no key whos value was a list.
But in the mean time, i made a work around of sorts. I created a set as the key and gave the yes_no as the value. this will allow me to pair many no type values with the keys being a set of the application, port, service, etc.. and then i can search for yes values and create additional dicts out of them for logic.
Any better ideas out there i am all ears.
for rownum in range(0, sh.nrows):
#row_val is all the values in the row of cell.index[rownum] as determined by rownum
row_val = sh.row_values(rownum)
col_val = sh.col_values(rownum)
print rownum, col_val[0], col_val[1: CoR]
header.append({col_val[0]: col_val[1: CoR]})
print header[0]['Start Port']
dec_tree = {}
count = 1
Base_Sheet = range(5, sh.ncols)
Column_Rows = range(1, sh.nrows)
for colnum in Base_Sheet:
Zone_Name = sh.col_values(colnum)[0]
Zone_App_Header = {sh.col_values(4)[0]:{}}
Zone_Svc_Header = {sh.col_values(3)[0]:{}}
Zone_Proto_Header = {sh.col_values(2)[0]:{}}
Zone_DestPort_Header = {sh.col_values(1)[0]: {}}
Zone_SrcPort_Header = {sh.col_values(0)[0]: {}}
Decision_List = {Zone_Name:{}}
for rows in Column_Rows:
app_object = sh.col_values(4)[rows]
svc_object = sh.col_values(3)[rows]
proto_object = sh.col_values(3)[rows]
dst_object = sh.col_values(2)[rows]
src_object = sh.col_values(1)[rows]
yes_no = sh.col_values(colnum)[rows]
for rule_name in Decision_List.iterkeys():
Decision_List[Zone_Name][(app_object, svc_object, proto_object)]= yes_no
Thanks again.
I think still a better way is to use collections.defaultdict
In this manner it will ensure that i am able to append to the specific yes_no as i had originally intended.
for colnum in Base_Sheet:
Zone_Name = sh.col_values(colnum)[0]
Zone_App_Header = {sh.col_values(4)[0]:{}}
Zone_Svc_Header = {sh.col_values(3)[0]:{}}
Zone_Proto_Header = {sh.col_values(2)[0]:{}}
Zone_DestPort_Header = {sh.col_values(1)[0]: {}}
Zone_SrcPort_Header = {sh.col_values(0)[0]: {}}
Decision_List = {Zone_Name:defaultdict(list)}
for rows in Column_Rows:
app_object = sh.col_values(4)[rows]
svc_object = sh.col_values(3)[rows]
proto_object = sh.col_values(2)[rows]
dst_object = sh.col_values(1)[rows]
src_object = sh.col_values(0)[rows]
yes_no = sh.col_values(colnum)[rows]
if yes_no not in Decision_List[Zone_Name]:
Decision_List[Zone_Name][yes_no]= [app_object, svc_object, proto_object, dst_object, src_object]
else:
Decision_List[Zone_Name][yes_no].append([(app_object, svc_object, proto_object,dst_object, src_object)])
This allows me to then set the values as a set and append them as needed

Comparing and delete api data

I have a django project that takes in some data from another app of ours. The data looks like this:
{u'   updated':   u'2017-04-03T22:30:53.760278   Z',
   u'added':   u'2017-04-03T22:30:53.760197   Z',
   u'name':u'Jean Lamb,
   1942-   ', u'   authority':{  
      u'id':2,
      u'added_by':2,
      u'name':u'VIAF'
   },
   u'local_identifier':u'85363862',
   u'concept_type':{  
      u'id':5,
      u'identifier':      u'viaf:personal',
      u'name':u'',
      u'description':None
   },
   u'identifier':   u'http://viaf.org/viaf/85363862',
   u'identities':[  
      {  
         u'part_of':{  
            u'id':1,
            u'added_by':2,
            u'name':            u'builtin:Conceptpower'
         },
         u'added':         u'2017-04-03T22:33:20.476637         Z',
         u'name':u'Jean Lamb',
         u'confidence':1.0,
         u'updated':         u'2017-04-03T22:33:20.476699         Z',
         u'concepts':[  
            u'http://viaf.org/viaf/85363862',
            u'http://www.digitalhps.org/concepts/CONpeSHC70qxNC0'
         ],
         u'id':208,
         u'added_by':{  
            u'username':u'erickjones',
            u'email':u'erick.jones#example.com'
         }
      },
      {  
         u'part_of':{  
            u'id':1,
            u'added_by':2,
            u'name':            u'builtin:Conceptpower'
         },
         u'added':         u'2017-04-03T22:35:02.546054         Z',
         u'name':u'Jean Lamb',
         u'confidence':1.0,
         u'updated':         u'2017-04-03T22:35:02.546116         Z',
         u'concepts':[  
            u'http://viaf.org/viaf/85363862',
            u'http://www.digitalhps.org/concepts/CONpeSHC70qxNC0'
         ],
         u'id':209,
         u'added_by':{  
            u'username':u'erickjones',
            u'email':u'erick.jones#example.com'
         }
      },
Right now I have a function that goes through and compares the concepts in in the identities. What I want to do is delete the duplicate concepts. The nesting of the dictionaries and lists are throwing me off. What I have been trying is:
del results[i]["identities"][z]["concepts"]
Any ideas as to why this does not work?
Here is my loop incase anyone is interested:
while (i != di):
test = results[i]["identities"]
if results[i]["identities"]:
z = 0
while (z != len(results[i]["identities"])):
con1 = results[i]["identities"][z]["concepts"]
print "this is con1: %s", con1
if z != len(results[i]["identities"]):
z = z + 1
else:
break
if z != len(results[i]["identities"]):
con2 = results[i]["identities"][z]["concepts"]
print "this is con2: %s", con2
if set(con1) == set(con2):
del results[i]["identities"][z]["concepts"]
else:
break
i = i + 1
In this line,
if set(con1) and set(con2):
Do you intend to check if con1 and con2 are the same set? Shouldn't you use == operator?

How can I group RadioMenuItem? (PyGtk)

That's the question.
I'm making an indicator for Ubuntu, all works fine, but... When I try to set two "RadioMenuItem" they are totally independent. I can check both.
The items:
item_first = gtk.RadioMenuItem('First Radio')
item_first.connect('activate', first_radio)
menu.append(item_first)
item_second = gtk.RadioMenuItem('Second Radio')
item_second.connect('activate', second_radio)
menu.append(item_second)
Should I use a container or something like this? Please, help me.
Try this,
self.menu = Gtk.Menu()
self.menu_items = list("First Radio","Second Radio")
group = []
for i in range(1,5):
menu_item = Gtk.RadioMenuItem.new_with_label(group, str(i))
group = menu_item.get_group()
self.menu_items[i] = menu_item
self.menu.append(menu_item)
menu_item.connect("activate", self.on_menu_select, i)
menu_item.show()
self.menu_items[2].set_active(True)
That's an old one, I know. However the solution is as following:
item_first = gtk.RadioMenuItem('First Radio')
item_first.connect('activate', first_radio)
menu.append(item_first)
item_second = gtk.RadioMenuItem('Second Radio', group=item_first) # <-- note group
item_second.connect('activate', second_radio)
menu.append(item_second)

How to resolve AttributeError: 'list' object has no attribute 'next' in Python

I am trying to read a file where the odd lines are department numbers, and even ones are sales totals. I need to be able to read a line and append it to a variable to be used later.
def main():
with open('P2data.txt') as x:
data = x.readlines()
dept = (data)[::2]
sales = (data)[1::2]
if dept == '1':
total = sales.next()
total.append(total1)
elif dept == '2':
total = sales.next()
total.append(total2)
else:
total = sales.next()
total.append(total3)
print('Dept 1:', total1)
print('Dept 2:', total2)
print('Dept 3:', total3)
main()
Your code is going in the wrong direction. You also are doing things like checking an entire data structure against what should be compared to one of that structure's elements, and mixing up the syntax for appending to a list. Simply loop over the data structures you create and add to a dictionary:
def main():
with open('P2data.txt') as x:
data = [line.strip() for line in x]
dept = data[::2]
sales = data[1::2]
totals = {'1':0, '2':0, '3':0}
for dep,sale in zip(dept, sales):
totals[dep] += float(sale)
for dep in sorted(totals):
print('Dept {}: {}'.format(dep, totals[dep]))
main()

Categories

Resources