前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python和shell的ping对比

python和shell的ping对比

作者头像
py3study
发布2020-01-07 11:14:35
7540
发布2020-01-07 11:14:35
举报
文章被收录于专栏:python3python3python3

1.shell脚本ping局域网的脚本

   脚本代码

#!/bin/bash
for i in {1..50}
do
        ping -c 1 192.168.0.$i >/dev/null
        if [ $? = 0 ]
        then
                echo "192.168.0.$i used"
        else
                echo "192.168.0.$i unused"
        fi
done

执行结果及执行时间

2.python版本ping局域网的脚本(windows和linux通用)

#!/usr/bin/python
#_*_coding:utf-8_*_
import os
import time
from threading import Thread
class PING(Thread):
        def __init__(self,ip):
                Thread.__init__(self)
                self.ip=ip
        def run(self):
                if os.name=="nt":
                        output=os.popen("ping -n 1 %s" % (self.ip)).read().split("\r\n")
                        if "Packets: Sent = 1, Received = 1, Lost = 0 (0% loss)," in output:
                                print "%s 使用" % self.ip
                        else:
                                print "\033[32m%s 未使用\033[0m" % self.ip
                elif os.uname()[0] == "Linux":
                         output=os.popen("ping -c 1 -w 2 %s" % (self.ip)).read().split("\n")
                         if "1 packets transmitted, 1 received, 0% packet loss, time 0ms" in output:
                                print "%s 使用\r" % self.ip
                         else:
                                print "\033[32m%s 未使用\r\033[0m" % self.ip
                else:
                         print ("%s is ERROR" %(self.ip))
#多线程同时执行
T_thread=[]
Ip_addr=[]
aa=raw_input('\033[31m input ping range,exp:192.168.0.0,192.168.0.10 \033[0m\n>>>')
aa1=aa.split('.')
ip1="%s.%s.%s." %(aa1[0],aa1[1],aa1[2])
ip2=int(aa1[6])
ip2+=1
aa2=aa1[3].split(',')
for i in range(int(aa2[0]),ip2):
        Ip_addr.append(ip1+str(i))
for i in Ip_addr:
        t=PING(i)
        T_thread.append(t)
for i in range(len(T_thread)):
        T_thread[i].start()

执行结果和时间截图

总结:

有可能小批量任务看不出明显差别,但是大批量执行,python多线程脚本是shell脚本使用的一半时间

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档