Python hex IP as string to DDN IP string - python

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

Related

How can I print in an f-string an IP address in the dotted binary notation from the output of inet_pton()?

The following code is supposed to take an IP from its user, convert it to the binary and print it to the screen.
#!/usr/bin/env python3
from socket import inet_aton, inet_pton, AF_INET
ip = input("IP?\n")
ip = inet_pton(AF_INET, ip)
print(f"{ip}")
When given 185.254.27.69 it prints
b'\xb9\xfe\x1bE' .f"{ip:08b}" does not work, perhaps because of the three dots in between the fours octets.. How could I get the dotted binary format of an IP printed on the screen? Any resources of use?
Unless I'm missing something, I don't see a reason to use inet_pton here. It converts to packed bytes, when you want a binary representation of the numbers (I assume):
ip = input("IP?\n")
print('.'.join(f'{int(num):08b}' for num in ip.split('.')))
For the input you supplied:
IP?
185.254.27.69
10111001.11111110.00011011.01000101
this code works for binary ip and keeps leading zeros:
from socket import inet_aton, inet_pton, AF_INET
ip = ip2 = input("IP?\n")
ip = inet_pton(AF_INET, ip)
ip2 = ip2.split(".")
ip3 = ""
for ip in ip2:
ip = int(ip)
if len(ip3) == 0:
zeros = str(bin(ip)[2:]).zfill(8)
ip3 += zeros
else:
zeros = str(bin(ip)[2:]).zfill(8)
ip3 += "." + zeros
print(f"{ip3}")

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']

converting IP string to hex for dpkt.IP

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'

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.

Str to hex in Python

I receive on my socket a 4 bytes value that I want to print as hex value. I am trying:
print "%08x" % (nonce)
However, I get an error message that string can't be converted to hex. Anyone an idea
how this could be quickly resolved?
Use the struct module to unpack the octets received from the network into an actual number. The %08x format will work on the number:
import struct
n, = struct.unpack('>I', nonce)
print "%08x" % n
You most likely have a string containing the bytes. However, to print them as a number you need well.. a number.
You can easily create the hex string you are looking for like this:
''.join('%02x' % ord(x) for x in nonce)
Demo:
>>> nonce = os.urandom(4)
>>> nonce
'X\x19e\x07'
>>> ''.join('%02x' % ord(x) for x in nonce)
'58196507'
Another option is:
from binascii import hexlify
>>> hexlify('a1n4')
'61316e34'
num = "9999"
print hex(int(num))
#0x270f
If your data can be converted to a string, you could use the str.encode() method:
>>> s = "XYZ"
>>> s.encode('hex')
'58595a'

Categories