1. 程式人生 > >python判斷網路是否通

python判斷網路是否通

提供兩種方法:

netstats.py

# -*- coding: gbk -*-
import myarp
import os
class netStatus:
    def internet_on(self,ip="192.168.150.1"):
        os.system("arp -d 192.168.150.1")
        if myarp.arp_resolve(ip, 0) == 0:   #使用ARP ping的方法
            return True
        else:
            return False

    def ping_netCheck
(self, ip):
#直接ping的方法 os.system("arp -d 192.168.150.1") cmd = "ping " +str(ip) + " -n 2" exit_code = os.system(cmd) if exit_code: return False return True if __name__ == "__main__": net = netStatus() print net.ping_netCheck("192.168.150.2"
)

myarp.py(這個是從ARP模組改來的)

"""
ARP / RARP module (version 1.0 rev 9/24/2011) for Python 2.7
Copyright (c) 2011 Andreas Urbanski.
Contact the me via e-mail: [email protected]

This module is a collection of functions to send out ARP (or RARP) queries
and replies, resolve physical addresses associated with specific ips and
to convert mac and ip addresses to different representation formats. It
also allows you to send out raw ethernet frames of your preferred protocol
type. DESIGNED FOR USE ON WINDOWS.

NOTE: Some functions in this module use winpcap for windows. Please make
sure that wpcap.dll is present in your system to use them.

LICENSING:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>
"""
__all__ = ['showhelp', 'find_device', 'open_device', 'close_device', 'send_raw', 'multisend_raw', 'arp_resolve', 'arp_reply', 'rarp_reply', 'mac_straddr', 'ip_straddr', 'ARP_REQUEST', 'ARP_REPLY', 'RARP_REQUEST', 'RARP_REPLY', 'FRAME_SAMPLE'] """ Set this to True you wish to see warning messages """ __warnings__ = False from ctypes import * import socket import struct import time FRAME_SAMPLE = """ Sample ARP frame +-----------------+------------------------+ | Destination MAC | Source MAC | +-----------------+------------------------+ | \\x08\\x06 (arp) | \\x00\\x01 (ethernet) | +-----------------+------------------------+ | \\x08\\x00 (internet protocol) | +------------------------------------------+ | \\x06\\x04 (hardware size & protocol size) | +------------------------------------------+ | \\x00\\x02 (type: arp reply) | +------------+-----------+-----------------+ | Source MAC | Source IP | Destination MAC | +------------+---+-------+-----------------+ | Destination IP | ... Frame Length: 42 ... +----------------+ """ """ Frame header bytes """ ARP_REQUEST = "\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01" ARP_REPLY = "\x08\x06\x00\x01\x08\x00\x06\x04\x00\x02" RARP_REQUEST = "\x80\x35\x00\x01\x08\x00\x06\x04\x00\x03" RARP_REPLY = "\x80\x35\x00\x01\x08\x00\x06\x04\x00\x04" """ Defines """ ARP_LENGTH = 42 RARP_LENGTH = 42 DEFAULT = 0 """ Look for wpcap.dll """ try: wpcap = cdll.wpcap except WindowsError: print "Error loading wpcap.dll! Ensure that winpcap is properly installed." """ Loading Windows system libraries should not be a problem """ try: iphlpapi = windll.Iphlpapi ws2_32 = windll.ws2_32 except WindowsError: """ Should it still fail """ print "Error loading windows system libraries!" """ Import functions """ if wpcap: """ Looks up for devices """ pcap_lookupdev = wpcap.pcap_lookupdev """ Opens a device instance """ popen_live = wpcap.pcap_open_live """ Sends raw ethernet frames """ pcap_sendpacket = wpcap.pcap_sendpacket """ Close and cleanup """ pcap_close = wpcap.pcap_close """ Find the first device available for use. If this fails to retrieve the preferred network interface identifier, disable all other interfaces and it should work.""" def find_device(): errbuf = create_string_buffer(256) device = c_void_p device = pcap_lookupdev(errbuf) return device """ Get the handle to a network device. """ def open_device(device=DEFAULT): errbuf = create_string_buffer(256) if device == DEFAULT: device = find_device() """ Get a handle to the ethernet device """ eth = popen_live(device, 4096, 1, 1000, errbuf) return eth """ Close the device handle """ def close_device(device): pcap_close(device) """ Send a raw ethernet frame """ def send_raw(device, packet): if not pcap_sendpacket(device, packet, len(packet)): return len(packet) """ Send a list of packets at the specified interval """ def multisend_raw(device, packets=[], interval=0): """ Bytes sent """ sent = 0 for p in packets: sent += len(p) send_raw(device, p) time.sleep(interval) """ Return the number of bytes sent""" return sent """ Resolve the mac address associated with the destination ip address""" def arp_resolve(destination, strformat=True, source=None): mac_addr = (c_ulong * 2)() addr_len = c_ulong(6) dest_ip = ws2_32.inet_addr(destination) if not source: src_ip = ws2_32.inet_addr(socket.gethostbyname(socket.gethostname())) else: src_ip = ws2_32.inet_addr(source) """ Iphlpapi SendARP prototype DWORD SendARP( __in IPAddr DestIP, __in IPAddr SrcIP, __out PULONG pMacAddr, __inout PULONG PhyAddrLen ); """ error = iphlpapi.SendARP(dest_ip, src_ip, byref(mac_addr), byref(addr_len)) return error """ Send a (gratuitous) ARP reply """ def arp_reply(dest_ip, dest_mac, src_ip, src_mac): """ Test input formats """ if dest_ip.find('.') != -1: dest_ip = ip_straddr(dest_ip) if src_ip.find('.') != -1: src_ip = ip_straddr(src_ip) """ Craft the arp packet """ arp_packet = dest_mac + src_mac + ARP_REPLY + src_mac + src_ip + \ dest_mac + dest_ip if len(arp_packet) != ARP_LENGTH: return -1 return send_raw(open_device(), arp_packet) """ Include RARP for consistency :)""" def rarp_reply(dest_ip, dest_mac, src_ip, src_mac): """ Test input formats """ if dest_ip.find('.') != -1: dest_ip = ip_straddr(dest_ip) if src_ip.find('.') != -1: src_ip = ip_straddr(src_ip) """ Craft the rarp packet """ rarp_packet = dest_mac + src_mac + RARP_REPLY + src_mac + src_ip + \ src_mac + src_ip if len(rarp_packet) != RARP_LENGTH: return -1 return send_raw(open_device(), rarp_packet) """ Convert c_ulong*2 to a hexadecimal string or a printable ascii string delimited by the 3rd parameter""" def mac_straddr(mac, printable=False, delimiter=None): """ Expect a list of length 2 returned by arp_query """ if len(mac) != 2: return -1 if printable: if delimiter: m = "" for c in mac_straddr(mac): m += "%02x" % ord(c) + delimiter return m.rstrip(delimiter) return repr(mac_straddr(mac)).strip("\'") return struct.pack("L", mac[0]) + struct.pack("H", mac[1]) """ Convert address in an ip dotted decimal format to a hexadecimal string """ def ip_straddr(ip, printable=False): ip_l = ip.split(".") if len(ip_l) != 4: return -1 if printable: return repr(ip_straddr(ip)).strip("\'") return struct.pack( "BBBB", int(ip_l[0]), int(ip_l[1]), int(ip_l[2]), int(ip_l[3]) ) def showhelp(): helpmsg = """ARP MODULE HELP (Press ENTER for more or CTRL-C to break) Constants: Graphical representation of an ARP frame FRAME_SAMPLE Headers for crafting ARP / RARP packets ARP_REQUEST, ARP_REPLY, RARP_REQUEST, RARP_REPLY Other ARP_LENGTH, RARP_LENGTH, DEFAULT Functions: find_device() - Returns an identifier to the first available network interface. open_device(device=DEFAULT) - Returns a handle to an available network device. close_device() - Close the previously opened handle. send_raw(device, packet) - Send a raw ethernet frame. Returns the number of bytes sent. multisend_raw(device, packetlist=[], interval=0) - Send multiple packets across a network at the specified interval. Returns the number of bytes sent. arp_resolve(destination, strformat=True, source=None) - Returns the mac address associated with the ip specified by 'destination'. The destination ip is supplied in dotted decimal string format. strformat parameter specifies whether the return value is in a hexadecimal string format or in list format (c_ulong*2) which can further be formatted using the 'mac_straddr' function (see below). 'source' specifies the ip address of the sender, also supplied in dotted decimal string format. arp_reply(dest_ip, dest_mac, src_ip, src_mac) - Send gratuitous ARP replies. This can be used for ARP spoofing if the parameters are chosen correctly. dest_ip is the destination ip in either dotted decimal string format or hexadecimal string format (returned by 'ip_straddr'). dest_mac is the destination mac address and must be in hexadecimal string format. If 'arp_resolve' is used with strformat=True the return value can be used directly. src_ip specifies the ip address of the sender and src_mac the mac address of the sender. rarp_reply(dest_ip, dest_mac, src_ip, src_mac) - Send gratuitous RARP replies. Operates similar to 'arp_reply'. mac_straddr(mac, printable=False, delimiter=None) - Convert a mac address in list format (c_ulong*2) to normal hexadecimal string format or printable format. Alternatively a delimiter can be specified for printable formats, e.g ':' for ff:ff:ff:ff:ff:ff. ip_straddr(ip, printable=False) - Convert an ip address in dotted decimal string format to hexadecimal string format. Alternatively this function can output a printable representation of the hex string format. """ for line in helpmsg.split('\n'): print line, raw_input('') if __name__ == "__main__": """ Test the module by sending an ARP query """ ip = "10.0.0.8" result = arp_resolve(ip, 0) print ip, "is at", mac_straddr(result, 1, ":")

相關推薦

python判斷網路是否

提供兩種方法: netstats.py # -*- coding: gbk -*- import myarp import os class netStatus: def internet_on(self,ip="192.168.150.1"):

python 判斷網路是否暢通

#!/usr/bin/env python #coding=utf8 import os  def fCheckNet(ip): cmd = 'ping ' + ip + " -c 2 >/dev/null 2>&1"temp = 0if StartMo

Python判斷telnet不通

這個跟ping那個差不多,ping的那個指令碼就是通過這個改了下,大體一致,不過telnet的不需要判斷返回的字串。快一些 這裡具體需要telnet的ip是需要自己向定義好的陣列中寫的 我這裡加了一個定時,是7200秒,也就是2小時 行了,上程式碼吧: #!/usr/b

簡單的python判斷基偶數練習

一個 pytho 程序 color ont style 奇數 log code #!/usr/bin/env python# Author:William Huangnum = int(input(‘please input your number:‘)) # 用int(

python——判斷、循環語句

生成 多重 一個 執行 判斷 列表 list 優秀 循環語句 簡單判斷語句:if… 一重判斷語句:if…else… 多重判斷語句:if elif else… Score=input(“請輸入你的分數”) Score=int(score) If score&

python判斷一個對象是否可叠代

span font false rom size iterable print 對象 方法 如何判斷一個對象是可叠代對象? 方法是通過collections模塊的Iterable類型判斷: >>> from collections import

通過python判斷質數

內存問題 cnblogs 質數 演示 range 是不是 Coding code 自然數 #!/usr/bin/env python3 #-*- coding:utf-8 -*- ‘‘‘ 質數,只能被1和自己整除的自然數 在數學上,如果一個數不能被從2到該數字開根數之間

python - 判斷是否為正小數和正整數

urn logs str 是否 check 進行 count code log 判斷輸入的金額是否為正整數和正小數 def check_float(string): #支付時,輸入的金額可能是小數,也可能是整數 s = str(string) if

Python判斷用戶登錄狀態,並返回結果

sed 成功 http gif 技術分享 user 狀態 and == username = "Anker" passward = "Abc123" number =2 for i in range(1,4,1): _username = input("use

python判斷字符串,str函數isdigit、isdecimal、isnumeric的區別

字符串 4.0 eric 8.0 ssp err must isa isn s為字符串s.isalnum() 所有字符都是數字或者字母s.isalpha() 所有字符都是字母s.isdigit() 所有字符都是數字s.islower() 所有字符都是小寫s.isupper(

python判斷兩個list包含關系

nbsp 判斷 span bsp pan 包含 spa num list a = [1,2] b = [1,2,3] c = [0, 1] set(b) > set(a) set(b) > set(c) python判斷兩個list包含關系

第四天:python判斷語句和循環語句

python一、判斷語句<1>開發中的判斷場景密碼判斷重要日期判斷 if 今天是周六或者周日: 約妹子 if 今天是情人節: 買玫瑰 if 今天發工資: 先還信用卡的錢 if 有剩余:

Python 判斷閏年,判斷日期是當前年的第幾天

也有 www 方法 uno 判斷閏年 style http sum pre http://www.cnblogs.com/vamei/archive/2012/07/19/2600135.html Python小題目 針對快速教程 作業答案 寫一個程序,判斷2008年是

Python 判斷是否為質數或素數

span mil 根據 inpu 自然數 執行 一個數 input round 一個大於1的自然數,除了1和它本身外,不能被其他自然數(質數)整除(2, 3, 5, 7等),換句話說就是該數除了1和它本身以外不再有其他的因數。 首先我們來第一個傳統的判斷思路: def ha

python判斷一個單詞是否為有效的英文單詞?——三種方法

eas www. cal ges art etc code port href For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant. Ther

python 判斷文件和文件夾是否存在的方法 和一些文件常用操作符

dir 判斷 是否 als import 文件 paths 方法 blog 1、判斷文件和文件夾是否存在及創建 import os #os.path.exists(dir_path/file_path) 判斷內容是否存在 >>>os.pat

Python - 判斷list是否為空

str 判斷 存在 emp col lis list pos python Python中判斷list是否為空有以下兩種方式: 方式一: 1 list_temp = [] 2 if len(list_temp): 3 # 存在值即為真 4 else: 5

python 判斷一個數為?

class OS color bsp body dig ins pos 字符 1. 判斷一個變量是否數字(整數、浮點數)? 1 instance(‘a‘, (int, long, float)) 2 3 True 4 5 6 isinstance(‘a‘, (int

Python判斷合數、質數

其他 編寫 pos 布爾 一個 pre 新的 序列 圖片 首先明確合數和質數的概念 合數:自然數中除了能被1和本身整除之外,還能被其他的數整除的數。(4,6,9,10...) 1 def heshu(m): 2 list_a = [] 3 for i in

python判斷字符串開頭、結尾

post clas 字符 去除 blog sta log 之前 nbsp python判斷的開頭結尾有快捷方法如下: 1、判斷開頭:  string.startswith("目標字符") 2、判斷結尾: string.endswith("目標字符") 返回 Tr