检测主机状态

(1)
import subprocess
import threading

def ping(host):
result = subprocess.call(
‘ping -c2 %s &> /dev/null’ % host,
shell=True
)
if result == 0: # result的值就是ping命令的退出码,即$?
print(‘%s’ % host)
# else:
# print(‘%s:down’ % host)

if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips: # 主线程用于产生工作线程
t = threading.Thread(target=ping, args=(ip,))
t.start() # 将会执行ping(ip),执行完就停止了,不会有僵尸进程
# 主线程不会等待工作线程结束,直接进入下次循环

(2)
import threading
import subprocess

class Ping:
# def init(self, host):
# self.host = host

def __call__(self, host):
    result = subprocess.call(
        'ping -c2 %s &> /dev/null' % host,
        shell=True
    )
    if result == 0:  # result的值就是ping命令的退出码,即$?
        print('%s:up' % host)
    else:
        print('%s:down' % host)

if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips:
t = threading.Thread(target=Ping(), args=(ip,))
t.start() # Ping(ip)() <==> target()

(3)
import threading
import subprocess

class Ping:
def init(self, host):
self.host = host

def __call__(self):
    result = subprocess.call(
        'ping -c2 %s &> /dev/null' % self.host,
        shell=True
    )
    if result == 0:  # result的值就是ping命令的退出码,即$?
        print('%s:up' % self.host)
    else:
        print('%s:down' % self.host)

if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips:
t = threading.Thread(target=Ping(ip))
t.start() # Ping(ip)() <==> target()

(4)
import subprocess
import os

def ping(host):
result = subprocess.call(
‘ping -c2 %s &> /dev/null’ % host,
shell=True
)
if result == 0: # result的值就是ping命令的退出码,即$?
print(‘%s:up’ % host)
else:
print(‘%s:down’ % host)

if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips:
pid = os.fork() # 父进程负责生成子进程
if not pid: # 子进程负责ping
ping(ip)
exit() # 子进程ping完一个地址后结束,不要再循环

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值