2010-08-16 114 views
0

我想弄清楚如何掃描類C的IP範圍; 例如用戶通過CMD線給我的腳本提供: 蟒蛇script.py 192.168.0.0/24(OR 192.168.0.1-255)掃描C類網絡Python

讓我們弄清楚我的劇本確實只是一個TCP連接動作:

import socket, sys 

host = sys.argv[1],65535 

s = socket(AF_INET, SOCK_STREAM) 

s.connect(host) 

s.send("helloworld") 

我真的需要做一個「for x in ip range」?!? 或者在模塊中構建可以做到這一點?

謝謝!

+1

順便說一句:「C類網絡」一詞自1993年(RFC 1518/1519)以來已被棄用,因爲它不僅僅意味着「一個有255個地址的網絡」。你也使用/ 24這個術語是正確的。 – IanH 2010-08-16 09:38:04

回答

3

它並不需要太多的代碼,你想要做純Python

import socket, struct 

def atod(a): # ascii_to_decimal 
    return struct.unpack("!L",socket.inet_aton(a))[0] 

def dtoa(d): # decimal_to_ascii 
    return socket.inet_ntoa(struct.pack("!L", d)) 

net,_,mask = sys.argv[1].partition('/') 
mask = int(mask) 
net = atod(net) 

for host in (dtoa(net+n) for n in range(0, 1<<32-mask)): 
    print host 
2

ipaddr-py是一個非常方便的模塊,用於處理IP地址和子網。

>>> from ipaddr import IPv4Network 
>>> net = IPv4Network('192.168.0.0/24') 
>>> for host in net.iterhosts(): 
...  print repr(host) 
... 
IPv4Address('192.168.0.1') 
IPv4Address('192.168.0.2') 
IPv4Address('192.168.0.3') 
IPv4Address('192.168.0.4') 
..... and the rest 
1

這裏是一個小工具SCANIP,這將有助於你得到的所有IP地址及其對應的MAC網絡中的地址(在Linux上運行)。這是用Python編寫的scanip(Ip和Mac掃描器)的鏈接。 https://pypi.python.org/pypi/scanip/1.0

您還可以使用畫中畫在Linux上安裝SCANIP並使用它,在Python創建一個測試文件,並使用它像這 -

import scanip.scanip 

scanip.scanip.start_scan() 

並運行此程序下載。局域網中的所有IP及其對應的MAC地址都將顯示在終端中。