memory address generator in python - python
I need to bruteforce some of the address space using python. At the moment this is my code:
offsets = [
"\x00","\x01","\x02","\x03","\x04","\x05","\x06","\x07","\x08","\x09","\x0a","\x0b","\x0c","\x0d","\x0e","\x0f"
,"\x10","\x11","\x12","\x13","\x14","\x15","\x16","\x17","\x18","\x19","\x1a","\x1b","\x1c","\x1d","\x1e","\x1f"
,"\x20","\x21","\x22","\x23","\x24","\x25","\x26","\x27","\x28","\x29","\x2a","\x2b","\x2c","\x2d","\x2e","\x2f"
,"\x30","\x31","\x32","\x33","\x34","\x35","\x36","\x37","\x38","\x39","\x3a","\x3b","\x3c","\x3d","\x3e","\x3f"
,"\x40","\x41","\x42","\x43","\x44","\x45","\x46","\x47","\x48","\x49","\x4a","\x4b","\x4c","\x4d","\x4e","\x4f"
,"\x50","\x51","\x52","\x53","\x54","\x55","\x56","\x57","\x58","\x59","\x5a","\x5b","\x5c","\x5d","\x5e","\x5f"
,"\x60","\x61","\x62","\x63","\x64","\x65","\x66","\x67","\x68","\x69","\x6a","\x6b","\x6c","\x6d","\x6e","\x6f"
,"\x70","\x71","\x72","\x73","\x74","\x75","\x76","\x77","\x78","\x79","\x7a","\x7b","\x7c","\x7d","\x7e","\x7f"
,"\x80","\x81","\x82","\x83","\x84","\x85","\x86","\x87","\x88","\x89","\x8a","\x8b","\x8c","\x8d","\x8e","\x8f"
,"\x90","\x91","\x92","\x93","\x94","\x95","\x96","\x97","\x98","\x99","\x9a","\x9b","\x9c","\x9d","\x9e","\x9f"
,"\xa0","\xa1","\xa2","\xa3","\xa4","\xa5","\xa6","\xa7","\xa8","\xa9","\xaa","\xab","\xac","\xad","\xae","\xaf"
,"\xb0","\xb1","\xb2","\xb3","\xb4","\xb5","\xb6","\xb7","\xb8","\xb9","\xba","\xbb","\xbc","\xbd","\xbe","\xbf"
,"\xc0","\xc1","\xc2","\xc3","\xc4","\xc5","\xc6","\xc7","\xc8","\xc9","\xca","\xcb","\xcc","\xcd","\xce","\xcf"
,"\xd0","\xd1","\xd2","\xd3","\xd4","\xd5","\xd6","\xd7","\xd8","\xd9","\xda","\xdb","\xdc","\xdd","\xde","\xdf"
,"\xe0","\xe1","\xe2","\xe3","\xe4","\xe5","\xe6","\xe7","\xe8","\xe9","\xea","\xeb","\xec","\xed","\xee","\xef"
,"\xf0","\xf1","\xf2","\xf3","\xf4","\xf5","\xf6","\xf7","\xf8","\xf9","\xfa","\xfb","\xfc","\xfd","\xfe","\xff"]
for i in xrange(110, 256):
num = offsets[i]
address = "\xee" + num + "\xff\xbf"
print `address`
And the output last part of the output:
'\xee\xfa\xff\xbf'
'\xee\xfb\xff\xbf'
'\xee\xfc\xff\xbf'
'\xee\xfd\xff\xbf'
'\xee\xfe\xff\xbf'
'\xee\xff\xff\xbf'
My question is if it is possible to get rid of the "offsets" array, and do it in a much cleaner way?
Sure is, just iterate over the xrange and call chr() on the current item:
>>> for i in xrange(110, 256):
... print "\xee" + chr(i) + "\xff\xbf"
Notice that it'll print the actual characters. If you just want to print the values, you can use the backticks, however a more pythonic approach is to use repr():
>>> for i in xrange(110, 256):
... print(repr("\xee" + chr(i) + "\xff\xbf"))
...
-- SNIP --
'\xee\xfa\xff\xbf'
'\xee\xfb\xff\xbf'
'\xee\xfc\xff\xbf'
'\xee\xfd\xff\xbf'
'\xee\xfe\xff\xbf'
'\xee\xff\xff\xbf'
for i in xrange(110, 256):
address = "\xee" + "\\" + hex(i)[1:] + "\xff\xbf"
print `address`
You can generate the offsets array in a one-liner:
offsets = ["0x{:02x}".format(_) for _ in range(0x100)]
You could just do the math, and let struct construct the 4-byte sequence.
base = b'\xee\x00\xff\xbf' #assuming little-endian for the math coming up
struct.unpack('I',base)
Out[89]: (3221160174,)
#showing they're the same, no magic involved
int('ee',16) + int('ff',16)*(16**4) + int('bf',16)*(16**6)
Out[90]: 3221160174
#equivalent to bitshifting, if you prefer
int('ee',16) + (int('ff',16) << 16) + (int('bf',16) << 24)
Out[91]: 3221160174
So that gives
start = 3221160174
[struct.pack('I', start + (x<<8)) for x in range(256)]
Out[93]:
[b'\xee\x00\xff\xbf',
b'\xee\x01\xff\xbf',
b'\xee\x02\xff\xbf',
b'\xee\x03\xff\xbf',
b'\xee\x04\xff\xbf',
b'\xee\x05\xff\xbf',
b'\xee\x06\xff\xbf',
#snip...
b'\xee\xff\xff\xbf']
Related
Optimized summing beween ints and strs [duplicate]
This question already has answers here: How do I put a variable’s value inside a string (interpolate it into the string)? (9 answers) Closed 2 years ago. print("ax^2 + bx + c = d what is your values for them? ") a = int(input(">a = ")) b = int(input(">b = ")) c = int(input(">c = ")) d = int(input(">d = ")) given_parabola = str(a) + "x^2 + " + str(b) + "x + " + (str(c)) + " = " + str(d) Is there any other way that I can merge integer variables with strings?
The "best" approach really depends on what you're trying to do. 1. Concatenating lists with variable number of items (numbers and strings) If you simply want to form a string from numbers and strings, I would first create a generator with generator expression and then join the strings with the join() method. In [1]: a = [2, 'a', 3, 'x', 'foo', 8, 55] In [2]: g = (str(x) for x in a) In [3]: ' '.join(g) Out[3]: '2 a 3 x foo 8 55' Pluses Can be used to concatenate any amount of strings and numbers, which can be in any order Minuses Probably not the most speed optimized, if you know more about the variables you are going to concatenate 2. Literal String interpolation If you know what amount of numeric variables you want to concatenate with what strings, the problem is called string interpolation. In Python 3.6+ you can use so-called f-strings to form string using a string template and a fixed number of variables. For example: In [1]: a, b, c, d = 3, 2, 1, 5 In [2]: f"{a}x^2 + {b}x + {c} = {d}" Out[2]: '3x^2 + 2x + 1 = 5' Pluses Probably the most speed optimized way to create a string from a template. Minuses This is not a general approach to "sum"/concatenate any amount of strings and numbers. 3. Using sympy for expression generation Since your problem looks like being very specific: You want to create string from mathematical formula, you might want to look at sympy. Installation pip install sympy Simple example In [1]: from sympy import symbols, Eq, mathematica_code In [2]: x, a, b, c, d = symbols('x a b c d') In [3]: expr = Eq(a*(x**2) + b*x + c, d) In [4]: var_dict = dict(a=3, b=2, c=1, d=5) In [5]: expr_with_numbers = expr.subs(var_dict) In [6]: mathematica_code(expr_with_numbers).replace('==', '=') Out[6]: '3*x^2 + 2*x + 1 = 5' you can also solve for the expression easily: In [7]: solve(expr_with_numbers, x) Out[7]: [-1/3 + sqrt(13)/3, -sqrt(13)/3 - 1/3] and you can print any kind of equation. For example In [1]: from sympy import symbols, Eq, mathematica_code, sqrt, pretty, solve In [2]: expr = Eq(a*(x**2)/(sqrt(x-c)), d) In [3]: var_dict = dict(a=3, b=2, c=1, d=5) In [4]: expr_with_numbers = expr.subs(var_dict) In [5]: print(pretty(expr_with_numbers, use_unicode=False)) 2 3*x --------- = 5 _______ \/ x - 1 Pros Useful, if you want to create complex mathematical expressions Can also output pretty multiline output or even LaTeX output. Can be useful if you want to actually solve the equation, too Cons Not speed-optimized for simple string formation.
You can avoid concatenating multiple strings using the format string python proposed. Using Format strings vs concatenation to do a list of more performant to less performant f-string as f"{a}x^2 + {b}x + {c} = {d}" "%sx^2 + %sx + %s = %s" % (a,b,c,d) "{}x^2 + {}x + {} = {}".format(a,b,c,d)
Might I suggest string interpolation? given_parabola = "%sx^2 + %sx + %s = %s" % (a, b, c, d) Or given_parabola = f"{a}x^2 + {b}x + {c} = {d}"
Yes, hopefully, this is what you mean: # This way the integer 10 will convert to a string automatically. Works in Print as well! x = 10 y = "lemons" z = "In the basket are %s %s" % (x, y) print(z) Output: In the basket are 10 lemons
Concentrate two int to one decimal
What's the fastest way to concentrate two int into one decimal. eg. a=100 b=10 to get = 100.10 Thanks.
Convert them into strings and then add them and again convert them c = float(str(a) + '.' + str(b)) Output: 100.10
Assuming python >= 3.6: a = 100 b = 10 # if you want a string c = f'{a}.{b}' # if you want a float d = float(f'{a}.{b}') It should be a little bit faster than string concatenation, see here.
Play with string concatenation y = float(str(a) + "." + str(b))
If for some reason you don't want to use string concatenation you can do the following: from math import log10, floor, pow c = a + (b/(pow(10, floor(log10(b) + 1)))) Not sure if it is any more efficient. You can also import from numpy or import all of either numpy or math: import numpy c = a + (b / (numpy.power(10, numpy.floor(numpy.log10(b) + 1))))
Find length of a string that includes its own length?
I want to get the length of a string including a part of the string that represents its own length without padding or using structs or anything like that that forces fixed lengths. So for example I want to be able to take this string as input: "A string|" And return this: "A string|11"
On the basis of the OP tolerating such an approach (and to provide an implementation technique for the eventual python answer), here's a solution in Java. final String s = "A String|"; int n = s.length(); // `length()` returns the length of the string. String t; // the result do { t = s + n; // append the stringified n to the original string if (n == t.length()){ return t; // string length no longer changing; we're good. } n = t.length(); // n must hold the total length } while (true); // round again The problem of, course, is that in appending n, the string length changes. But luckily, the length only ever increases or stays the same. So it will converge very quickly: due to the logarithmic nature of the length of n. In this particular case, the attempted values of n are 9, 10, and 11. And that's a pernicious case.
A simple solution is : def addlength(string): n1=len(string) n2=len(str(n1))+n1 n2 += len(str(n2))-len(str(n1)) # a carry can arise return string+str(n2) Since a possible carry will increase the length by at most one unit. Examples : In [2]: addlength('a'*8) Out[2]: 'aaaaaaaa9' In [3]: addlength('a'*9) Out[3]: 'aaaaaaaaa11' In [4]: addlength('a'*99) Out[4]: 'aaaaa...aaa102' In [5]: addlength('a'*999) Out[5]: 'aaaa...aaa1003'
Here is a simple python port of Bathsheba's answer : def str_len(s): n = len(s) t = '' while True: t = s + str(n) if n == len(t): return t n = len(t) This is a much more clever and simple way than anything I was thinking of trying! Suppose you had s = 'abcdefgh|, On the first pass through, t = 'abcdefgh|9 Since n != len(t) ( which is now 10 ) it goes through again : t = 'abcdefgh|' + str(n) and str(n)='10' so you have abcdefgh|10 which is still not quite right! Now n=len(t) which is finally n=11 you get it right then. Pretty clever solution!
It is a tricky one, but I think I've figured it out. Done in a hurry in Python 2.7, please fully test - this should handle strings up to 998 characters: import sys orig = sys.argv[1] origLen = len(orig) if (origLen >= 98): extra = str(origLen + 3) elif (origLen >= 8): extra = str(origLen + 2) else: extra = str(origLen + 1) final = orig + extra print final Results of very brief testing C:\Users\PH\Desktop>python test.py "tiny|" tiny|6 C:\Users\PH\Desktop>python test.py "myString|" myString|11 C:\Users\PH\Desktop>python test.py "myStringWith98Characters.........................................................................|" myStringWith98Characters.........................................................................|101
Just find the length of the string. Then iterate through each value of the number of digits the length of the resulting string can possibly have. While iterating, check if the sum of the number of digits to be appended and the initial string length is equal to the length of the resulting string. def get_length(s): s = s + "|" result = "" len_s = len(s) i = 1 while True: candidate = len_s + i if len(str(candidate)) == i: result = s + str(len_s + i) break i += 1
This code gives the result. I used a few var, but at the end it shows the output you want: def len_s(s): s = s + '|' b = len(s) z = s + str(b) length = len(z) new_s = s + str(length) new_len = len(new_s) return s + str(new_len) s = "A string" print len_s(s)
Here's a direct equation for this (so it's not necessary to construct the string). If s is the string, then the length of the string including the length of the appended length will be: L1 = len(s) + 1 + int(log10(len(s) + 1 + int(log10(len(s))))) The idea here is that a direct calculation is only problematic when the appended length will push the length past a power of ten; that is, at 9, 98, 99, 997, 998, 999, 9996, etc. To work this through, 1 + int(log10(len(s))) is the number of digits in the length of s. If we add that to len(s), then 9->10, 98->100, 99->101, etc, but still 8->9, 97->99, etc, so we can push past the power of ten exactly as needed. That is, adding this produces a number with the correct number of digits after the addition. Then do the log again to find the length of that number and that's the answer. To test this: from math import log10 def find_length(s): L1 = len(s) + 1 + int(log10(len(s) + 1 + int(log10(len(s))))) return L1 # test, just looking at lengths around 10**n for i in range(9): for j in range(30): L = abs(10**i - j + 10) + 1 s = "a"*L x0 = find_length(s) new0 = s+`x0` if len(new0)!=x0: print "error", len(s), x0, log10(len(s)), log10(x0)
convert cidr to subnet mask in python
I have a python dictionary that I've created, this dictionary contains a list of subnets in the following format: x.x.x.x/24 y.y.y,y/25 z.z.z.z/26 a.a.a.a/27 etc... I would like to take the items in this dictionary, parse it, then spit out the results in the following format: x.x.x.x 255.255.255.0 y.y.y.y 255.255.255.128 x.x.x.x 255.255.255.192 a.a.a.a 255.255.255.224 I don't have much on this as of right now because I can't find a lot on this topic on the web, not anything that can be in a quick and concise way that is. Thoughts?
Code: import socket import struct def cidr_to_netmask(cidr): network, net_bits = cidr.split('/') host_bits = 32 - int(net_bits) netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits))) return network, netmask Usage: >>> cidr_to_netmask('10.10.1.32/27') ('10.10.1.32', '255.255.255.224') >>> cidr_to_netmask('208.128.0.0/11') ('208.128.0.0', '255.224.0.0') >>> cidr_to_netmask('208.130.28.0/22') ('208.130.28.0', '255.255.252.0')
I thought I'd throw in my own solution, since I was going for a little bit more readability in it than the other answers shown. def cidr_to_netmask(cidr): cidr = int(cidr) mask = (0xffffffff >> (32 - cidr)) << (32 - cidr) return (str( (0xff000000 & mask) >> 24) + '.' + str( (0x00ff0000 & mask) >> 16) + '.' + str( (0x0000ff00 & mask) >> 8) + '.' + str( (0x000000ff & mask))) It's now easier to see what's going on, and that is: Get the numeric mask by padding the front with 1s and having the cidr make up the rest For each bit, apply the mask Concatenate all the bits together, separated by periods This is very procedural and does not use any libraries.
Try this solution: Python3 from ipaddress import IPv4Network networks = {'n1':'10.1.0.0/21','n2':'10.2.0.0/22','n3':'10.3.0.0/23','n4':'10.4.0.0/24'} for x,y in enumerate(networks): print(IPv4Network(networks[y]).network_address, IPv4Network(networks[y]).netmask) Result: 10.1.0.0 255.255.248.0 10.2.0.0 255.255.252.0 10.3.0.0 255.255.254.0 10.4.0.0 255.255.255.0 Python2 from netaddr import IPNetwork networks = {'n1':'10.1.0.0/21','n2':'10.2.0.0/22','n3':'10.3.0.0/23','n4':'10.4.0.0/24'} for x,y in enumerate(networks): print(str(IPNetwork(networks[y]).network), str(IPNetwork(networks[y]).netmask)) Result: ('10.1.0.0', '255.255.248.0') ('10.2.0.0', '255.255.252.0') ('10.3.0.0', '255.255.254.0') ('10.4.0.0', '255.255.255.0')
Try this lsIP = [] ans = 0 CIDR = 32 IP = [1] * CIDR for i in range(len(IP)): iIdx = i % 8 if iIdx == 0: if i >= 8: lsIP.append(ans) ans = 0 ans += pow(2, 7 - iIdx) lsIP.append(ans) [lsIP.append(0) for i in range(4 - len(lsIP))] print lsIP
Python's equivalent of perl vec() function
I am new to Python. In Perl, to set specific bits to a scalar variable(integer), I can use vec() as below. #!/usr/bin/perl -w $vec = ''; vec($vec, 3, 4) = 1; # bits 0 to 3 vec($vec, 7, 4) = 10; # bits 4 to 7 vec($vec, 11, 4) = 3; # bits 8 to 11 vec($vec, 15, 4) = 15; # bits 12 to 15 print("vec() Has a created a string of nybbles, in hex: ", unpack("h*", $vec), "\n"); Output: vec() Has a created a string of nybbles, in hex: 0001000a0003000f I was wondering how to achieve the same in Python, without having to write bit manipulation code and using struct.pack manually?
Not sure how the vec function works in pearl (haven't worked with the vec function). However, according to the output you have mentioned, the following code in python works fine. I do not see the significance of the second argument. To call the vec function this way: vec(value, size). Every time you do so, the output string will be concatenated to the global final_str variable. final_vec = '' def vec(value, size): global final_vec prefix = '' str_hex = str(hex(value)).replace('0x','') str_hex_size = len(str_hex) for i in range (0, size - str_hex_size): prefix = prefix + '0' str_hex = prefix + str_hex final_vec = final_vec + str_hex return 0 vec(1, 4) vec(10, 4) vec(3, 4) vec(15, 4) print(final_vec)
If you really want to create a hex string from nibbles, you could solve it this way nibbles = [1,10,3,15] hex = '0x' + "".join([ "%04x" % x for x in nibbles])