python运维-检测活跃主机(ping)

1.shell脚本实现

#!/bin/bash

for i in `seq 125 135`
do
	ip="192.168.154.$i"
	if ping $ip -c 1 &> /dev/null
	then
		echo "$ip is alive."
	else
		echo "$ip is not"
	fi
done

2.python多线程实现,为每一个ip创建一个线程

#!/usr/bin/python3

import subprocess
import threading

alives = []

def is_reacheable(ip):
	if subprocess.call(["ping", "-c", "1", ip]) == 0:
		print("{0} is alive.".format(ip))
		alives.append(ip)
	else:
		print("{0} is not.".format(ip))


def main():	
	threads = []
	for i in range(100,200):
		ip = "192.168.154." + str(i)
		thr = threading.Thread(target=is_reacheable, args=(ip,))
		thr.start()
		threads.append(thr)

	for thr in threads:
		thr.join()

if __name__ == "__main__":
	main()
	print(alives)

3.python多线程实现,创建10个线程,并使用队列解决多线程之间的并发问题

#!/usr/bin/python3

import subprocess
import threading
from queue import Queue
from queue import Empty

alives = []


def call_ping(ip):
    if subprocess.call(["ping", "-c", "1", ip]) == 0:
        print("{0} is alive.".format(ip))
        alives.append(ip)
    else:
        print("{0} is not.".format(ip))


def is_reacheable(q):
    try:
        while True:
            ip = q.get_nowait()
            call_ping(ip)
    except Empty:
        pass


def main():
    threads = []
    q = Queue()
    for i in range(100, 200):
        ip = "192.168.154." + str(i)
        q.put(ip)

    for i in range(10):
        thr = threading.Thread(target=is_reacheable, args=(q,))
        thr.start()
        threads.append(thr)

    for thr in threads:
        thr.join()


if __name__ == "__main__":
    main()
    print(alives)
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值