接受ip地址作为用户输入

时间:2014-05-27 04:35:08

标签: python-2.7 networking ip ip-address user-input

import os
import sys
import time
import pprint
import subprocess
from netaddr import *

print "(1).Ping specific target.\n(2).Ping sweep Subnet.\n(3).Exit"
choice = raw_input("Enter your choice:- ")
if choice == '1':
    host = raw_input("Enter IP address to scan: ")
    ip = IPAddress("host")
    print "accepted"

这是该计划的第一部分。我在接受用户的IP地址作为输入时遇到问题。 执行后我得到以下错误。

Traceback (most recent call last):
  File "ping.py", line 13, in <module>
    ip = IPAddress("host")
  File "/usr/local/lib/python2.7/dist-packages/netaddr/ip/__init__.py", line 308, in __init__
    'address from %r' % addr)
netaddr.core.AddrFormatError: failed to detect a valid IP address from 'host'

使用python 2.7.6

2 个答案:

答案 0 :(得分:0)

你可以使用try / except循环:

done = False
while not done:
    host = raw_input("Enter IP address to scan: ")
    try:
        ip = IPAddress("host")
        done = True
    except netaddr.core.AddrFormatError:
        print 'Invalid IP Address Format, please try again!'

答案 1 :(得分:0)

您在作业中使用字符串"host"而不是变量host

变化:

ip = IPAddress("host")

ip = IPAddress(host)