Is there a script available to convert a starting and ending IP address to a slash notation?
Example:
>>> ip_long = '10.182.71.0-10.182.75.255'
>>> convert_to_slash(ip_long)
10.182.71.0/24, 10.182.72.0/22
Use summarize_address_range() from ipaddress, which is part of the Python 3 standard library (and backported to Python 2).
>>> import ipaddress
>>> first = ipaddress.IPv4Address('10.182.71.0')
>>> last = ipaddress.IPv4Address('10.182.75.255')
>>> summary = ipaddress.summarize_address_range(first, last)
>>> list(summary)
[IPv4Network('10.182.71.0/24'), IPv4Network('10.182.72.0/22')]
Google's ipaddr-py library has a method called summarize_address_range(first, last).
summarize_address_range(first, last):
"""Summarize a network range given the first and last IP addresses.
Example:
>>> summarize_address_range(IPv4Address('1.1.1.0'),
IPv4Address('1.1.1.130'))
[IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
IPv4Network('1.1.1.130/32')]
Args:
first: the first IPv4Address or IPv6Address in the range.
last: the last IPv4Address or IPv6Address in the range.
Returns:
The address range collapsed to a list of IPv4Network's or
IPv6Network's.
Raise:
TypeError:
If the first and last objects are not IP addresses.
If the first and last objects are not the same version.
ValueError:
If the last object is not greater than the first.
If the version is not 4 or 6.
"""
Another solution:
from ipaddress import IPv4Address, summarize_address_range
a=" ".join(map(str, summarize_address_range(IPv4Address('8.8.8.8'), IPv4Address('8.8.9.1'))))
print(a)
Related
I might be using wrong python terminology.
I have an array of 3 integer elements: month, date and year.
However, I am not able to print each individual element when concatenating strings.
import ssl
import OpenSSL
import time
import sys
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
raw_date = x509.get_notAfter()
decoded_date = raw_date.decode("utf-8")
dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
bes = dexpires.tm_mon,dexpires.tm_mday,dexpires.tm_year
print (bes)
#print(bes[0]+"/"+bes[1]+"/"+bes[2])
domain = sys.argv[1]
port = 443
get_SSL_Expiry_Date(domain, port)
If I uncomment line 14, I get an error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I am trying to get the date in this format (all strings): Month/Date/Year.
What am I doing wrong?
You can use Python's format() method to handle it (much cleaner also):
print("{0}/{1}/{2}".format(bes[0],bes[1],bes[2]))
...or further simplified (thanks Anton)
print("{0}/{1}/{2}".format(*bes))
↳ Python String Formatting
Simply use:
print(time.strftime("%m/%d/%y",dexpires))
See also https://docs.python.org/3/library/time.html
In general python modules usually contain all kinds of reformatting functions you don't have to reinvent them.
Example:
>>> dexpires=time.strptime('20180823131455z','%Y%m%d%H%M%Sz')
>>> dexpires
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=23, tm_hour=13, tm_min=14, tm_sec=55, tm_wday=3, tm_yday=235, tm_isdst=-1)
>>> time.strftime('%m/%d/%y',dexpires)
'08/23/18'
>>>
First you have to convert int values to string than only you are able to concave them.
You can use str() inbuilt method
print(str(bes[0])+"/"+ str(bes[1])+"/"+ str(bes[2])) #convert int to str first.
I'm trying to take a known subnet ID and CIDR mask, e.g., 10.0.0.0/22, and get a list like this:
[('10.0.0.0', '10.0.3.255'),
('10.0.4.0', '10.0.7.255'),
...
('10.255.252.0', '10.255.255.255')]
I've tried a few existing modules like ipcalc, but it doesn't seem to have a feature like that. I'm not sure what kind of math is necessary for me to write my own module to do it, either.
You can use ipaddress module if you use Python 3.3+:
>>> import ipaddress
>>> it = ipaddress.ip_network('10.0.0.0/8').subnets(new_prefix=22)
>>> networks = [(str(n.network_address), str(n.broadcast_address)) for n in it]
>>> len(networks)
16384
>>> networks[0]
('10.0.0.0', '10.0.3.255')
>>> networks[-1]
('10.255.252.0', '10.255.255.255')
In Python 2.x, use ipaddr:
>>> import ipaddr
>>> it = ipaddr.IPNetwork('10.0.0.0/8').subnet(new_prefix=22)
>>> networks = [(str(n.network), str(n.broadcast)) for n in it]
>>> len(networks)
16384
>>> networks[0]
('10.0.0.0', '10.0.3.255')
>>> networks[-1]
('10.255.252.0', '10.255.255.255')
UPDATE
There's Python 2.7 backport of Python 3.3 ipaddress: py2-ipaddress.
Use the new ipaddress module in Python 3.3:
import ipaddress
for i in ipaddress.ip_network('10.0.0.0/8').subnets(new_prefix=22):
print(i)
I'm learning Python (classes at this momment). On this site (bottom of the page) first exercise (under 13.7. Exercises) says:
Create and print a Point object, and then use id to print the object's unique identifier. Translate the hexadecimal form into decimal and confirm that they match.
I need help with this because I'm not quite sure I understand what I have to do.
If I do:
class Point:
pass
print Point()
print id(Point)
I get this output:
<__main__.Point instance at 0xb71c496c>
3072094252
So, should I do this first part of exercise like this or? And what now? I assume that this second line is decimal number (Am I right?). But what with the first line? How to translate it into decimal?
Translate the second number into hexadecimal with the hex() function then test if it is present in the first:
p = Point()
hexadecimal_id = hex(id(p))
present = hexadecimal_id in repr(p)
Note that I first store a reference to the Point() instance; otherwise you'd get a new one with potentially a new id() value.
Also, don't confuse the class with the instance; the class is an object in its own right, and as such has a id() value too.
To go the other way, you'd have to parse out the hexadecimal string; if you are going to assume it is the part after the last space that's doable as:
hexadecimal_id = repr(p).rpartition(' ')[-1][:-1]
present = int(hexadecimal_id, 16) == id(p)
Here, the str.rpartition() method splits on the last space, and we take whatever comes after it with [-1] (last element), then shorted that result by one character to remove the > character at the end.
Once you have the hexadecimal number you can interpret it as an integer with the int() function, specifying the base as 16.
Demo:
>>> class Point:
... pass
...
>>> p = Point()
>>> id(p)
4300021632
>>> hex(id(p))
'0x1004d1f80'
>>> p
<__main__.Point instance at 0x1004d1f80>
>>> hex(id(p)) in repr(p)
True
>>> # the other direction
...
>>> repr(p).rpartition(' ')[-1][:-1]
'0x1004d1f80'
>>> hexadecimal_id = repr(p).rpartition(' ')[-1][:-1]
>>> int(hexadecimal_id, 16)
4300021632
>>> int(hexadecimal_id, 16) == id(p)
True
Specifically can I provide append() a Null/None value in Python?
I am trying to add auto complete functionality to a command line application, so am using readline to obtain anything the user may have typed at the raw_input prompt.
I'm getting an issue when I try to tab (with no value entered into the console) and get this message: "append() takes exactly one argument (0 given)"
Here is the code:
tokens = readline.get_line_buffer().split()
if not tokens or readline.get_line_buffer()[-1] == ' ':
tokens.append()
I'm using the example provided here because of the traverse function where the depth of the tree isn't an issue:
https://www.ironalbatross.net/wiki/index.php5?title=Python_Readline_Completions#Complex_problem_.28Regular_Grammar.29
tokens variable is a list, so lists method append really takes exactly one argument.
>>> a = []
>>> a
>>> []
>>> a.append(1)
>>> a
>>> [1]
>>> a.append()
>>> TypeError: append() takes exactly one argument (0 given)
>>> a.append(None)
>>> a
>>> [1, None]
append require exactly one argument
None object can't invoke append function
OK I managed to fix it... wasn't sure what value to provide append() when there was no value returned by readline so did this and it worked:
def complete(self,text,state):
try:
tokens = readline.get_line_buffer().split()
if not tokens or readline.get_line_buffer()[-1] == ' ':
tokens.append(text)
Thanks guys!
I am using inet_aton to convert IPv4 IP(216.12.207.142) to a string 3624718222. I use the following code for that:
ip_dec = unpack('>L', inet_aton(ip))[0]
Now I need to convert IPv6 ip 2001:23::207:142 to a similar string. It gives me error as it is not IPv4 address. How can I do this?
This is the code I've uses for the purpose before. Note that it returns a 128 bit integer rather than a string (an integer is more useful in general)
from socket import inet_pton, AF_INET6
from struct import unpack
def ip6_to_integer(ip6):
ip6 = inet_pton(AF_INET6, ip6)
a, b = unpack(">QQ", ip6)
return (a << 64) | b
And testing it
>>> ip6_to_integer("2001:23::207:142")
42540490934961530759802172199372521794L
Or as a string if you must!
>>> str(ip6_to_integer("2001:23::207:142"))
'42540490934961530759802172199372521794'