Home >Backend Development >Python Tutorial >Python实现扫描局域网活动ip(扫描在线电脑)

Python实现扫描局域网活动ip(扫描在线电脑)

WBOY
WBOYOriginal
2016-06-06 11:26:073090browse

内网的主机都是自动分配ip地址,有时候需要查看下有那些ip在使用,就写了个简单的脚本。
linux和windows下都可以用,用多线程来ping1-255所有的地址,效率不高,2分钟左右。 先凑合和用吧。

#-*- coding: utf-8 -*- 
#author: orangleliu date: 2014-11-12 
#python2.7.x ip_scaner.py 
 
''''' 
不同平台,实现对所在内网端的ip扫描 
 
有时候需要知道所在局域网的有效ip,但是又不想找特定的工具来扫描。 
使用方法 python ip_scaner.py 192.168.1.1 
(会扫描192.168.1.1-255的ip) 
''' 
 
import platform 
import sys 
import os 
import time 
import thread 
 
def get_os(): 
  ''''' 
  get os 类型 
  ''' 
  os = platform.system() 
  if os == "Windows": 
    return "n" 
  else: 
    return "c" 
   
def ping_ip(ip_str): 
  cmd = ["ping", "-{op}".format(op=get_os()), 
      "1", ip_str] 
  output = os.popen(" ".join(cmd)).readlines() 
   
  flag = False 
  for line in list(output): 
    if not line: 
      continue 
    if str(line).upper().find("TTL") >=0: 
      flag = True 
      break 
  if flag: 
    print "ip: %s is ok ***"%ip_str 
 
def find_ip(ip_prefix): 
  ''''' 
  给出当前的127.0.0 ,然后扫描整个段所有地址 
  ''' 
  for i in range(1,256): 
    ip = '%s.%s'%(ip_prefix,i) 
    thread.start_new_thread(ping_ip, (ip,)) 
    time.sleep(0.3) 
   
if __name__ == "__main__": 
  print "start time %s"%time.ctime() 
  commandargs = sys.argv[1:] 
  args = "".join(commandargs)   
   
  ip_prefix = '.'.join(args.split('.')[:-1]) 
  find_ip(ip_prefix) 
  print "end time %s"%time.ctime() 


是应用的时候: python ip_scaner.py 192.168.31.1 就会扫描 1-255所有的ip地址了。

D:\CodeHouse\python\tools>python ip_scaner.py 10.0.1.38 
start time Wed Nov 12 18:50:58 2014 
ip: 10.0.1.1 is ok *** 
ip: 10.0.1.2 is ok *** 
ip: 10.0.1.24 is ok *** 
ip: 10.0.1.38 is ok *** 
ip: 10.0.1.39 is ok *** 
end time Wed Nov 12 18:52:16 2014 

就这样。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn