首頁  >  文章  >  後端開發  >  使用python檢測某網段已用ip和未使用的ip的方法

使用python檢測某網段已用ip和未使用的ip的方法

高洛峰
高洛峰原創
2017-03-22 10:11:001647瀏覽

借鑒了前輩的博客,然後自己加了很多東西。

其中用到了subprocess模組

>>> import subprocess

>>> p = subprocess.Popen('df -h',stdin =subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

#取得命令執行結果的回傳碼,透過wait()函數

#>>> p.wait()

0

##取得指令輸出結果(標準輸出),透過read()方法

> >> p.stdout.read()

'Filesystem            Size  Used Avail Use% Mounted on\n/dev/sda1                     495M     0  495M   0% /dev/shm \n'

# 取得指令錯誤輸出結果,透過read()方法

>>> p.stderr.read()            

''

##為空,表示沒有錯誤輸出

#取得錯誤輸出

object

 at 0x7f267528dbd0>

#> ;>> p = subprocess.Popen('ls /etc/password',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,close_fds=True)

#>>> p.stderr.read()

'ls: cannot access /etc/password: No such file or directory\n'

#@其他取得錯誤輸出的方法還有:read(),

readline

(),readlines(),close(),write()和writelines()等.#!/usr/bin/env

python

#_*_ coding:utf8 _*_

# by lijiajun

import re,subprocess,os,sys

#net_region='192.168.3'

print("

##")

print("#此腳本主要基於ping,測試某網段已用ip與未使用的ip       #")

print("#分別儲存至/tmp/alive_ip.txt                  /dead_ip.txt                                   #")

print("

")

#print(" ")

if

os .path.isfile("/tmp/alive_ip.txt"):  

os.popen("mv /tmp/alive_ip.txt /tmp/alive_ip.txt.old")

print "you can see the used ip in this file : /tmp/alive_ip.txt"

if os.path.isfile("/tmp/dead_ip.txt"):  

os.popen ("mv /tmp/dead_ip.txt /tmp/dead_ip.txt.old") print "you can see the unused ip in this file : /tmp/dead_ip.txt"

# print(" ")

dead_ip=0

alive_ip=0######def check_alive(ip,###count###,###time###out ):###### global alive_ip###### global dead_ip###### cmd='ping -c %d -w %d %s' % (count,timeout,ip)### ### p=subprocess.Popen(cmd,###### stdin=subprocess.PIPE,###### stdout=subprocess.PIPE,####### stderr=subprocess.PIPE,### ### shell=True)###### result=p.stdout.read()###### regx=re.findall('100% packet loss',result)###### if len(regx)==0:###### print("\033[1;32;40m %s is UP \033[0m")  % (ip)###### f=file(' /tmp/alive_ip.txt','a')###### f.write('%s\n' %ip)###### f.close()###### alive_ip= alive_ip+1###### print "alive_ip count is %d" % alive_ip###### ###return### alive_ip###### ###else###:### ### print "\033[31m %s is DOWN\033[0m" % (ip)######                f=file('/tmp/dead_ip.txt','a')#### #                f.write('%s\n' %ip)###### f.close()###### dead_ip=dead_ip+1###### print "dead_### dead_ip=dead_ip+1###### print "dead_ip ## dead_ipcount" % dead_ip###### return dead_ip######if name=="###main###":###### #f=file('/tmp/iplist.txt') ###### ###for### i in ###range###(1,255):###### ip='%s.%s' % (net_region,i)### ### print ip###

check_alive(ip,1,1)

print ("  ")

print "final dead_ip 計數為 %d" % dead_ip

# print "最終的alived_ip 計數為%d" % alive_ip

以上是使用python檢測某網段已用ip和未使用的ip的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn