Python实现Ping程序

        首先利用Python实现的Ping程序是使用Python的subprocess模块实现的,subprocess包主要功能是执行外部的命令和程序,其封装了很多常用函数。此程序通过subprocess模块的Popen函数执行命令,读取返回的TTL信息判断主机是否在线。在此之前有说过TTL字段是IP头部生存时间(time to live)。

        其次,功能相对简单,包括支持输入需要Ping的IP地址段、显示主机是否在线、默认开启20个线程进行扫描。

# -*- coding: GBK -*-
from tkinter import *
import subprocess
import threading
import time
import re
def btn_click():
    text.insert(INSERT,("IP地址        状态!\n"))
    i=0
    j=1
    thread_id =[]
    ip=int(ipText.get())
    v=('10.104.117.%d' % (x) for x in range(0,ip+1))
    for it in v:
        loop = str('%s' % it)   
        thread_id.append(0)  
        thread_id[i] = Ping(loop, int(j/20))  
        thread_id[i].start()
        #thread_id[i].join()
        i=i+1
        j=j+10
class Ping(threading.Thread):
    def __init__(self,str_ip,sleep_time):  
        threading.Thread.__init__(self)
        self.str_ip = str_ip
        self.sleep_time = sleep_time 
    def run(self):
        time.sleep(self.sleep_time) 
        ftp_ret = subprocess.Popen('ping %s -n 3' % self.str_ip,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
        ret = ftp_ret.stdout.read()  
        str_ret = ret.decode("gbk")  
        ret_s = re.search("TTL",str_ret)
        if ret_s:
            text.insert(INSERT,("%s    在线!\n" % self.str_ip))
            #text.update()
        else:
            text.insert(INSERT,("%s    下线!\n" % self.str_ip))
   
root = Tk()
root.title('局域网Ping程序')
root.geometry('600x400')
main_frame = Frame(root)
text_frame=Frame(main_frame)
ip_frame=Frame(main_frame)
botton_frame=Frame(ip_frame)


l1 = Label(ip_frame,text='IP地址:10.104.117 从 0 到')
l2 = Label(ip_frame,text='   线程20   ')
ipText=Entry(ip_frame)

l1.pack(side='left')
ipText.pack(side='left')
ipText['width']=5
l2.pack(side='left')
b = Button(ip_frame,text='开始',command=btn_click)
b['width']=4
b['height']=1
b.pack(side='left')


text = Text(text_frame,width = 30, height= 25)
text.pack()
main_frame.pack()
ip_frame.pack(side='top',pady='5')
text_frame.pack()
root.mainloop()

 

 

 

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我的书包哪里去了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值