python ping脚本

        每次做路由器无线桥接,都会忘了路由器的ip是多少,一个一个的ping又太麻烦,故写了这个脚本,希望可以帮助到有需要的人。

        * 需要安装以下两个包:

                pip install chardet

                pip install git+https://github.com/ray3175/xy.git

import re
import subprocess
import socket
import threading
from xy.common.file.file_check import FileCheck
# pip install git+https://github.com/ray3175/xy.git
# pip install chardet


class Ping:
    re_success = re.compile(r"字节[=<>]\d+\s+时间[=<>]\d+ms\s+TTL[=<>]\d+")

    def __init__(self, ip=None):
        """
        :param ip: 传入参数地址,如192.168.*.*,则会将*转化为具体数字(0-255),默认获取当前所在ip。
        """
        self.__local_ip = socket.gethostbyname(socket.gethostname())
        if not ip:
            ip = re.sub(r"(\w+\.\w+\.\w+\.)(\w+)", lambda x: x.group(1) + "*", self.__local_ip)
        self.__ip = ip

    def _new_ip_list(self, ip_list):
        new_ip_list = list()
        for i in ip_list:
            if i == "*":
                if new_ip_list:
                    tmp_ip_list = list()
                    for new_ip in new_ip_list:
                        for j in range(0, 256):
                            tmp_ip_list.append(new_ip + [str(j)])
                    new_ip_list = tmp_ip_list
                else:
                    for j in range(1, 256):
                        new_ip_list.append([j])
            else:
                if new_ip_list:
                    for new_ip in new_ip_list:
                        new_ip.append(i)
                else:
                    new_ip_list.append([i])
        return new_ip_list

    def _ping_action(self, ip, result_list):
        p = subprocess.Popen(f"ping {ip}", stdout=subprocess.PIPE)
        text_byte = p.stdout.read()
        text = text_byte.decode(FileCheck.extract_encoding_from_bytes_str(text_byte))
        if self.re_success.search(text):
            result_list.append(ip)
        return True

    def start_ping(self):
        result_list = list()
        t_pool = list()
        for ip in self._new_ip_list(self.__ip.split(".")):
            t_pool.append(threading.Thread(target=self._ping_action, args=(".".join(ip), result_list)))
        for t in t_pool:
            t.start()
        for t in t_pool:
            t.join()
        return result_list


if __name__ == '__main__':
    result = Ping().start_ping()
    for ip in result:
        print(ip)

运行结果:

192.168.0.1
192.168.0.101
192.168.0.105
192.168.0.100
192.168.0.106

        最终找到了我的路由器 192.168.0.101 

python ping脚本_第1张图片

 

你可能感兴趣的:(python3)