Created
November 18, 2011 07:53
-
-
Save oinak/1375855 to your computer and use it in GitHub Desktop.
Configure custom vpn's
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require "rubygems" # ruby1.9 doesn't "require" it though | |
require "thor" | |
# The program takes different commands as in git thing style. | |
# At the moment it list avaiable/enable VPN's or sets them. | |
# | |
# Author:: Fernando Martínez (mailto:[email protected]) | |
# Copyright:: Copyright (c) 2010 LCIbérica SL | |
# License:: Distributes under the same terms as Ruby | |
# This class implements the actions using @wycats' Thor | |
# If it is called with no arguments it prints help as with | |
# help command or '-h' switch | |
class Vpn < Thor | |
map "-l" => :list | |
include Thor::Actions | |
include Thor::Shell | |
class_option :path, :type => :string, | |
:aliases => "-p", | |
:default => '/etc/openvpn/', | |
:desc => "Path where OpenVPN configuration files live" | |
class_option :list, :type => :boolean, | |
:aliases => "-l", | |
:desc => "List of avaiable configs (e.g: 'vpn -l -p /usr/local/opnevpn')" | |
# Required by some thor actions | |
def self.source_root #:nodoc: | |
File.dirname(__FILE__) | |
end | |
# Sets sudo only for non-root | |
def self.sudo | |
Process.uid == 0 ? '' : 'sudo' | |
end | |
# Returns PID file cross-plattform compatible full path | |
def self.pid_file(config) | |
"/var/run/openvpn.#{config}.pid" | |
end | |
# Locates openvpn command or exits with error | |
def self.command | |
command = %x{#{Vpn.sudo} which openvpn}.strip | |
abort "Could not find OpenVPN command" if command.empty? | |
command | |
end | |
desc "unset", "Stops OpenVPN execution" | |
def unset | |
run "#{Vpn.sudo} pkill openvpn" | |
end | |
desc "set [CONFIG]", "Start VPN with provided config" | |
def set(config) | |
config_path = options[:path] | |
unset | |
inside config_path, :verbose => false do | |
run "#{Vpn.sudo} #{Vpn.command} --daemon --script-security 2 system --writepid #{Vpn.pid_file(config)} --config #{config_path}#{config}.bak" | |
end | |
end | |
desc "list", "List avaiable configs (e.g: 'vpn list')" | |
def list | |
config_path = options[:path] | |
inside config_path do | |
say " * Avaiable configs:" | |
configs = Dir.entries('.').select{|e| %r{\.(bak|conf)$}=~e} | |
configs.each do |cfg| | |
base_name = cfg.gsub(/.(bak|conf)/,'') | |
if File.exists?( Vpn.pid_file(base_name) ) | |
say_status( 'ON', base_name, :green ) | |
else | |
say_status('off', base_name, :red) | |
end | |
end | |
end | |
end | |
end | |
Vpn.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment