logo Debian Debian Debian-France Debian-Facile Debian-fr.org Forum-Debian.fr Debian ? Communautés logo inclusivité

Debian-facile

Bienvenue sur Debian-Facile, site d'aide pour les nouveaux utilisateurs de Debian.

Vous n'êtes pas identifié(e).

#1 14-06-2012 19:12:35

anthony38
Membre
Distrib. : Bookworm 6.1.69-1
Noyau : Linux 6.1.0-17-amd64
(G)UI : sddm
Inscription : 01-05-2012
Site Web

relancer Openvpn [RESOLU]

Bonjour à tous, j'utilise Openvpn sur Debian Squeeze (6.0.5), j'ai un compte Vyprvpn via Giganews. Donc je me connecte où je veux et cela fonctionne mais, parfois le VPN se déconnecte, alors j'aimerais savoir si l'on peut avec un logiciel ou un script surveillé et relancer en cas de déconnexion. Je possède Webmin si cela peut être utile hmm . Voilà merci d'avance .

Dernière modification par anthony38 (04-07-2012 18:20:17)

Hors ligne

#2 14-06-2012 21:36:56

palmito
Administrateur
Lieu : Dans la boite de gâteau!
Distrib. : bah....
Noyau : heu...
(G)UI : gné?
Inscription : 28-05-2007

Hors ligne

#3 15-06-2012 16:27:16

lenglemetz
Team A DonF
Lieu : Marmande
Distrib. : Testing pour faire mumuse !
Noyau : Celui qui passe !
(G)UI : KDE
Inscription : 29-05-2007
Site Web

Re : relancer Openvpn [RESOLU]

Webmin ne sera pas tres utile, networt manager a un bug a ce niveau et la connection / reconnection automatique ne marche pas :S mais tu peux le contourner par un script

J'ai une solution mais bourrin ! tu te fais un petit dossier dans /etc ( du nom que tu veux ), scripts dans cette exemple, tu crées un fichier ( touch autovpn ) tu colles ça dedans :

#!/usr/bin/env python
"""
Copyright 2011 Domen Kozar. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, this list of
      conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer in the documentation and/or other materials
      provided with the distribution.

THIS SOFTWARE IS PROVIDED BY DOMEN KOZAR ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DOMEN KOZAR OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of DOMEN KOZAR.

USAGE
=====

1) clone gist somewhere (eg. /home/user/autovpn/)
2) add to /etc/rc.local: python /home/user/autovpn/autovpn.py "myvpn" 'Auto homenetwork,Auto worknetwork' >> /var/log/autovpn.log&
3) reboot :-)

CHANGELOG
=========

0.2 (28.01.2012)
----------------

* feature: use logging module
* bug: script would fail if there was no active connection

0.1 (01.01.2012)
----------------

* bug: compatible with NM 0.9, dropped support for 0.8
* feature: specify networks that vpn is not autoconnected

KNOWN ISSUES
============

* it will always use first active network connection

"""
import sys
import logging

from dbus.mainloop.glib import DBusGMainLoop
import dbus
import gobject


logger = logging.getLogger(__name__)
logging.basicConfig(
    level=logging.INFO,
    filename='/var/log/autovpn.log',
    filemode='a',
)


class AutoVPN(object):
    """Solves two jobs, tested with NetworkManager 0.9.x:

    * if VPN connection is not disconnected by user himself, reconnect (configurable max_attempts)
    * on new active network connection, activate VPN

    :param vpn_name: Name of VPN connection that will be used for autovpn
    :param ignore_networks: Comma separated network names in NM that will not force VPN usage
    :param max_attempts: Maximum number of attempts of reconnection VPN session on failures
    :param delay: Miliseconds to wait before reconnecting VPN

    """

    def __init__(self, vpn_name, ignore_networks='', max_attempts=5, delay=5000):
        self.vpn_name = vpn_name
        self.max_attempts = max_attempts
        self.delay = delay
        self.failed_attempts = 0
        self.bus = dbus.SystemBus()
        self.ignore_networks = filter(None, ignore_networks.split(','))
        self.get_network_manager().connect_to_signal("StateChanged", self.onNetworkStateChanged)
        logger.info("Maintaining connection for %s, reattempting up to %d times with %d ms between retries", vpn_name, max_attempts, delay)

    def onNetworkStateChanged(self, state):
        """Handles network status changes and activates the VPN on established connection."""
        logger.debug("Network state changed: %d", state)
        if state == 70:
            self.activate_vpn()

    def onVpnStateChanged(self, state, reason):
        """Handles different VPN status changes and eventually reconnects the VPN."""
        # vpn connected or user disconnected manually?
        if state == 5 or (state == 7 and reason == 2):
            self.failed_attempts = 0
            if state == 5:
                logger.info("VPN %s connected", self.vpn_name)
            else:
                logger.info("User disconnected manually")
            return
        # connection failed or unknown?
        elif state in [6, 7]:
            # reconnect if we haven't reached max_attempts
            if not self.max_attempts or self.failed_attempts < self.max_attempts:
                logger.info("Connection failed, attempting to reconnect")
                self.failed_attempts += 1
                gobject.timeout_add(self.delay, self.activate_vpn)
            else:
                logger.info("Connection failed, exceeded %d max attempts.", self.max_attempts)
                self.failed_attempts = 0

    def get_network_manager(self):
        """Gets the network manager dbus interface."""
        logger.debug("Getting NetworkManager DBUS interface")
        proxy = self.bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
        return dbus.Interface(proxy, 'org.freedesktop.NetworkManager')

    def get_vpn_interface(self, name):
        'Gets the VPN connection interface with the specified name.'
        logger.debug("Getting %s VPN connection DBUS interface", name)
        proxy = self.bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings')
        iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.Settings')
        connections = iface.ListConnections()
        for connection in connections:
            proxy = self.bus.get_object('org.freedesktop.NetworkManager', connection)
            iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.Settings.Connection')
            con_settings = iface.GetSettings()['connection']
            if con_settings['type'] == 'vpn' and con_settings['id'] == name:
                logger.debug("Got %s interface", name)
                return iface
        logger.error("Unable to acquire %s VPN interface. Does it exist?", name)
        return None

    def get_active_connection(self):
        """Gets the dbus interface of the first active
        network connection or returns None.
        """
        logger.debug("Getting active network connection")
        proxy = self.bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
        iface = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')
        active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')
        if len(active_connections) == 0:
            logger.info("No active connections found")
            return None
        logger.info("Found %d active connection(s)", len(active_connections))
        return active_connections[0]

    def activate_vpn(self):
        """Activates the vpn connection."""
        logger.info("Activating %s VPN connection", self.vpn_name)
        vpn_con = self.get_vpn_interface(self.vpn_name)
        active_con = self.get_active_connection()
        if active_con is None:
            return

        # check if we have to ignore vpn
        proxy = self.bus.get_object('org.freedesktop.NetworkManager', active_con)
        con = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties').Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')
        proxy = self.bus.get_object('org.freedesktop.NetworkManager', con)
        settings = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.Settings.Connection').GetSettings()
        if settings['connection']['id'] in self.ignore_networks:
            logger.info("Ignored network connection %s based on settings", settings['connection']['id'])
            return

        # activate vpn and watch for reconnects
        if vpn_con and active_con:
            new_con = self.get_network_manager().ActivateConnection(
                vpn_con,
                dbus.ObjectPath("/"),
                active_con,
            )
            proxy = self.bus.get_object('org.freedesktop.NetworkManager', new_con)
            iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.VPN.Connection')
            iface.connect_to_signal('VpnStateChanged', self.onVpnStateChanged)
            logger.info("VPN %s should be active (soon)", self.vpn_name)


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'usage: autovpn VPN_CONNECTION_NAME <COMMA SEPARATED NAMES OF IGNORABLE NETWORKS>'
        print '-> activates vpn if any network connection is active'
        print '-> and reconnects VPN on failure'
        sys.exit(0)

    # set up the main loop
    DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    # TODO: argparse
    if len(sys.argv) > 2:
        AutoVPN(sys.argv[1], sys.argv[2])
    else:
        AutoVPN(sys.argv[1])
    loop.run()


Un petit chmod +x autovpn

tu colles ça dans /etc/rc.local ( juste avant le exit 0 ) >>           python /etc/scripts/autovpn "NomdetaconnectionVPN" ( pour avoir le nom précis de te connection VPN tu peux faire : 'nmcli con' dans un terminal )

Enjoy !!! mais par contre le vpn ne se connectera pas automatiquement au boot mais une fois accrocher manuellement une première fois il restera même après un retour de veille, pour activer le script il suffit de faire un reboot wink


>< PRO le DonF.dev ¬|¬ STREAM La Team à DonF.me ¬|¬ PERSO Lenglemetz > [Thème] Sujet (état) < • La TeaM à DonF

Hors ligne

#4 23-06-2012 16:08:31

anthony38
Membre
Distrib. : Bookworm 6.1.69-1
Noyau : Linux 6.1.0-17-amd64
(G)UI : sddm
Inscription : 01-05-2012
Site Web

Re : relancer Openvpn [RESOLU]

Salut à tous, et merci de vos réponse !  je test ça ce soir et je vous tien au courant . Merci encore  smile

Hors ligne

#5 24-06-2012 09:57:25

anthony38
Membre
Distrib. : Bookworm 6.1.69-1
Noyau : Linux 6.1.0-17-amd64
(G)UI : sddm
Inscription : 01-05-2012
Site Web

Re : relancer Openvpn [RESOLU]

Bon j'ai testé " Vpnautoconnect  " j'ai réussi à installer que la version 1.0.8 . pour l'instant je sais pas si il marche car, ça n'a pas coupé encore mais, On dirait que ça consomme un peu . Vous l'avez testé vous ?

Hors ligne

#6 24-06-2012 23:06:53

palmito
Administrateur
Lieu : Dans la boite de gâteau!
Distrib. : bah....
Noyau : heu...
(G)UI : gné?
Inscription : 28-05-2007

Re : relancer Openvpn [RESOLU]

salut

Je ne sais pas...je l'ai testé que très rapidement (il ne m'a pas semblé consommé..). Perso j'ai trouvé un vpn qui coupe que très très rarement du coup j'ai abandonné vpnautoconnect et tout les scripts que l'on peut trouver sur le net.

Hors ligne

#7 30-06-2012 18:53:38

anthony38
Membre
Distrib. : Bookworm 6.1.69-1
Noyau : Linux 6.1.0-17-amd64
(G)UI : sddm
Inscription : 01-05-2012
Site Web

Re : relancer Openvpn [RESOLU]

Salut, bon il me convient très bien au final. Dois-je mettre un resolu quelque part ?
une petite question concernant mon openvpn, quand j'allume mon serveur j'ai un écran noir avec tout plein de daemon qui se lance,  arriver sur virtual network private il se stop,  me mes le nom de ma connexion VPN et me demande un nom d'utilisateur et un mot de passe . Comment enlever ceci. Merci encore à vous.


EDIT !!  j'ai trouvais il fallait supprimer le fichier MaConnexionVpn.conf dans /etc/openvpn/  . mais dans ce cas la comment faire pour insérer mon mot de passe dans ce fichier .conf ?

Dernière modification par anthony38 (30-06-2012 19:24:35)

Hors ligne

#8 02-07-2012 07:36:30

paskal
autobahn
Lieu : ailleurs
Inscription : 14-06-2011
Site Web

Re : relancer Openvpn [RESOLU]

Bonjour,

anthony38 a écrit :

Dois-je mettre un résolu quelque part ?


Oui, dans le titre, en éditant ton premier message. smile


I'd love to change the world
But I don't know what to do
So I'll leave it up to you...

logo-sur-fond.png

Hors ligne

Pied de page des forums