程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Scan the specified network segment IP of LAN in Python

編輯:Python

One 、 Origin of the problem

Working in a local area network , Many devices will be connected , The network device on the robot is 2 A the , A giant brother infrared , A Hikvision visible light . Robots have their own ip.
Sometimes robots hang too much , The equipment is under repair and replacement , I don't remember what happened ip What is it? , You can really scan it out with your own software , But it will take two windows Software in environment , time-consuming , Toss about . Just in linux, That's easy , Strike an order .
nmap -P 192.168.1.0/24
You can scan it 192.168.1.0~192.168.1.255 All ip
But the premise is to install nmap

apt-get install nmap

But I always felt that I was beating mosquitoes with anti-aircraft guns —— overqualified
Then do it yourself python Well , So I copied and changed on the Internet .

Two 、python Scan the specified network segment ip

1、demo

pingS.py

import sys
import os
import time
import _thread
import datetime
def 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):
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__":
startTime = datetime.datetime.now()
print("start time %s"%(time.ctime()))
net=sys.argv[1]
args = "".join(("192.168."+net+".1"))
ip_prefix = '.'.join(args.split('.')[:-1])
find_ip(ip_prefix)
endTime = datetime.datetime.now()
print("end time %s"%(time.ctime()))
print("total takes :",(endTime - startTime).seconds)
  • python3 Division thread modular , For Compatibility Use _thread Instead of , The safest use is to use threading modular
  • datetime.datetime.now() Get the current time
  • os = platform.system() Judge the current system type
  • output = os.popen() Call the terminal , The return value is saved in output in
  • The duration of each scan is about 76 s.

2、 function

python3 pingS.py 1

Parameters 1 Is the specified network segment , If you want to scan 192.168.5.0~192.168.5.255
Then input. :

python3 pingS.py 5

3、 pack

pyinstaller -F pingS.py Packaged into a single executable
Use the above command if... Is installed pyinstaller——-(pip intsall pyinstaller)

After running, a pingS The executable of

cp pingS /bin

Okay , To this step , Open the terminal input anywhere :

pingS 1

All can be done 192.168.1.0~192.168.1.255 Scan


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved