Advertisement
renix1

Create service

Sep 1st, 2018
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. #!/usr/bin/python2
  2. # coding:utf-8
  3. import subprocess
  4. import os
  5.  
  6. class ServiceFile(object):
  7.     def __init__(self):
  8.         self._path = '/etc/systemd/system'
  9.         self.fn = 'cpugovernor.service'
  10.         self.lines = ['[Unit]\n', 'Description=CPU Performance\n', '\n'
  11.                       '[Service]\n', 'Type=oneshot\n', 'ExecStart=/usr/bin/set-perf\n', '\n',
  12.                       '[Install]\n', 'WantedBy=multi-user.target\n']
  13.  
  14.     def create_executable(self):
  15.         current_path = os.path.join(os.getcwd(), 'set-perf')
  16.         r = subprocess.Popen(['sudo', 'ln', '-s', current_path, '/usr/bin/set-perf', '2>&1'], stdout=subprocess.PIPE).communicate()[0]
  17.  
  18.     def create_file(self):
  19.         self.create_executable()
  20.         with open(os.path.join(self._path, self.fn), 'w') as f:
  21.             for line in self.lines:
  22.                 f.write(line)
  23.  
  24.     def enable_service(self):
  25.         subprocess.Popen(['sudo', 'systemctl', 'start', self.fn])
  26.         subprocess.Popen(['sudo', 'systemctl', 'enable', self.fn], stdout=subprocess.PIPE)
  27.         subprocess.Popen(['sudo', 'systemctl', 'daemon-reload'])
  28.         r = subprocess.Popen(['sudo', 'systemctl', 'status', os.path.join(self._path, self.fn)], stdout=subprocess.PIPE).communicate()[0]
  29.         r = r[r.find('Loaded'):]
  30.         if not 'not loaded' in r:
  31.             return True
  32.         else:
  33.             return False
  34.  
  35. if __name__ == '__main__':  
  36.     if os.getuid() != 1000:
  37.         service = ServiceFile()
  38.         service.create_file()
  39.         print('Serviço está rodando: {}'.format(service.enable_service()))
  40.     else:
  41.         print('Script rodando sob nível usuário. Por-favor execute novamente como superusuário.')
  42.         exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement