A maneira mais simples é usar ping -c4 google.com
para testar sua conexão com a Internet. Se puder chegar além do roteador para qualquer URL, você terá acesso à Internet. Isso pode ser facilmente adaptado a um script que periodicamente pinga um site que você escolhe. Mas eu tenho uma ideia um pouco diferente.
Este é um indicador do painel superior que solicita periodicamente a conexão à Internet. Se a sua conexão à Internet cair, o ícone mudará para um sinal de alerta. Ele usa nomes de ícones padrão, portanto, não é necessário adicionar ícones adicionais.
Salve este como arquivo, verifique se ele tem permissões executáveis com chmod +x interwebs-indicator
(do terminal) ou através do menu do botão direito do mouse no gerenciador de arquivos. Executar manualmente no terminal como
python3 intwerwebs-indicator
ou
./interwebs-indicator
se tiver concedido permissões executáveis.
Você pode fazê-lo iniciar automaticamente no login da GUI , também.
Simples e fácil de usar.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author: Serg Kolo , contact: [email protected]
# Date: November 3rd, 2016
# Purpose: appindicator for testing internet connection
# Tested on: Ubuntu 16.04 LTS
#
#
# Licensed under The MIT License (MIT).
# See included LICENSE file or the notice below.
#
# Copyright © 2016 Sergiy Kolodyazhnyy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import gi
gi.require_version('AppIndicator3', '0.1')
gi.require_version('Notify', '0.7')
from gi.repository import GLib as glib
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Gtk as gtk
from gi.repository import Gio
from gi.repository import Gdk
import urllib.request as urllib2
class InterwebsIdicator(object):
def __init__(self):
self.app = appindicator.Indicator.new(
'interwebs-indicator', "gtk-network",
appindicator.IndicatorCategory.HARDWARE
)
self.app.set_attention_icon('dialog-warning')
#self.app.set_status(appindicator.IndicatorStatus.ACTIVE)
self.make_menu()
self.update()
def add_menu_item(self, menu_obj, item_type, image, label, action, args):
""" dynamic function that can add menu items depending on
the item type and other arguments"""
menu_item, icon = None, None
if item_type is gtk.ImageMenuItem and label:
menu_item = gtk.ImageMenuItem.new_with_label(label)
menu_item.set_always_show_image(True)
if '/' in image:
icon = gtk.Image.new_from_file(image)
else:
icon = gtk.Image.new_from_icon_name(image, 48)
menu_item.set_image(icon)
elif item_type is gtk.ImageMenuItem and not label:
menu_item = gtk.ImageMenuItem()
menu_item.set_always_show_image(True)
if '/' in image:
icon = gtk.Image.new_from_file(image)
else:
icon = gtk.Image.new_from_icon_name(image, 16)
menu_item.set_image(icon)
elif item_type is gtk.MenuItem:
menu_item = gtk.MenuItem(label)
elif item_type is gtk.SeparatorMenuItem:
menu_item = gtk.SeparatorMenuItem()
if action:
menu_item.connect('activate', action, *args)
menu_obj.append(menu_item)
menu_item.show()
def add_submenu(self,top_menu,label):
menuitem = gtk.MenuItem(label)
submenu = gtk.Menu()
menuitem.set_submenu(submenu)
top_menu.append(menuitem)
menuitem.show()
return submenu
def make_menu(self):
self.app_menu = gtk.Menu()
self.add_menu_item(self.app_menu,gtk.ImageMenuItem,'exit','quit',self.quit,[None])
self.app.set_menu(self.app_menu)
def check_connection(self,*args):
try:
url = urllib2.urlopen('http://google.com')
page = url.read()
except urllib2.HTTPError:
print('>>> err:')
self.app.set_status(appindicator.IndicatorStatus.ATTENTION)
#self.app.attention-icon('network-error')
except Exception as e:
print('>>> exception:',e)
else:
print('>>> OK')
self.app.set_status(appindicator.IndicatorStatus.ACTIVE)
self.app.set_icon('network')
def callback(self,*args):
timeout = 5
glib.timeout_add_seconds(timeout, self.update)
def update(self,*args):
self.check_connection()
self.callback()
# General purpose functions
def quit(self,*args):
gtk.main_quit()
def run(self):
""" Launches the indicator """
try:
gtk.main()
except KeyboardInterrupt:
pass
def quit(self, *args):
""" closes indicator """
gtk.main_quit()
def main():
""" defines program entry point """
indicator = InterwebsIdicator()
indicator.run()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
gtk.main_quit()