Created
December 16, 2015 16:21
-
-
Save u8sand/6f9ea1ae711a0f0e6263 to your computer and use it in GitHub Desktop.
A simple and easy script to convert to/from open vpn's embedded format (ovpn)
This file contains 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
#!/bin/python | |
import argparse | |
import re | |
parser = argparse.ArgumentParser(description='Convert to and from ovpn files') | |
parser.add_argument('file', type=str, help='the .config or the .ovpn') | |
args = parser.parse_args() | |
m = re.match(r'(.*)\.(ovpn|conf)', args.file) | |
if not m: | |
print('File must be either .ovpn or .con') | |
exit() | |
r = open(args.file, 'r') | |
fname, fext = m.groups() | |
if fext == 'conf': | |
f = re.compile(r'(ca|cert|key|tls-auth) ([^ \n]*|"[^\n]")( \d)?( *(#.*)?)') | |
w = open('%s.ovpn' % (fname), 'w') | |
for l in r.readlines(): | |
m = f.match(l) | |
if not m: | |
w.write(l) | |
else: | |
t = m.group(1) | |
fn = m.group(2) | |
if t == 'tls-auth': | |
d = m.group(3) | |
w.write('key-direction %s\n' % (d)) | |
c = m.group(4) or '' | |
rr = open(fn, 'r') | |
w.write('<%s>%s\n%s</%s>\n' % (t, c, ''.join(rr.readlines()), t)) | |
rr.close() | |
w.close() | |
elif fext == 'ovpn': | |
nname = { | |
'ca': 'ca.crt', | |
'cert': '%s.crt' % (fname), | |
'key': '%s.key' % (fname), | |
'tls-auth': 'ta.key' | |
} | |
f = re.compile(r'</?(ca|cert|key|tls-auth)>( *(#.*)?)') | |
fk = re.compile(r'key-direction (\d) *(#.*)?') | |
tt, td, tc = None, None, None | |
kt, kc, kw = None, None, None | |
w = open('%s.conf' % (fname), 'w') | |
for l in r.readlines(): | |
m = f.match(l) | |
if not m: # cert definition? | |
if kt: # writing a cert? | |
kw.write(l) | |
else: # writing config | |
m = fk.match(l) | |
if m: # key-direction? | |
td = m.group(1) # save | |
else: # writing conf | |
w.write(l) | |
else: # cert definition. | |
if kt: # writing a cert--flush | |
if t == 'tls-auth': | |
tt, tc = kt, kc | |
else: | |
w.write('%s %s%s\n' % (kt, nname[t], kc)) | |
kw.close() | |
kt, kc = None, None | |
else: # starting net cert definition | |
t = m.group(1) | |
c = m.group(2) or '' | |
kt, kc = t, c | |
kw = open(nname[t], 'w') | |
if tt: # write tls-auth definition | |
w.write('%s %s %s%s\n' % (tt, nname[tt], td or '', tc)) | |
w.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment