12
from optparse import OptionParser
16
"""Gets routing information from the system.
20
def _hex_to_dec(self, string):
21
"""Returns the integer value of a hexadecimal string s
23
return int(string, 16)
25
def _num_to_dotted_quad(self, number):
26
"""Convert long int to dotted quad string
28
return socket.inet_ntoa(struct.pack("<L", number))
30
def _get_default_gateway_from_proc(self):
31
""""Returns the current default gateway, reading that from /proc
33
logging.debug("Reading default gateway information from /proc")
35
file = open("/proc/net/route")
38
logging.error("Failed to read def gateway from /proc")
41
h = re.compile("\n(?P<interface>\w+)\s+00000000\s+(?P<def_gateway>[\w]+)\s+")
44
if w.group("def_gateway"):
45
return self._num_to_dotted_quad(self._hex_to_dec(w.group("def_gateway")))
47
logging.error("Could not find def gateway info in /proc")
50
logging.error("Could not find def gateway info in /proc")
53
def _get_default_gateway_from_bin_route(self):
54
"""Get default gateway from /sbin/route -n
55
Called by get_default_gateway and is only used if could not get that from /proc
57
logging.debug("Reading default gateway information from route binary")
58
routebin = commands.getstatusoutput("export LANGUAGE=C; /usr/bin/env route -n")
61
logging.error("Error while trying to run route")
64
h = re.compile("\n0.0.0.0\s+(?P<def_gateway>[\w.]+)\s+")
65
w = h.search(routebin[1])
67
def_gateway = w.group("def_gateway")
72
logging.error("Could not find default gateway by running route")
75
def get_hostname(self):
76
return socket.gethostname()
78
def get_default_gateway(self):
79
t1 = self._get_default_gateway_from_proc()
81
t1 = self._get_default_gateway_from_bin_route()
85
def ping(host, count, deadline):
86
command = "ping -q -c %s -w %s %s" % (count, deadline, host)
87
reg = re.compile(r"(\d) received")
90
output = os.popen(command)
91
for line in output.readlines():
92
received = re.findall(reg, line)
94
packets_received = int(received[0])
96
return packets_received
102
usage = "%prog [HOST]"
103
parser = OptionParser(usage=usage)
104
parser.add_option("-c", "--count",
105
default=default_count,
107
help="Number of packets to send.")
108
parser.add_option("-d", "--deadline",
109
default=default_delay,
111
help="Timeouts in seconds.")
112
(options, args) = parser.parse_args(args)
118
host = route.get_default_gateway()
120
received_packets = ping(host, options.count, options.deadline)
122
if received_packets == 0:
123
print "No Internet connection"
124
elif received_packets != options.count:
125
print "Connection established lost a packet"
127
print "Internet connection fully established"
131
if __name__ == "__main__":
132
sys.exit(main(sys.argv[1:]))