[PYTHON]Python3中实现fping类似的功能

标签: python

实际上python中有fping模块,只是想要实现类似的功能,并且可以根据前几天所做的脚本把想要的数据插入到数据库中

1. 需要两个成熟的模块IPy和ping3

IPy为python中处理ip地址的模块;

ping3是python3中使用icmp协议达到ping同样功能的模块,当前最新版本1.0.0中该模块中verbose_ping功能有一处需要修改,否则无法获取到争取的返回值,下面会提出。


2.想要实现的功能:

检测IP是否在线,记录到数据库中(对!又是写入数据库),然后在网页中展现出当前有哪些IP地址存活哪些可以使用(以后做,以后做,以后做)。

优化(to do):

a. 其实可以用多线程来实现,但是要根据输入的子网掩码来判断IP数量然后把ip发送到不同的线程中去,有思路但是暂时不会实现T^T

b. 每次写入前查询是否存在该ip,存在则更新不存在则插入;

c. 反查dns,查询是否有域名并写入数据库。



3. ping3.py需要修改的部分:

原代码第127行开始:


def verbose_ping(dest_addr, timeout=4, count=4):
    """
    Send pings to destination address with the given timeout and display the result.

    Args:
        dest_addr: Str. The destination address. Ex. "192.168.1.1"/"example.com"
        timeout: Int. Timeout in seconds. Default is 4s, same as Windows CMD.
        count: Int. How many pings should be sent. Default is 4, same as Windows CMD.

    Returns:
        Formatted ping results printed.
    """
    for i in range(count):
        print("ping '{}' ... ".format(dest_addr), end='')
        try:
            delay = ping(dest_addr, timeout)
        except socket.gaierror as e:
            print("Failed. (socket error: '{}')".format(e[1]))
            break

        if delay is None:
            print("Timeout > {}s".format(timeout))
        else:
            delay = delay * 1000
            print("{}ms".format(int(delay)))
        print


修改后的代码:


def verbose_ping(dest_addr, timeout=4, count=4):
    """
    Send pings to destination address with the given timeout and display the result.

    Args:
        dest_addr: Str. The destination address. Ex. "192.168.1.1"/"example.com"
        timeout: Int. Timeout in seconds. Default is 4s, same as Windows CMD.
        count: Int. How many pings should be sent. Default is 4, same as Windows CMD.

    Returns:
        Formatted ping results printed.
    """
    for i in range(count):
        print("ping '{}' ... ".format(dest_addr), end='')
        try:
            delay = ping(dest_addr, timeout)
        except socket.gaierror as e:
            print("Failed. (socket error: '{}')".format(e[1]))
            break

        if delay is None:
            print("Timeout > {}s".format(timeout))
            return False
        else:
            delay = delay * 1000
            print("{}ms".format(int(delay)))
            return True


修改后如果ping通ip地址的话,会返回True,ping不通则会返回False。

4. 修改完成后是时候展现我自己的代码了:


# -*- coding : utf8 -*-
import IPy, ping3, mysql.connector
#ip = IPy.IP('172.18.1.0/255.255.255.0')
#print (ip.len())
#for i in ip:
#    status = ping3.verbose_ping(str(i), count = 1)
#    print (status)


ping_config = {
    'host': '',
    'user': 'zhangky',
    'password': '',
    'port': 3306,
    'database': 'python',
    'charset': 'utf8'
}


def fun_mysql(ip, status):
    insert_cmd = 'insert into pingstatus(ip,status) values(%s, %s)'
    param = (ip, status)
    try:
        conn = mysql.connector.connect(**ping_config)
    except mysql.connector.Error as error:
        print('连接失败!', format(error))
    cursor = conn.cursor()
    try:
        cursor.execute(insert_cmd,param)
        conn.commit()                           
    except mysql.connector.Error as error:
        print('连接失败!', format(error))
    finally:
        cursor.close()
        conn.close()


def fun_ping(ip, mask):
    print(ip + '/' + mask)
    iplist = IPy.IP(ip + '/' + mask)
    for ips in iplist:
        ipping = ping3.verbose_ping(str(ips), count = 1, timeout=2)
        fun_mysql(ip=str(ips), status=str(ipping))


ip = input('请输入IP地址  :')
mask = input('请输入子网掩码:')
ipstatus = str(fun_ping(ip=ip,mask=mask))
print (ipstatus)












版权所有:《Hoiwan's 》 => 《[PYTHON]Python3中实现fping类似的功能
本文地址:http://ihoiwan.com/?post=51
除非注明,文章均为 《Hoiwan's 》 原创,欢迎转载!转载请注明本文地址,谢谢。

评论:

Hoiwan
2018-01-19 18:20
curl -I -m 10 -o /dev/null -s -w %{http_code} 'www.baidu.com'

发表评论: