简体   繁体   English

Python 将 Base64 中编码的 IP 地址转换为十进制 ZA12A3079E14CED46E621AZ9BA52B8A 地址

[英]Python Convert an IP address encoded in Base64 to a Decimal IP address

I am very new to programming and Python so please bear with me.我对编程和 Python 非常陌生,所以请多多包涵。 I have a string that is Base64 and I want to convert it to decimal.我有一个字符串是 Base64,我想将它转换为十进制。 The string can come in to the script as any value, for example zAvIAQ.该字符串可以作为任何值进入脚本,例如 zAvIAQ。 This value represents an IP address which is 204.11.200.1 when converted to decimal.此值表示 IP 地址,转换为十进制时为 204.11.200.1。 What I want to do is convert the Base64 string to decimal and assign it to a variable so that I can use it elsewhere in the script.我想要做的是将 Base64 字符串转换为十进制并将其分配给一个变量,以便我可以在脚本的其他地方使用它。

I have tried to use the base64.decode function, but that just gives me a very strange text output.我曾尝试使用 base64.decode function,但这只是给了我一个非常奇怪的文本 output。 I have tried to use the Decimal() function but that gives me an error.我尝试使用 Decimal() function 但这给了我一个错误。 After searching for several days now I haven't found a way to do this, at least not one that I can understand.经过几天的搜索,我还没有找到一种方法来做到这一点,至少不是我能理解的方法。 Any help that you can provide would be appreciated.您可以提供的任何帮助将不胜感激。

First decode the base64-encoded string using decode('base64') and then decode the resulting number into an IP quartet by using socket.inet_ntoa .首先使用decode('base64') base64 编码的字符串,然后使用socket.inet_ntoa将结果数字解码为 IP 四重奏。 Like this:像这样:

>>> socket.inet_ntoa('zAvIAQ=='.decode('base64'))
'204.11.200.1'
>>> address=[ord(c) for c in base64.b64decode('zAvIAQ==')]
>>> address
[204, 11, 200, 1]

I usually use base64.b64decode() .我通常使用base64.b64decode() With that you get:有了它,你会得到:

In [18]: base64.b64decode('zAvIAQ==')
Out[18]: '\xcc\x0b\xc8\x01'

That is probably the weird output you were referring to.那可能就是您所指的奇怪的 output 。 The point is that you get a byte string back, with each byte representing a value between 0 and 255. Those values might not be printable, hence the \x representation.关键是你得到一个字节字符串,每个字节代表一个介于 0 和 255 之间的值。这些值可能无法打印,因此是 \x 表示。

But as you know that these are the buckets of an IPv4 address, you go through them converting them to decimals, eg with the generator expression:但是您知道这些是 IPv4 地址的存储桶,您可以通过 go 将它们转换为小数,例如使用生成器表达式:

[ord(c) for c in ...]

and you get the more familiar representation 204, 11, 200, 1.你会得到更熟悉的表示 204、11、200、1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM