#!/usr/bin/env ruby # this script could be used as an up/down script for the openvpn client # it parses the dhcp options provided by the openvpn server to update the # resolv.conf file accordingly. # The notify-send command shows a nice popup to notify connecting and # disconnecting. script_type = ENV['script_type'] def osd(message) `notify-send "#{message}"` end if 'up' == script_type puts '[UP] Backup Resolv.conf' `cp /etc/resolv.conf /etc/resolv.conf.ovpn_backup` puts '[UP] Parse dhcp_options:' num = 1; options = [] while true option_key = 'foreign_option_%d' % num num += 1 if ENV.has_key? option_key options << ENV[option_key] if not ENV[option_key].empty? else break end end puts '[UP] dhcp_options: %s' % (options.inspect) puts '[UP] trucate resolv.conf, write nameservers' file = File.open('/etc/resolv.conf', 'w') options.each do |option| if option.match /dhcp-option DNS (.*)$/ file << "nameserver #{$1}\n" end end file.close() osd('OpenVPN connection established') elsif 'down' == script_type puts '[DOWN] Revert Resolv.conf to backup' `cp /etc/resolv.conf.ovpn_backup /etc/resolv.conf` osd('OpenVPN disconnected') end