converting IP string to hex for dpkt.IP - python

I want to learn packet decoder processing using dpkt. On the site, I saw the following example code:
>>> from dpkt.ip import IP
>>> ip = IP(src='\x01\x02\x03\x04', dst='\x05\x06\x07\x08', p=1)
>>> ...
How do I convert an IP String like '1.2.3.4' to '\x01\x02\x03\x04'?

Use socket.inet_aton:
>>> import socket
>>> socket.inet_aton('1.2.3.4')
'\x01\x02\x03\x04'
To get the dotted decimal back, use socket.inet_ntoa:
>>> socket.inet_ntoa('\x01\x02\x03\x04')
'1.2.3.4'
UPDATE
In Python 3.3+, ipaddress.IPv4Address is another option.
>>> import ipaddress
>>> ipaddress.IPv4Address('1.2.3.4').packed
b'\x01\x02\x03\x04'
>>> ipaddress.IPv4Address(b'\x01\x02\x03\x04')
IPv4Address('1.2.3.4')
>>> str(ipaddress.IPv4Address(b'\x01\x02\x03\x04'))
'1.2.3.4'

Related

Python program to convert wildcard mask to netmask

I need help with writing a python program to achieve this task.
I am trying to convert wildcard mask to netmask.
Input:
192.168.0.1 0.0.0.15
Expected output:
192.168.0.1 255.255.255.240
What have you tried? I think it is just xor operator on the bits. Let me know if I'm correct please.
my inputs: 192.168.0.1 0.0.0.15
expected output: 192.168.0.1 255.255.255.240
ip, wcmask = input.split()
netmask='.'.join([str(255^int(i)) for i in wcmask.split('.')])
return '{} {}'.format(ip, netmask)
python2
>>> import ipaddress
>>> print ipaddress.ip_network(u'192.168.0.1/0.0.0.15', strict=False).netmask
255.255.255.240
python3
>>> import ipaddress
>>> print(ipaddress.ip_network('192.168.0.1/0.0.0.15', strict=False).netmask)
255.255.255.240
Convert wildcard to subnet
from cisco_acl import Address
address = Address("192.168.0.1 0.0.0.15")
subnets = address.subnets()
print(subnets)
# ['192.168.0.0 255.255.255.240']
Convert non-contiguous wildcard to list of subnets
from cisco_acl import Address
address = Address("192.168.0.1 0.0.3.15")
subnets = address.subnets()
print(subnets)
# ['192.168.0.0 255.255.255.240',
# '192.168.1.0 255.255.255.240',
# '192.168.2.0 255.255.255.240',
# '192.168.3.0 255.255.255.240']

Python hex IP as string to DDN IP string

I have the following IP in hex: 0xac141315
I would like to convert it to its DDN equivalent.
I used to use '.'.join([str(x) for x in 0xac141315.asNumbers()]) when 0xac141315 had the following type: <class 'CiscoNetworkAddress'>
Or is there a way to convert the string back to CiscoNetworkAddress?
According to CISCO-TC MIB, CiscoNetworkAddress is actually an octet string. There are many ways to turn octet string into a DDN. For example, with ipaddress module from Python 3 stdlib:
>>> from pysnmp.hlapi import OctetString
>>> ip = OctetString(hexValue='ac141315') # this is what you have
>>>
>>> ipaddress.IPv4Address(ip.asOctets())
IPv4Address('172.20.19.21')
Or you can turn it into SNMP SMI IP address:
>>> from pysnmp.hlapi import IpAddress
>>> IpAddress(ip.asOctets()).prettyPrint()
'172.20.19.21'
Also, you could get a sequence of integer octets right from your existing object:
>>> ip.asNumbers()
(172, 20, 19, 21)
Keep in mind, that CiscoNetworkAddress is designed to hold many different address types, not just IPv4. So you should probably apply the IPv4 conversion only when it's actually IPv4 address.
Here is a complete example of how to convert to decimal ip:
#!/usr/bin/python
import sys
# Must be (0xXXXXXXXX)
if len(sys.argv)< 2:
print("Usage: %s (HEX FORMAT, for example 0xAC141315)" % sys.argv[0])
sys.exit(0)
user_option = sys.argv[1]
hex_data=user_option[2:]
#Check if length = 8
if len(hex_data)< 8:
hex_data = ''.join(('0',hex_data))
def hex_to_ip_decimal(hex_data):
ipaddr = "%i.%i.%i.%i" % (int(hex_data[0:2],16),int(hex_data[2:4],16),int(hex_data[4:6],16),int(hex_data[6:8],16))
return ipaddr
result=hex_to_ip_decimal(hex_data)
print result

Print python os.urandom output on terminal

how can i print the output of os.urandom(n) in terminal?
I try to generate a SECRET_KEY with fabfile and will output the 24 bytes.
Example how i implement both variants in the python shell:
>>> import os
>>> out = os.urandom(24)
>>> out
'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I'
>>> print out
oS�������5*������piE�I
If what you want is hex-encoded string, use binascii.a2b_hex (or hexlify):
>>> out = 'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I'
>>> import binascii
>>> print binascii.hexlify(out)
6f53f8f4e2c8dae37fc7352a83b1068c85a4a7706945d649
To use just built-ins, you can get the integer value with ord and then convert that back to a hex number:
list_of_hex = [str(hex(ord(z)))[2:] for z in out]
print " ".join(list_of_hex)
If you just want the hex list, then the str() and [2:] are unnecessary
The output of this and the hexify() version are both type str and should work fine for the web app.

different outputs in unpack function in python

I am observing a different output in the unpack function of python when I accept the string input from the console and when I read the string input from a variable.
I read the string input from the variable, input:
>>> import struct
>>> input="\x0d\x00\x00\x00"
>>> print struct.unpack("I",input)[0]
13
I read the string input from the console:
>>> import sys
>>> import struct
>>> print struct.unpack("I",sys.stdin.read(4))[0]
\x0d\x00\x00\x00
1680898140
The input string is the same but the output is different. Does it interpret the input read from the console in a different way? How can I get the same input by reading the data from console?
"\x0d\x00\x00\x00" (from the first code) is different from r"\x0d\x00\x00\x00" (== "\\x0x\\x00\x00\x00") from the second code.
>>> struct.unpack("I", '\x0d\x00\x00\x00')[0]
13
>>> struct.unpack("I", r'\x0d\x00\x00\x00'[:4])[0]
1680898140
Try following:
>>> struct.unpack("I", sys.stdin.readline().decode('string-escape')[:4])[0]
\x0d\x00\x00\x00
13
seems like you are unpacking the wrong data...
>>> struct.unpack('I','\\x0d')[0]
1680898140
your call to sys.stdin.read(4) reads only 4 characters: \, x, 0 and d.
>>> import sys
>>> import struct
>>> value = raw_input().decode('string-escape')
\x0d\x00\x00\x00
>>> print struct.unpack("I", value)[0]
13

python pack output in string format

I have done the following.
from struct import pack, unpack
t = 1234
tt = str(pack("<I", t))
printing tt gives \xf3\xe0\x01\x00. How do I get original value of t back from tt?
I tried using unpacking the repr(tt) but that does not work out. How do I go about doing this?
>>> t=1234
>>> tt=pack('<I', t)
>>> tt
'\xd2\x04\x00\x00'
>>> unpack('<I', tt)
(1234,)
>>> ttt, = unpack('<I', tt)
>>> ttt
1234
you are using the wrong package for serialization. the struct package is only useful for python code which interacts with C code.
for serialization into a string, you should use the pickle module.
import pickle
t = 1234
tt = pickle.dumps(t)
t = pickle.loads(tt)
unpack('<I', tt) will give you (1234,).
repr doesn't work since it adds quotes to the string:
>>> repr('foo')
'"foo"'

Categories