介绍
本篇文章给大家分享的是有关使用python怎么编写一个ping命令小程序,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
ping的原理是发送一个ICMP请求包,然后根据目的地址的应答包来判断是否能够和这个主机进行通信。
我们使用python实现,借助于scapy来进行编写程序。
得到scapy.all import * import 时间、结构、随机的 #,编写ping一个包的函数。 时间=def ping_one (dst & # 39; 36.152.44.95& # 39;, ttl_no =, 64年,id_no =, 345年,seq_no =, 5): 时间=start_time 才能;time.time () #,才能将时间转换为二进制序列。 time_to_bytes 才能=,struct.pack(& # 39;在d # 39;, start_time) #,才能进行发送ICMP包,发送出去一个,收回来一个。 ping_one_result 才能=,sr1 (IP (=dst dst ttl =, ttl_no)/ICMP (=seq seq_no, id =, id_no)/time_to_bytes, timeout =, 1, verbose=False) #,才能打印(ping_one_result.show ()) #才能,判断收回来的包是不是ICMP的应答包,和序列号是否相同。 尝试才能: ,,,if ping_one_result.getlayer (& # 39; icmp # 39;) .type ==, 0,以及ping_one_result.getlayer (& # 39; icmp # 39;) .seq ==, seq_no: ,,,,,#,打印(& # 39;进行解析包& # 39;) ,,,,,#,提取IP头部中的源IP地址,也就是我们ping的IP地址。 ,,,,,reply_src_IP =, ping_one_result.getlayer (& # 39; ip # 39;) .src ,,,,,#,提取序列号。 ,,,,,reply_icmp_seq =, ping_one_result.getlayer (& # 39; icmp # 39;) .seq ,,,,,#,提取ttl ,,,,,reply_icmp_ttl =, ping_one_result.getlayer (& # 39; ip # 39;) .ttl ,,,,,#,数据长度等于,数据长度(生),+,垫片长度(填充),+,8字节(ICMP头部长度) ,,,,,if ping_one_result.getlayer(生),!=,没有: ,,,,,,,Raw_length =, len (ping_one_result.getlayer(生).load) ,,,,,其他的: ,,,,,,,Raw_length =0 ,,,,,if ping_one_result.getlayer(填充),!=,没有: ,,,,,,,Padding_length =, len (ping_one_result.getlayer(填充).load) ,,,,,其他的: ,,,,,,,Padding_length =0 ,,,,,#,计算数据长度。 ,,,,,reply_data_length =, Raw_length +, Padding_length + 8 ,,,,,#,取出数据部分,这里的数据部分是我们发送ICMP请求包的时候填入的时间。 ,,,,,reply_data =, ping_one_result.getlayer .load(生) ,,,,,#,定义我们收包的时间。 ,,,,,end_time =, time.time () ,,,,,#,将数据时间部分进行转换。 ,,,,,reply_data_time =, struct.unpack(& # 39;在d # 39;, reply_data) ,,,,,#,然后打印出转换后的类型。 ,,,,,#,打印(类型(reply_data_time)) ,,,,,#,打印(reply_data_time) ,,,,,time_to_pass_ms =, (end_time 安康;reply_data_time [0]), *, 1000 ,,,,,#,(接收时间,安康;发送时间),*,1000为毫秒数为消耗时间的毫秒数 ,,,,,#,打印(time_to_pass_ms) ,,,,,return reply_data_length, reply_src_IP, reply_icmp_seq, reply_icmp_ttl time_to_pass_ms except 才能;Exception  as e: ,,,#,打印出错误。 ,,,#,打印(& # 39;e # 39;,, e) ,,,#,匹配错误是否为NoneType类型。 ,,,if re.match (& # 39;。* NoneType。* & # 39;,, str (e)): ,,,,,印刷(& # 39;错误了& # 39;) ,,,,,#,如果没有回应,就返回没有 ,,,,,return 没有 时间=def 平(dst & # 39; 36.152.44.95& # 39;): #才能,这里其实可以取进程号的,但是我们用随机生成一个数字模拟一下。 时间=id_no 才能;random.randint (0, 65535) #,才能打印(id_no) #才能,然后进行发送5个数据包。 for 才能小姐:拷贝范围(1,6): ,,,#,调平用一个包函数,入参为目的需要平的IP地址.ttl, id,和序列号.seq。 ,,,ping_result =, ping_one (id_no dst, 64,我) ,,,if ping_result !=,没有: ,,,,,印刷(& # 39;% d bytes 得到% s:, icmp_seq=% d ttl=% d 时间=% 4.2 f 女士# 39;,%,(ping_result [0],, ping_result [1],, ping_result [2],, ping_result [3],, ping_result [4])) ,,,: ,,,,,印刷(& # 39;强生# 39;,最终获得=,& # 39;& # 39;,flush =,真的) ,,,#,这里我们暂停一秒。 null null null null使用python怎么编写一个ping命令小程序