我正在嘗試構建一個非常簡單的埠掃描器,以便練習套接字的概念。我的設計如下:
from socket import *
ip = input("Submit IP to scan:")
start = input("Submit starting port:")
end = input("Submit ending port:")
print("Scanning IP:", ip)
for port in range(int(start),int(end)):
print("Scanning port:" str(port) "..")
var_socket = socket(AF_INET,SOCK_STREAM)
var_socket.settimeout(3)
if var_socket.connect_ex((ip,port)) == 0:
print("port", port, "is open")
else:
print("err code:", var_socket.connect_ex((ip,port)))
var_socket.close()
print("Scanning completed!")
當我從檔案運行它時,這一切都很好。不幸的是,我可能并不總是能夠從檔案中運行我的腳本,因此我需要能夠在命令 shell 中創建這個腳本。我自己使用互聯網上的提示和技巧進行了一些嘗試,但它們都以某種方式失敗了。
from socket import * #Press enter. Note that I am in a windows terminal.
ip = input("enter ip to scan:")\ #Press enter
start = input("enter starting port:")\ #Press enter
輸出:語法錯誤:語法無效
我發現的另一個解決方案確實有效,但在此程序中帶來了一些不必要的復雜性:
from socket import *
ip,start,end = map(int,input().split()) #Press enter
此解決方案允許我輸入由空格分隔的 3 個值,分別將它們映射到 ip、start 和 end。當然,除非我設計一個函式將輸入的 ip 值手動轉換為有效的點分十進制 IP 地址,否則這將不起作用。有誰知道在 shell 環境中要求多個輸入的更好方法嗎?
非常感謝。
uj5u.com熱心網友回復:
復制您的腳本時,python 解釋器會逐行讀取您的代碼,這使得它用您正在鍵入的腳本填充您的輸入。避免這種情況的一種解決方案是從不同位置(引數、檔案等)讀取檔案。或者,您也可以將腳本加載到記憶體中,然后在請求輸入之前執行:
script = '''
from socket import *
ip = input("Submit IP to scan:")
start = input("Submit starting port:")
end = input("Submit ending port:")
print("Scanning IP:", ip)
for port in range(int(start),int(end)):
print("Scanning port:" str(port) "..")
var_socket = socket(AF_INET,SOCK_STREAM)
var_socket.settimeout(3)
if var_socket.connect_ex((ip,port)) == 0:
print("port", port, "is open")
else:
print("err code:", var_socket.connect_ex((ip,port)))
var_socket.close()
print("Scanning completed!")
'''
exec(script)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361608.html
