Created
April 19, 2024 09:59
-
-
Save jenya239/01a1c6e78b55b558b4fce24c7c1c9e32 to your computer and use it in GitHub Desktop.
clear disconnected openvpn3 sessions
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 'active_support/all' | |
class Session | |
FIELDS = [:path, :created, :pid, :owner, :device, :config_name, :session_name, :status] | |
@@sessions = [] | |
attr_accessor(*FIELDS) | |
attr_accessor :id | |
@fields = {} | |
def initialize(section) | |
@@sessions << self | |
@fields = {} | |
lines = section.split("\n").delete_if {|line| line.start_with?('---')} | |
lines.each do |line| | |
process_string(nil, line) | |
end | |
@id = @fields[:path].match(/\w*$/)[0] | |
# p @fields | |
end | |
def field_regex(field) | |
/\s*#{field.to_s.gsub('_', ' ')}:\s*/i | |
end | |
def process_string(parent, str, right = true) | |
return unless str&.strip | |
found = false | |
Session::FIELDS.each do |field| | |
regex = field_regex(field) | |
if str =~ regex | |
parts = str.split(regex) | |
found = true | |
process_string(field, parts[0], false) | |
process_string(field, parts[1], true) | |
break | |
end | |
end | |
if !found && parent && right | |
@fields[parent] = str | |
# p "this is #{parent} = #{str}" | |
end | |
end | |
def connected? | |
@fields[:status].include?('connected') | |
end | |
def disconnect | |
`openvpn3 session-manage --session-path #{@fields[:path]} --disconnect` | |
p "#{@id} disconnected" | |
end | |
def self.sessions | |
@@sessions | |
end | |
def self.clear | |
@@sessions.each do |session| | |
session.disconnect unless session.connected? | |
end | |
end | |
def self.get_list | |
`openvpn3 sessions-list`.split("\n\n").map{ |section| Session.new(section) } | |
end | |
end | |
Session.get_list | |
Session.clear |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment