Skip to content

Instantly share code, notes, and snippets.

@jorge-lavin
Created February 5, 2015 14:35
Show Gist options
  • Save jorge-lavin/5aca395b4c0517dbea16 to your computer and use it in GitHub Desktop.
Save jorge-lavin/5aca395b4c0517dbea16 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import logging
import os
import subprocess
import sys
VPN_NAME='vpnc'
def setup_logging(level=logging.DEBUG, formatter=logging.Formatter('%(asctime)s %(levelname)s : %(message)s - (%(module)s, line %(lineno)s)')):
"""
Setups a logger with a `StreamHandler` that prints to `stdout` with `debug` logging
level and the following formatter
%(asctime)s %(levelname)s : %(message)s - (%(module)s, line %(lineno)s')
@return logger: The previously formatted logger
"""
# FIXME: Add rtype to __doc__
# FIXME: Does this work with some previously configured libraries?
# First the logger
logger = logging.getLogger(__name__)
logger.setLevel(level)
# Then the handler
stdout_handler = logging.StreamHandler()
stdout_handler.setLevel(level)
stdout_handler.setFormatter(formatter)
# We add the handler to the logger
logger.addHandler(stdout_handler)
return logger
def get_pid(process_name):
"""
Returns the PID of the process associated to process_name
@return pid: The pid of the process
@rtype int
@raises CalledProcessError
"""
try:
subprocess.check_output(["pidof", process_name])
except AttributeError:
# Python 2.6 Compatibility ...
subprocess.check_call(["pidof", process_name])
def ask_boolean(message):
"""
Asks a yes/no question to the user and looks if the answer is yes or no
"""
yes = ['YES', 'Yes', 'yes', 'y']
no = ['NO', 'No', 'n']
answer = raw_input(message+'{new_line}Choose one of [{yes}] or [{no}] {new_line}'.format(new_line=os.linesep, yes=' '.join(yes), no=' '.join(no)))
if answer in yes:
return True
elif answer in no:
return False
else:
return False
def vpn():
vpn_folder = os.path.join(os.sep, 'etc', 'vpnc')
user_uid = os.getuid()
logger.debug('Vpn folder {vpn_folder}'.format(vpn_folder=vpn_folder))
logger.debug('User uid {user_uid}'.format(user_uid=user_uid))
if user_uid == 0:
vpn_cmd = [os.path.join(vpn_folder, VPN_NAME)] + ['prb']
else:
vpn_cmd = ['sudo'] + [os.path.join(vpn_folder, VPN_NAME)] + ['prb']
logger.debug('Launching {cmd}'.format(cmd=' '.join(vpn_cmd)))
process = subprocess.Popen(vpn_cmd, stderr=subprocess.PIPE, stdin=subprocess.PIPE ,universal_newlines=True, bufsize=1)
process_stdout, process_stderr = process.communicate(raw_input())
return_code = process.returncode
logger.debug('Process {proc} exited with code {code}'.format(proc=' '.join(vpn_cmd), code=return_code))
if return_code != 0:
raise OSError(process_stderr)
def blcred():
auth_profile_name = os.environ['BL_AUTH_PROFILE_NAME']
blcred_cmd = ['blcred', 'cred', '-acquire', '-profile', auth_profile_name]
if 'SRP' in auth_profile_name:
blcred_cmd += ['-i', os.path.join(os.path.expanduser('~'), '.bladelogic', 'info.dat')]
elif 'SSO' in auth_profile_name:
blcred_cmd = ['blcred', 'cred', '-acquire', '-profile', auth_profile_name]
logger.debug('Launching {cmd}'.format(cmd=' '.join(blcred_cmd)))
process = subprocess.Popen(blcred_cmd, stderr=subprocess.PIPE, stdin=subprocess.PIPE ,universal_newlines=True, bufsize=1)
process_stdout, process_stderr = process.communicate()
return_code = process.returncode
logger.debug('Process {proc} exited with code {code}'.format(proc=' '.join(blcred_cmd), code=return_code))
if return_code != 0:
raise OSError(process_stderr)
if __name__ == '__main__':
logger = setup_logging()
logger.debug('Looking for the pid of vpn provided by {0}'.format(VPN_NAME))
try:
get_pid(VPN_NAME)
except subprocess.CalledProcessError:
logger.info('The vpn is not running')
logger.info('Launching vpn')
vpn()
logger.info('Launching blcred')
blcred()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment