Last active
February 19, 2019 07:54
-
-
Save mhatreabhay/695a90331c29dcb83ef7d439b394ad5d to your computer and use it in GitHub Desktop.
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 python | |
""" | |
SFRP script for Linux vms to install rssh package | |
""" | |
import os | |
import os.path | |
import imp | |
import time | |
import subprocess | |
import errno | |
import logging | |
import logging.handlers | |
import shutil | |
import sys | |
import platform | |
import json | |
import re | |
from distutils.spawn import find_executable | |
operation = "background_installer" | |
status = "success" | |
msg = "Enabled successfully." | |
logger_name = operation | |
script_path = os.path.realpath(__file__) | |
script_directory = os.path.dirname(script_path) | |
log_path = os.path.join(script_directory, '{0}.log'.format(operation)) | |
log_level = logging.DEBUG | |
resolve_lock_err_cmd = "sudo rm /var/lib/apt/lists/* -rf" | |
resolve_dpkg_lock_err_cmd = "sudo rm /var/lib/dpkg/lock; sudo dpkg --configure -a " | |
def get_logger(logger_name, logger_path, log_level): | |
'''Returns a properly formatted logger object that uses a rotating file handler''' | |
logger = logging.getLogger(logger_name) | |
logger.setLevel(log_level) | |
logFormatter = logging.Formatter('%(asctime)s [%(levelname)s] - %(message)s') | |
consoleHandler = logging.StreamHandler() | |
consoleHandler.setLevel(log_level) | |
consoleHandler.setFormatter(logFormatter) | |
fileHandler = logging.handlers.RotatingFileHandler(logger_path, maxBytes=1024 * 1024, backupCount=2) | |
fileHandler.setLevel(log_level) | |
fileHandler.setFormatter(logFormatter) | |
logger.addHandler(consoleHandler) | |
logger.addHandler(fileHandler) | |
return logger | |
log = get_logger(operation, log_path, log_level) | |
def query_package(package, version): | |
command_list = 'dpkg -s {0} | grep "Version: {1}$" |wc -l '.format(package, version) | |
process = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) | |
output, error = process.communicate() | |
status = process.returncode | |
log.debug('Command List: {0}{1}Status: {2}{1}Output: {3}{1}Error: {4}{1}'.format(command_list, os.linesep, status, | |
output.strip(), error.strip())) | |
if int(output) >= 1: | |
return True | |
else: | |
return False | |
def execute_command(command_list, raise_exception_on_error=False, available_retry=10): | |
'''Executes the specified command using the supplied parameters''' | |
ExtensionShortName = "CustomScript_rssh_2_3_4_4" | |
status = 1 | |
retrycount = 0 | |
cmds = ", ".join(command_list) | |
while (status != 0 and retrycount < available_retry): | |
try: | |
process = subprocess.Popen(command_list, bufsize=4096, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | |
shell=True) | |
# timeout=360 | |
time.sleep(1) | |
log.info("Executing: {0}".format(cmds)) | |
while process.poll() is None: | |
time.sleep(10) | |
except OSError as os_err: | |
log.error('{0}:{1}'.format(os_err.errno, os_err.strerror)) | |
process.kill() | |
except ValueError: | |
log.error('Invalid arguments:{0}'.format(cmds)) | |
time.sleep(30) | |
process.kill() | |
except IOError as io_err: | |
log.error("IO Error: {0}:{1}".format(io_err.errno, io_err.strerror)) | |
if "dpkg: error: dpkg status database is locked by another process" in e.strerror: | |
execute_command([resolve_dpkg_lock_err_cmd], available_retry=3) | |
time.sleep(30) | |
process.kill() | |
except Exception as e: | |
log.error("Unexpected error:{0}".format(sys.exc_info()[0])) | |
log.error("error msg: {0}".format(e.message)) | |
time.sleep(30) | |
process.kill() | |
finally: | |
output, error = process.communicate() | |
status = process.returncode | |
retrycount += 1 | |
if status == 0: | |
log.debug( | |
'Command List: {0}{1}Status: {2}{1}Output: {3}{1}Error: {4}{1}'.format(cmds, os.linesep, status, | |
output.strip(), | |
error.strip())) | |
else: | |
log.error( | |
'Command List: {0}{1}Status: {2}{1}Output: {3}{1}Error: {4}{1}'.format(cmds, os.linesep, | |
status, output.strip(), | |
error.strip())) | |
time.sleep(30) | |
if "Could not get lock /var/lib/dpkg/lock" in error: | |
execute_command([resolve_lock_err_cmd], available_retry=3) | |
return status, output, error | |
def run_cmd(cmd): | |
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) | |
proc.wait() | |
output = proc.stdout.read() | |
code = proc.returncode | |
return code,output | |
def install_rssh_package(): | |
status, output, error = execute_command(["sed -i 's+//\t\"vim\"+\trssh+g' /etc/apt/apt.conf.d/50unattended-upgrades"]) | |
status, output, error = execute_command(["cd /tmp && sudo wget http://archive.ubuntu.com/ubuntu/pool/universe/r/rssh/rssh_2.3.4-4_amd64.deb -O rssh_2.3.4-4_amd64.deb"]) | |
if(status == 0): | |
status, output, error = execute_command(["sudo dpkg -i /tmp/rssh_2.3.4-4_amd64.deb"]) | |
if(status == 0): | |
status, output, error = execute_command(["sed -i 's+//\t\"vim\"+\trssh+g' /etc/apt/apt.conf.d/50unattended-upgrades"]) | |
return status, output, error | |
def main(): | |
# Global Variables definition | |
global distro_info | |
distro_info = platform.dist() | |
distro_name = distro_info[0] | |
status = 1 | |
retrycount = 0 | |
if (distro_name == 'Ubuntu' or distro_name == 'debian'): | |
try: | |
if (query_package('rssh', '2.3.4-4')): | |
log.info('rssh_2.3.4-4 is installed') | |
status = 0 | |
while (status != 0 and retrycount < 100): | |
status, output, error = install_rssh_package() | |
time.sleep(5) | |
retrycount += 1 | |
if (status != 0): | |
status, output, error = install_rssh_package() | |
if not (query_package('rssh', '2.3.4-4')): | |
status = 1 | |
log.error('rssh_2.3.4-4 not installed') | |
else: | |
log.info('rssh_2.3.4-4 installed successfully') | |
status = 0 | |
except Exception as e: | |
log.error("error msg: {0}".format(e.message)) | |
finally: | |
if not (query_package('rssh', '2.3.4-4')): | |
log.error('rssh_2.3.4-4 not installed') | |
install_rssh_package() | |
return | |
else: | |
log.info('rssh_2.3.4-4 installed successfully') | |
status = 0 | |
else: | |
# exception | |
log.error('not supported yet') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment