使用 IP 地址并拆分 Python

Using IP address and splitting in Python

求助!我很愚蠢,无法找到如何做到这一点。 也因为我是 Python.

的初学者

我在 Python 中需要有关此脚本的帮助。

  1. 如何在 python 脚本中使用 IP 地址?
  2. 如何根据破折号 (-) 拆分 IP 地址

我正在尝试这样做

#code
a = input("Enter ip address: ")
print 'edit "ip-' + str(a) + '"\n',

# Shell

Enter ip address:10.203.1.10
# output
edit "ip-10.203.1.10"

如何存储 IP 地址?当我添加小数点时,我会得到一个错误 是否有模块或包或一些秘密。拆分方法可以这样工作吗 x.split("-") 拆分和 IP 地址你如何存储值然后 (a,b)?拥有 像这样。

输入

10.228.50.88-10.228.50.91

输出

编辑"ipr-10.228.50.88-10.228.50.91"

设置类型iprange

设置起始IP 10.228.50.88

设置结束IP 10.228.50.91

非常感谢任何帮助或任何可以为我指明正确方向的人。

希望以下脚本对您有所帮助:

a = raw_input("Enter ip address: ")

print 'edit "ip-' + str(a) + '"\n'

if '-' in a:
    ips = a.split('-')

    print ('set type iprange')

    print ('set start-ip '+ips[0])
    print 'set end-ip '+ips[1]

问题是你在 Python 上使用 input 而 运行 2. 你希望它的 return 类型是一个字符串,但它不是.在 Python 2 中,input 实际上试图 解析和执行输入,就好像它是 Python 代码 一样。显然,192.168.0.0 或任何 IP 地址都是无效的 Python 代码,因此会出现错误。

要解决此问题,请使用 raw_input 而不是 input。那么a就是str类型,也就是一个普通的字符串(IP地址没什么特别的),所以可以用a.splita.join等方法的 str class。

Per https://docs.python.org/2/library/functions.html#input, input is doing this: eval(raw_input(prompt)). The eval means it is trying to take the input and interpret it as python code, which is why you are getting syntax errors. It also says: Consider using the raw_input() 函数用于用户的一般输入,这听起来像您正在寻找的内容。此外,快速测试和 Python3 文档,它看起来像 input() 功能不同并且表现得更像 raw_input() 函数。快速测试:

Python 3.6.2:

>>> a = input("Enter ip address: ")
Enter ip address: 10.1.1.1
>>> a
'10.1.1.1'

Python Python 2.7.13:

>>> a = input("Enter ip address: ")
Enter ip address: 10.1.1.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    10.1.1.1
     ^
SyntaxError: invalid syntax