即使我把str转换成int,它仍然说是s

2024-05-14 23:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个端口扫描程序,用户可以在其中键入要在主机上扫描的端口范围,我将输入从str转换为int作为range,但它仍然表示它是str。下面是我的代码:

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()

我的错误是:

  File "swisshack_W2.py", line 61, in portScanner
for port in range(portRange1, ", ", portRange2):
TypeError: range() integer end argument expected, got str.

Tags: toinhosttargetforinputrawport
1条回答
网友
1楼 · 发布于 2024-05-14 23:52:05

将int添加到字符串", "时,得到一个字符串。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).

相关问题 更多 >

    热门问题