【问题标题】:Even when I convert an str to int it still says it's a str即使我将 str 转换为 int 它仍然说它是 str
【发布时间】:2017-06-30 05:24:48
【问题描述】:

我正在尝试制作一个端口扫描器,用户可以在其中键入一系列端口以在主机上进行扫描,我将输入从 str 转换为 int 以获取范围,但它仍然说它是一个 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.

【问题讨论】:

  • ", " 不是整数。
  • for port in range(portRange1 + ", " + portRange2): ", " 我觉得你在搞什么鬼
  • 另外,您发布的代码与您发布的错误消息不匹配。

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


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助:)。
猜你喜欢
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2018-08-14
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多