Python Forum
a class that gets available, running, and stopped services (Ubuntu/Debian)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a class that gets available, running, and stopped services (Ubuntu/Debian)
#5
(Aug-26-2018, 01:32 AM)rootVIII Wrote: does the output of service --status-all on your machine give a service/status that does not have a [+] or a [-]?
They all have [ + ] or [ - ], however man service indicates

Quote: service --status-all runs all init scripts, in alphabetical order, with the status
command. The status is [ + ] for running services, [ - ] for stopped services and
[ ? ] for services without a 'status' command. This option only calls status for
sysvinit jobs; upstart jobs can be queried in a similar manner with initctl list.

It could be a good idea to parse more seriously the lines of output in case the syntax of service --status-all changes. The re module can be used for this. Also the command can be made a classmethod of the Service class, which would allow further code to subclass the Service class

from collections import namedtuple
import os
import re

class Service(namedtuple('Service', 'name status')):
    __slots__ = ()
    def is_running(self):
        return self.status == '+'
    def is_stopped(self):
        return self.status == '-'
    def has_no_status(self):
        return self.status == '?'

    @classmethod
    def iterate_all(cls):
        for line in os.popen("service --status-all &> /dev/null"):
            match = re.match(
                r"\[\s*(?P<status>[-+?])\s*\]\s*(?P<name>[^\s].+)", line.strip())
            if not match:
                raise ValueError(('Unknown service status syntax:', line))
            yield cls(match.group('name'), match.group('status'))

if __name__ == '__main__':
    for service in Service.iterate_all():
        print(service)
Reply


Messages In This Thread
RE: a class that gets available, running, and stopped services (Ubuntu/Debian) - by Gribouillis - Aug-26-2018, 07:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  A torsocks DDOS tool for Debian Linux Distros: python + wget + tor rootVIII 0 2,405 Jun-09-2019, 09:53 AM
Last Post: rootVIII
  A small/simple class for running nslookup on a list of domain names rootVIII 1 3,585 Apr-17-2019, 04:49 AM
Last Post: rootVIII

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020