Déconnexion intempestive de client OpenVPN ?

Tout ce qui se rapporte à l'informatique en général
Répondre
Avatar du membre
Guepi
Administrateur
Administrateur
Messages : 518
Enregistré le : 28 novembre 2009, 00:55
Localisation : Lille

Déconnexion intempestive de client OpenVPN ?

Message par Guepi »

Ceci est probablement la solution !

Je suis tombé sur ce code sur le site ubuntu-fr.org.

Code : Tout sélectionner

#--------------------------------------------------
#!/bin/bash
# auteur: alan524 --  06 Avril 2014
#
# surveillance de la liaison vpn 
#   -> arret du programme de transfert si le vpn se déconnecte
#   -> essai périodique de reconnexion vpn avec relance prpgramme
#
#--------------------------------------------------
# ce programme est basé sur la note publiée ci-après:
#  --- cf  http://ubuntuforums.org/showthread.php?t=1941380&page=2
#--------------------------------------------------
#
#
#
#Note: can not use a string to represent the program because the name 
#of the string will be stored as the job name instead of the program name.
#
	function lanceprocess()
	{
#myprogram01 &			# replace myprogram01 by program name 
#qbittorrent &			# 
transmission-gtk &

#programID=`pidof myprogram01`	# replace myprogram01 by program name 
#programID=$(pidof qbittorrent)	# 
programID=$(pidof transmission-gtk)	# 
	}
#
#nameVPN="myconnexionVPN"	# replace myconnexionVPN by vpn name
#nameVPN="vyprvpn-PPTP"		# 
nameVPN="mullvad_linux"		# 
#
#myIPext="xxx.xxx.xxx.xxx"	# replace xxx par mon adresse ip externe (provider)
myIPext="12.345.67.89"
#-----------------
#
#
#
#==== Test etat VPN ====
	function testVPN()
	#if vpn connected  vpn=1
	{
	connected=$(nmcli con status | awk -v nVPN=$nameVPN '{if($1 == nVPN) {print $5;}; }')

	if [ "$connected" = "oui" ] || [ "$connected" = "yes" ]; then 
		vpnuuid=$(nmcli con status | awk -v nVPN=$nameVPN '{if($1 == nVPN) {print $2;}; }')
		vpn=1
		else
		vpn=0
	fi
	}

#==== Test etat VPN ====
	function rwaitIPext()
	{
	IPext=$myIPext
	vpn=0
	testVPN

	while [ "$IPext" = "$myIPext" ]
	do
	   while [ "$vpn" = 0 ]
	    do
	      sleep 5
	      testVPN
	   done
	   nmcli -p con up uuid $vpnuuid		#Retry the VPN
	   # essai sur un 2eme site si le premier est out
	   IPext=$(wget -qO- www.adresseip.com | grep -Eo '[0-9]{1,3}(\.[0-9]{1,3}){3}' | awk 'BEGIN {flag = 0}{if (flag == 0){print $1; flag = 1;}}')
	   if [ "$IPext" = "" ]; then 
	   IPext=$(wget -qO- www.ipchicken.com | grep -Eo '[0-9]{1,3}(\.[0-9]{1,3}){3}' | awk 'BEGIN {flag = 0}{if (flag == 0){print $1; flag = 1;}}')
	   fi
	   if [ "$IPext" = "" ]; then 
		IPext=$myIPext
	   fi
	   if [ "$IPext" != "$myIPext" ]; then 
	 	break
	   fi
	sleep 10		# attente que le vpn soit effectif
	done
	}


#==== VPN nok ====
	function nokVPN()
	{
	date
	echo "VPN disconnected. Stoping VPN dependancies"
	if [ "$programID" != 0 ]; then
	 kill -SIGKILL $programID	#Connection lost stop the VPN dependancy.
	fi
	echo "VPN dependancies stopped."
	jobs
	rwaitIPext			#  attente reconnexion
	echo "VPN dependencies restarted."
	lanceprocess			# relance du process
	date
	}

#==== VPN OK ====
	function okVPN()
	{
	sleep 1				# surveillance périodique 1 seconde
	}
#===================
#==== Main Proc ====
#===================
#
#
programID=0
vpn=0
vpnuuid=''
IPext=''

	date
	echo "-- lancement torrent --"
	echo "-- Activation surveillance VPN --"

	rwaitIPext			# connexion OK?
	lanceprocess

while true; do
	testVPN
	if [ $vpn = 1 ]; then 
		okVPN 
			else 
		nokVPN 
	fi
done
Bon, dans les choses sur lesquelles il faut être bien vigilant :
  • nommer sa connexion sans espace
  • obtenir son adresse ip externe "avant" de se connecter à son VPN (via le site http://www.adresseip.com
  • renseigner le nom du programme à monitorer (ici, par exemple, c'est transmission-gtk)
Dans mon cas, j'ai encore des erreurs, mais au fur et à mesure, je vais déboguer un peu ce script et je le mettrais à jour.

Pour information, je suis sur une version Ubuntu 14.04 LTS.
Avatar du membre
Elgrande71
Administrateur
Administrateur
Messages : 1768
Enregistré le : 29 février 2008, 10:24
Localisation : Le Creusot
Contact :

Re: Déconnexion intempestive de client OpenVPN ?

Message par Elgrande71 »

Je vois que l'on s'amuse bien Guepi .
Tiens nous au courant de tes avancées . :coucou:
Debian - Distribution GNU/Linux de référence
Parabola GNU/Linux - Distribution GNU/Linux Libre
MX Linux
Jabber elgrande71@chapril.org
Avatar du membre
Guepi
Administrateur
Administrateur
Messages : 518
Enregistré le : 28 novembre 2009, 00:55
Localisation : Lille

Re: Déconnexion intempestive de client OpenVPN ?

Message par Guepi »

Apparemment, la commande pidof est appelée à disparaître.
Il convient de la remplacer par pgrep.

Voici le script dans la dernière version diffusée sur le forum précédemment cité.

Code : Tout sélectionner

#!/bin/bash
# This script monitors a VPN connection and stops a program when that connection
# is lost, then restarts that program when the connecton is re-established.

#Attempt an initial connection until connected
#------------------------------------------------------------------------------
# Set progID to whatever program you need stopped when VPN fails.
progID='transmission-gtk'

# Get the UUID of the only vpn on the system.
# Note if you have more then one VPN configured on your system, you will need to
# comment out line 14 and uncomment line 15 replacing "your-vpn-name-here" with 
# the name of the vpn you want to use with this script.
uuid_str=`nmcli -t -f TYPE,UUID con list |grep vpn |sed s/vpn://g`
# `nmcli -t -f NAME,UUID con list |grep your-vpn-name-here |sed s/your-vpn-name-here://g`

function connectVPN()
{
			# If the connection is just started or lost, try to reconnect then break out once connected.
			while :
				do
	  		connected=`nmcli -t -f VPN con status |grep yes`      #Store the current state of the VPN connection.
				if [ "$connected" = "yes" ]; then
#					echo "VPN connection active"
					break
				else
					echo "Attempting VPN connection in 5 seconds."       	   
					sleep 5		#Give the VPN time to recover so we don't abuse it with reconnection requests.
					nmcli -p con up uuid $uuid_str		#Retry the VPN
				fi
			done
}
connectVPN
sleep 5				#Give the connection time to stabelize before continueing.


# Run the program and get its process ID number.
#------------------------------------------------------------------------------
# Note: Here a string can not be used to represent the program because the name
# of the string will be stored as the job name instead of the program name. So 
# instead a variable is used to store the name of the program (see line 8).
$progID &
sleep 5
btID=`pgrep $progID`	#changed from 'pidof' because 'pidof' quit working.
sleep 2


date
#Monitor the connection for discconnections and secure VPN dependancies.
#------------------------------------------------------------------------------
while true; do
	vpnstring=$(nmcli -t -f VPN con status|grep -c yes)		#Define a string to test, 0 = no connection, 1 = connected.

	case $vpnstring in				#Test the connection string.
		"0")
	    date
			echo "VPN disconnected. Stoping VPN dependancies"
			kill -SIGSTOP $btID		#Connection lost stop the VPN dependancy.
			echo "VPN dependancies stopped."
			jobs

			connectVPN
			echo "VPN dependencies restarted."		#Placed here so it wont be endlessly repeated in the outer loop.
			date
	;;
		"1")
			kill -SIGCONT $btID
	;;
	esac

sleep 5
done
A noter que dans cette version, il n'est pas besoin de nommer spécifiquement la connexion VPN, du moment où il n'y en a qu'une sur la machine.

Mon problème est le suivant :
Attempting VPN connection in 5 seconds.
connection VPN activée avec succès (chemin D-Bus actif : /org/freedesktop/NetworkManager/ActiveConnection/1)
connection VPN activée avec succès (chemin D-Bus actif : /org/freedesktop/NetworkManager/ActiveConnection/1)

(process:3997): GLib-CRITICAL **: Source ID 71 was not found when attempting to remove it
Attempting VPN connection in 5 seconds.
Lorsque je lance le script, il active bien le VPN, mais il y a une erreur critique, liée à Glib.
Je pense qu'il s'agit de l'appel à l'application transmission-gtk qui échoue.
Avatar du membre
Guepi
Administrateur
Administrateur
Messages : 518
Enregistré le : 28 novembre 2009, 00:55
Localisation : Lille

Re: Déconnexion intempestive de client OpenVPN ?

Message par Guepi »

Donc, j'ai finalement résolu mes soucis.
  1. le retour de la commande nmcli est francisé, donc c'est "oui" et non pas "yes".
  2. La commande pgrep fonctionne bizarrement : elle ne trouve pas l'application "transmission-gtk", mais trouve l'application qui commence par "transmission-gt". On corrige en "forçant" la commande à prendre la chaîne entière avec un pgrep -f.
Voici le script complet en question.

Code : Tout sélectionner

#!/bin/bash
# This script monitors a VPN connection and stops a program when that connection
# is lost, then restarts that program when the connecton is re-established.

#Attmept an initial connection until connected
#------------------------------------------------------------------------------
# Set progID to whatever program you need stopped when VPN fails.
progID='transmission-gtk'

# Get the UUID of the only vpn on the system.
# Note if you have more then one VPN configured on your system, you will need to
# comment out line 14 and uncomment line 15 replacing "your-vpn-name-here" with 
# the name of the vpn you want to use with this script.
uuid_str=`nmcli -t -f TYPE,UUID con list |grep vpn |sed s/vpn://g`
# `nmcli -t -f NAME,UUID con list |grep your-vpn-name-here |sed s/your-vpn-name-here://g`

function connectVPN()
{
			# If the connection is just started or lost, try to reconnect then break out once connected.
			while :
				do
	  		connected=`nmcli -t -f VPN con status |grep oui`      #Store the current state of the VPN connection.
				if [ "$connected" = "oui" ]; then
#					echo "VPN connection active"
					break
				else
					echo "Tentative de connexion au VPN dans 5 secondes."       	   
					sleep 5		#Give the VPN time to recover so we don't abuse it with reconnection requests.
					nmcli -p con up uuid $uuid_str		#Retry the VPN
				fi
			done
}
connectVPN
sleep 5				#Give the connection time to stabelize before continueing.


# Run the program and get its process ID number.
#------------------------------------------------------------------------------
# Note: Here a string can not be used to represent the program because the name
# of the string will be stored as the job name instead of the program name. So 
# instead a variable is used to store the name of the program (see line 8).
$progID &
sleep 5
btID=`pgrep -f $progID`	#changed from 'pidof' because 'pidof' quit working.
sleep 2


date
#Monitor the connection for discconnections and secure VPN dependancies.
#------------------------------------------------------------------------------
while true; do
	vpnstring=$(nmcli -t -f VPN con status|grep -c oui)		#Define a string to test, 0 = no connection, 1 = connected.

	case $vpnstring in				#Test the connection string.
		"0")
	    date
			echo "Le VPN est déconnecté. On stoppe les dépendances."
			kill -SIGSTOP $btID		#Connection lost stop the VPN dependancy.
			echo "Les dépendances sont stoppées."
			jobs

			connectVPN
			echo "Les dépendances sont relancées."		#Placed here so it wont be endlessly repeated in the outer loop.
			date
	;;
		"1")
			kill -SIGCONT $btID
	;;
	esac

sleep 5
done
Avatar du membre
Elgrande71
Administrateur
Administrateur
Messages : 1768
Enregistré le : 29 février 2008, 10:24
Localisation : Le Creusot
Contact :

Re: Déconnexion intempestive de client OpenVPN ?

Message par Elgrande71 »

Merci pour ton retour Guepi . :jap:
Il faut effectivement penser au piège de la francisation , pas évident .
Debian - Distribution GNU/Linux de référence
Parabola GNU/Linux - Distribution GNU/Linux Libre
MX Linux
Jabber elgrande71@chapril.org
Répondre