即使我将str转换为int,它仍然表示它是str

时间:2017-02-12 02:12:28

标签: python string python-2.7 int port-scanning

我正在尝试创建一个端口扫描程序,用户可以在其中键入一系列端口以在主机上扫描,我将输入从str转换为int作为范围,但它仍然说它是一个str。这是我的代码:

import json

...

textfile.write(json.dumps(words))

我的错误是:

os.system('cls')
host = raw_input('Enter hostname or IP address: ')
target = socket.gethostbyname(host)
# converts hostname to IP address

portRange1 = raw_input("Please enter the first number (x) in your range (x, y): ")
portRange2 = raw_input("Please enter the second number (y) in your range (" + portRange1 + ", y): ")
# asks user for range of ports to scan

portRange1 = int(portRange1)
portRange2 = int(portRange2)
# converts variables from str to int

os.system('cls')
# clears console screen

print 'Starting scan on host ' +  target
for port in range(portRange1 + ", " + portRange2):  
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((target, port))
    if result == 0:
        print "Port {}:      Open".format(port)
sock.close()
choice()
# scans for ports 0-1025 on host

choice()

1 个答案:

答案 0 :(得分:2)

当您为字符串", "添加整数时,您会得到一个字符串。 range()方法采用整数参数。

for port in range(portRange1, portRange2 + 1):

使用python交互式解释器来试用代码片段。

help(range)

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).