Guest User

Untitled

a guest
Apr 20th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.03 KB | None | 0 0
  1. import os
  2. import re
  3. import subprocess
  4. import sys
  5.  
  6. __author__ = 'baryshev'
  7.  
  8.  
  9. class LogColors:
  10. def __init__(self):
  11. """
  12. """
  13. pass
  14.  
  15. BLACK = '\033[30m'
  16. GREEN = '\033[92m'
  17. YELLOW = '\033[93m'
  18. RED = '\033[91m'
  19. ON_RED = '\033[41m'
  20. ON_GREEN = '\033[42m'
  21. ON_YELLOW = '\033[43m'
  22. ENDC = '\033[0m'
  23.  
  24.  
  25. class Constants:
  26. def __init__(self):
  27. """
  28. """
  29. pass
  30.  
  31. NO_COLORS = False
  32. ABORT_ON_FAIL = True
  33.  
  34.  
  35. def process_argv(argv):
  36. """
  37. :param argv: list of str
  38. :return: dict
  39. """
  40. args = {}
  41. for arg in argv[1:]:
  42. arg = arg.split('=')
  43. if len(arg) == 2 and len(arg[1]) > 0:
  44. args[arg[0]] = arg[1]
  45. else:
  46. args[arg[0]] = None
  47. return args
  48.  
  49.  
  50. def get_real_path(path):
  51. """
  52. :param path: str
  53. :return: str
  54. """
  55. try:
  56. return get_cmd_response(cmd='readlink|-f|{}'.format(path))
  57. except:
  58. return path
  59.  
  60.  
  61. def get_run_from(current_file):
  62. """
  63. :param current_file: str
  64. :return: str
  65. """
  66. if current_file is None:
  67. current_file = __file__
  68. return os.path.dirname(os.path.abspath(current_file))
  69.  
  70.  
  71. def run_cmd(cmd):
  72. """
  73. :param cmd: str
  74. """
  75. log_warning('Running command: {}'.format(cmd.split('|').__str__()))
  76. process = subprocess.Popen(cmd.split('|'))
  77. process.communicate()
  78. code = process.returncode
  79. if code != 0:
  80. log_error(message='failed to execute command [{}]'.format(' '.join(cmd.split('|'))))
  81. log_error(message='exiting with status {}'.format(code))
  82. if Constants.ABORT_ON_FAIL:
  83. sys.exit(code)
  84.  
  85.  
  86. def run_cmd_in_background(cmd, stdout_to_pipe=True, stderr_to_pipe=True):
  87. """
  88. :param stderr_to_pipe: boolean
  89. :param cmd: str
  90. """
  91. log_warning('Running command: {}'.format(cmd.split('|').__str__()))
  92. stderr = None
  93. stdout = None
  94. if stderr_to_pipe:
  95. stderr = subprocess.PIPE
  96. if stdout_to_pipe:
  97. stdout = subprocess.PIPE
  98. process = subprocess.Popen(cmd.split('|'), stdout=stdout, stderr=stderr)
  99. return process
  100.  
  101.  
  102. def get_cmd_response(cmd):
  103. """
  104. :param cmd: str
  105. :return: str
  106. """
  107. cmd = cmd.split('|')
  108. process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  109. out, err = process.communicate()
  110. code = process.returncode
  111. if code != 0:
  112. log_error(message='failed to execute command [{}]'.format(' '.join(cmd.split('|'))))
  113. log_error(message='exiting with status {}'.format(code))
  114. if Constants.ABORT_ON_FAIL:
  115. sys.exit(code)
  116. return out.strip().decode()
  117.  
  118.  
  119. def grep(text, pattern):
  120. """
  121. :param text: str
  122. :param pattern: str
  123. :return: bool
  124. """
  125. reg = re.compile(pattern)
  126. for line in text.split('\n'):
  127. if reg.match(line):
  128. return True
  129. return False
  130.  
  131.  
  132. def mkdir_p(path_to_dir):
  133. """
  134. :param path_to_dir: str
  135. """
  136. if not os.path.exists(path_to_dir):
  137. os.makedirs(path_to_dir)
  138.  
  139.  
  140. def mkdir_for_file(path_to_file):
  141. """
  142. :param path_to_file: str
  143. """
  144. mkdir_p(path_to_dir=os.path.dirname(path_to_file))
  145.  
  146.  
  147. def read_from_file(filename):
  148. """
  149. :param filename: str
  150. :return: str
  151. """
  152. s = open(filename, 'r')
  153. out = s.read()
  154. s.close()
  155. return out.strip()
  156.  
  157.  
  158. def write_to_file(path_to_file, data):
  159. """
  160. :param path_to_file: str
  161. :param data: str
  162. """
  163. mkdir_for_file(path_to_file=path_to_file)
  164. file_to_rewrite = open(path_to_file, 'w')
  165. file_to_rewrite.write(data)
  166. file_to_rewrite.close()
  167.  
  168.  
  169. def append_file(path_to_file, data):
  170. """
  171. :param path_to_file: str
  172. :param data: str
  173. """
  174. mkdir_for_file(path_to_file=path_to_file)
  175. file_to_rewrite = open(path_to_file, 'a')
  176. file_to_rewrite.write(data)
  177. file_to_rewrite.close()
  178.  
  179.  
  180. def touch_file(path_to_file):
  181. """
  182. :param path_to_file: str
  183. """
  184. open(path_to_file, 'w').close()
  185.  
  186.  
  187. def copy_file_save_path(path_to_file, new_parent_dir):
  188. if os.path.exists(path_to_file):
  189. write_to_file(path_to_file='{}/{}'.format(new_parent_dir, path_to_file), data=read_from_file(path_to_file))
  190.  
  191.  
  192. def write_configfile(path_to_file, section, data=None):
  193. """
  194. :param path_to_file: str
  195. :param section: str
  196. :param data: list
  197. """
  198. if not data:
  199. data = []
  200. dirname = os.path.dirname(path_to_file)
  201. if not os.path.exists(dirname):
  202. os.makedirs(dirname)
  203. import configparser
  204. config = configparser.ConfigParser()
  205. config.read(path_to_file)
  206. if section not in config.sections():
  207. config.add_section(section)
  208. for key, value in data:
  209. config.set(section, key, value)
  210. configfile = open(path_to_file, 'w')
  211. config.write(configfile)
  212. configfile.close()
  213.  
  214.  
  215. def log_info(message):
  216. """
  217. :param message: str
  218. """
  219. if not Constants.NO_COLORS:
  220. for text in message.split('\n'):
  221. if len(text) > 0:
  222. print(LogColors.ON_GREEN + LogColors.BLACK + text + LogColors.ENDC)
  223. else:
  224. print('')
  225. else:
  226. print(message)
  227.  
  228.  
  229. def log_error(message):
  230. """
  231. :param message: str
  232. """
  233. if not Constants.NO_COLORS:
  234. for text in message.split('\n'):
  235. if len(text) > 0:
  236. print(LogColors.ON_RED + text + LogColors.ENDC)
  237. else:
  238. print('')
  239. else:
  240. print(message)
  241.  
  242.  
  243. def log_warning(message):
  244. """
  245. :param message: str
  246. """
  247. if not Constants.NO_COLORS:
  248. for text in message.split('\n'):
  249. if len(text) > 0:
  250. print(LogColors.ON_YELLOW + LogColors.BLACK + text + LogColors.ENDC)
  251. else:
  252. print('')
  253. else:
  254. print(message)
  255.  
  256.  
  257. def relaunch_as_root(current_file=None):
  258. """
  259. :param current_file: str
  260. """
  261. run_from = get_run_from(current_file=current_file)
  262. os.chdir(run_from)
  263.  
  264. if os.geteuid() != 0:
  265. log_warning(message='script runs under non-privileged user (id:{})\nnow we will try to relaunch as root...'.format(os.geteuid()))
  266. os.execvp('sudo', ['sudo', 'python'] + sys.argv)
  267. log_info(message='launch success\n')
Add Comment
Please, Sign In to add comment