2017-02-12 42 views
-1

我正在嘗試創建一個端口掃描器,用戶可以在其中鍵入要在主機上掃描的端口範圍,我將輸入從str轉換爲int範圍但它仍然表示這是一條大街。這裏是我的代碼:即使當我將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. 
+2

' 「」'是不是一個整數。 – user2357112

+1

'對於範圍內的端口(portRange1 +「,」+ portRange2):' '「,」是什麼與你混在一起我認爲 – Nullman

+1

此外,您發佈的代碼與您發佈的錯誤消息不匹配。 – user2357112

回答

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). 
+0

感謝您的幫助:)。 –

相關問題