pystemd


Namepystemd JSON
Version 0.13.2 PyPI version JSON
download
home_page
SummaryA systemd binding for python
upload_time2023-05-28 05:14:51
maintainer
docs_urlNone
authorAlvaro Leiva Geisse
requires_python
licenseLGPL-2.1+
keywords systemd linux dbus
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            pystemd
=======

[![Continuous Integration](https://github.com/systemd/pystemd/workflows/Continuous%20Integration/badge.svg?event=push)](https://github.com/systemd/pystemd/actions) [![Matrix](https://img.shields.io/matrix/pystemd:matrix.org)](https://matrix.to/#/#pystemd:matrix.org)


This library allows you to talk to systemd over dbus from python, without
actually thinking that you are talking to systemd over dbus. This allows you to
programmatically start/stop/restart/kill and verify services status from
systemd point of view, avoiding executing `subprocess.Popen(['systemctl', ...`
and then parsing the output to know the result.


Show don't tell
---------------

In software as in screenwriting, it's better to show how things work instead of
tell. So this is how you would use the library from a interactive shell.

    In [1]: from pystemd.systemd1 import Unit
    In [2]: unit = Unit(b'postfix.service')
    In [3]: unit.load()

Note: you need to call `unit.load()` because by default `Unit` will not load the
unit information as that would require do some IO (and we dont like doing io on a class constructor). 
You can autoload the unit by `Unit(b'postfix.service', _autoload=True)` or using the unit as a 
contextmanager like `with Unit(b'postfix.service'): ...`

Once the unit is loaded, you can interact with it, you can do by accessing its
systemd's interfaces:

    In [4]: unit.Unit.ActiveState
    Out[4]: b'active'

    In [5]: unit.Unit.StopWhenUnneeded
    Out[5]: False

    In [6]: unit.Unit.Stop(b'replace') # require privilege account
    Out[6]: b'/org/freedesktop/systemd1/job/6601531'

    In [7]: unit.Unit.ActiveState
    Out[7]: b'inactive'

    In [8]: unit.Unit.SubState
    Out[8]: b'running'

    In [9]: unit.Unit.Start(b'replace') # require privilege account
    Out[9]: b'/org/freedesktop/systemd1/job/6601532'

    In [10]: unit.Unit.ActiveState
    Out[10]: b'active'

    In [11]: unit.Service.GetProcesses() # require systemd v238 and above
    Out[11]:
    [(b'/system.slice/postfix.service',
        1754222,
        b'/usr/libexec/postfix/master -w'),
     (b'/system.slice/postfix.service', 1754224, b'pickup -l -t fifo -u'),
     (b'/system.slice/postfix.service', 1754225, b'qmgr -l -t fifo -u')]

    In [12]: unit.Service.MainPID
    Out[12]: 1754222

The `systemd1.Unit` class provides shortcuts for the interfaces in the systemd
namespace, as you se above, we have  Service (org.freedesktop.systemd1.Service)
and Unit (org.freedesktop.systemd1.Unit). Others can be found in
`unit._interfaces` as:

```
In [12]: unit._interfaces
Out[12]:
{'org.freedesktop.DBus.Introspectable': <org.freedesktop.DBus.Introspectable of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.DBus.Peer': <org.freedesktop.DBus.Peer of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.DBus.Properties': <org.freedesktop.DBus.Properties of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.systemd1.Service': <org.freedesktop.systemd1.Service of /org/freedesktop/systemd1/unit/postfix_2eservice>,
 'org.freedesktop.systemd1.Unit': <org.freedesktop.systemd1.Unit of /org/freedesktop/systemd1/unit/postfix_2eservice>}

 In [13]: unit.Service
 Out[13]: <org.freedesktop.systemd1.Service of /org/freedesktop/systemd1/unit/postfix_2eservice>
```

Each interface has methods and properties, that can access directly as
`unit.Service.MainPID`, the list of properties and methods is in `.properties`
and `.methods` of each interface.

The above code operates on root user units by default. To operate on userspace units, explicitly pass in a user mode DBus instance:
```
from pystemd.dbuslib import DBus
with DBus(user_mode=True) as bus:
    unit = Unit(b"postfix.service", bus=bus)
    unit.load()
```

Alongside the `systemd1.Unit`, we also have a `systemd1.Manager`, that allows
you to interact with systemd manager.


```
In [14]: from pystemd.systemd1 import Manager

In [15]: manager = Manager()

In [16]: manager.load()

In [17]: manager.Manager.ListUnitFiles()
Out[17]:
...
(b'/usr/lib/systemd/system/rhel-domainname.service', b'disabled'),
 (b'/usr/lib/systemd/system/fstrim.timer', b'disabled'),
 (b'/usr/lib/systemd/system/getty.target', b'static'),
 (b'/usr/lib/systemd/system/systemd-user-sessions.service', b'static'),
...

In [18]: manager.Manager.Architecture
Out[18]: b'x86-64'

In [19]: manager.Manager.Virtualization
Out[19]: b'kvm'

```

Extras:
-------
We also include `pystemd.run`, the spiritual port of systemd-run
to python. [example of usage](_docs/pystemd.run.md):

```python
# run this as root
>>> import pystemd.run, sys
>>> pystemd.run(
    [b'/usr/bin/psql', b'postgres'],
    machine=b'db1',
    user=b'postgres',
    wait=True,
    pty=True,
    stdin=sys.stdin, stdout=sys.stdout,
    env={b'PGTZ': b'UTC'}
)
```

will open a postgres interactive prompt in a local nspawn-machine.

You also get an interface to `sd_notify` in the form of `pystemd.daemon.notify` [docs](_docs/daemon.md).

```python
# run this as root
>>> import pystemd.daemon
>>> pystemd.daemon.notify(False, ready=1, status='Gimme! Gimme! Gimme!')
```

And access to listen file descriptors for socket activation scripts.

```python
# run this as root
>>> import pystemd.daemon
>>> pystemd.daemon.LISTEN_FDS_START
3
>>> pystemd.daemon.listen_fds()
1 # you normally only open 1 socket
```

And access if watchdog is enabled and ping it.

```python
import time
import pystemd.daemon

watchdog_usec = pystemd.daemon.watchdog_enabled()
watchdog_sec = watchdog_usec/10**6

if not watchdog_usec:
  print(f'watchdog was not enabled!')

for i in range(20):
    pystemd.daemon.notify(False, watchdog=1, status=f'count {i+1}')
    time.sleep(watchdog_sec*0.5)

print('sleeping for 30 seconds')
time.sleep(watchdog_sec*2)
print('you will never reach me in a watchdog env')

```

We also provide basic journal interaction with `pystemd.journal` [docs](_docs/journal.md)

```python
import logging
import pystemd.journal

pystemd.journal.sendv(
  f"PRIORITY={logging.INFO}",
  MESSAGE="everything is awesome",
  SYSLOG_IDENTIFIER="tegan"
)
```

will result in the message (shorten for sake of example).

```json

{

  "SYSLOG_IDENTIFIER" : "tegan",
  "PRIORITY" : "20",
  "MESSAGE" : "everything is awesome",
  ...
}

```

Install
-------

So you like what you see, the simplest way to install pystemd is by:

```bash
$ pip install pystemd
```

pystemd is packaged in a few distros like Fedora and Debian. As of Fedora 32 and in EPEL as of EPEL 8.

It can be installed with:

```bash
$ sudo dnf install python3-pystemd # fedora
$ sudo apt install python3-pystemd # debian
```

which will also take care of installing any required dependencies. Keep in mind that most distros manage their own repos and version, and you may be getting old versions.


Build  from source
------------------


you'll need to have:

* Python headers: Just use your distro's package (e.g. python-dev).
* systemd headers: Chances are you already have this. Normally, it is called
`libsystemd-dev` or `systemd-devel`. You need to have at least v237.
Please note that CentOS 7 ships with version 219. To work around this, please read
  [this](_docs/centos7.md).
* systemd library: check if `pkg-config --cflags --libs libsystemd` returns
`-lsystemd` if not you can install `systemd-libs` or
`libsystemd` depending on your distribution, version needs to be at least
v237.
* gcc: or any compiler that `setup.py` will accept.
* [`pkg-config`](https://www.freedesktop.org/wiki/Software/pkg-config/) command. Depending on your distro, the package is called "pkg-config", "pkgconfig" or a compatible substitute like "pkgconf"

if you want to install from source then after you clone this repo all you need to do its `pip install . `


In addition to previous requirements you'll need:

  * setuptools: Just use your distro's package (e.g. python-setuptools).
  * Cython: at least version 0.21a1, just pip install it or use the official
  installation guide from cython homepage to get latest
   http://cython.readthedocs.io/en/latest/src/quickstart/install.html.


Learning more
-------------

This project has been covered in a number of conference talks:
* [Using systemd in high level languages](https://www.youtube.com/watch?v=lBQgMGPxqNo) at [All Systems Go! 2018](https://all-systems-go.io)
* [systemd: why you should care as a Python developer](https://www.youtube.com/watch?v=ZUX9Fx8Rwzg) at [PyCon 2018](https://us.pycon.org/2018/)
* [Better security for Python with systemd](https://www.youtube.com/watch?v=o-OqslA5dkw) at [Pyninsula #10](https://www.meetup.com/Pyninsula-Python-Peninsula-Meetup/events/244939632/)

A [Vagrant-based demo](https://github.com/aleivag/pycon2018) was also developed
for PyCon 2018.

License
-------

pystemd is licensed under LGPL 2.1 or later.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "pystemd",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "Alvaro Leiva Geisse <aleivag@gmail.com>, Davide Cavalca <dcavalca@meta.com>, Anita Zhang <the.anitazha@gmail.com>",
    "keywords": "systemd,linux,dbus",
    "author": "Alvaro Leiva Geisse",
    "author_email": "Alvaro Leiva Geisse <aleivag@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/16/2f/a3397229c357a982f7a198d7301372fb59bed2c2a89034f9d88b764f6441/pystemd-0.13.2.tar.gz",
    "platform": null,
    "description": "pystemd\n=======\n\n[![Continuous Integration](https://github.com/systemd/pystemd/workflows/Continuous%20Integration/badge.svg?event=push)](https://github.com/systemd/pystemd/actions) [![Matrix](https://img.shields.io/matrix/pystemd:matrix.org)](https://matrix.to/#/#pystemd:matrix.org)\n\n\nThis library allows you to talk to systemd over dbus from python, without\nactually thinking that you are talking to systemd over dbus. This allows you to\nprogrammatically start/stop/restart/kill and verify services status from\nsystemd point of view, avoiding executing `subprocess.Popen(['systemctl', ...`\nand then parsing the output to know the result.\n\n\nShow don't tell\n---------------\n\nIn software as in screenwriting, it's better to show how things work instead of\ntell. So this is how you would use the library from a interactive shell.\n\n    In [1]: from pystemd.systemd1 import Unit\n    In [2]: unit = Unit(b'postfix.service')\n    In [3]: unit.load()\n\nNote: you need to call `unit.load()` because by default `Unit` will not load the\nunit information as that would require do some IO (and we dont like doing io on a class constructor). \nYou can autoload the unit by `Unit(b'postfix.service', _autoload=True)` or using the unit as a \ncontextmanager like `with Unit(b'postfix.service'): ...`\n\nOnce the unit is loaded, you can interact with it, you can do by accessing its\nsystemd's interfaces:\n\n    In [4]: unit.Unit.ActiveState\n    Out[4]: b'active'\n\n    In [5]: unit.Unit.StopWhenUnneeded\n    Out[5]: False\n\n    In [6]: unit.Unit.Stop(b'replace') # require privilege account\n    Out[6]: b'/org/freedesktop/systemd1/job/6601531'\n\n    In [7]: unit.Unit.ActiveState\n    Out[7]: b'inactive'\n\n    In [8]: unit.Unit.SubState\n    Out[8]: b'running'\n\n    In [9]: unit.Unit.Start(b'replace') # require privilege account\n    Out[9]: b'/org/freedesktop/systemd1/job/6601532'\n\n    In [10]: unit.Unit.ActiveState\n    Out[10]: b'active'\n\n    In [11]: unit.Service.GetProcesses() # require systemd v238 and above\n    Out[11]:\n    [(b'/system.slice/postfix.service',\n        1754222,\n        b'/usr/libexec/postfix/master -w'),\n     (b'/system.slice/postfix.service', 1754224, b'pickup -l -t fifo -u'),\n     (b'/system.slice/postfix.service', 1754225, b'qmgr -l -t fifo -u')]\n\n    In [12]: unit.Service.MainPID\n    Out[12]: 1754222\n\nThe `systemd1.Unit` class provides shortcuts for the interfaces in the systemd\nnamespace, as you se above, we have  Service (org.freedesktop.systemd1.Service)\nand Unit (org.freedesktop.systemd1.Unit). Others can be found in\n`unit._interfaces` as:\n\n```\nIn [12]: unit._interfaces\nOut[12]:\n{'org.freedesktop.DBus.Introspectable': <org.freedesktop.DBus.Introspectable of /org/freedesktop/systemd1/unit/postfix_2eservice>,\n 'org.freedesktop.DBus.Peer': <org.freedesktop.DBus.Peer of /org/freedesktop/systemd1/unit/postfix_2eservice>,\n 'org.freedesktop.DBus.Properties': <org.freedesktop.DBus.Properties of /org/freedesktop/systemd1/unit/postfix_2eservice>,\n 'org.freedesktop.systemd1.Service': <org.freedesktop.systemd1.Service of /org/freedesktop/systemd1/unit/postfix_2eservice>,\n 'org.freedesktop.systemd1.Unit': <org.freedesktop.systemd1.Unit of /org/freedesktop/systemd1/unit/postfix_2eservice>}\n\n In [13]: unit.Service\n Out[13]: <org.freedesktop.systemd1.Service of /org/freedesktop/systemd1/unit/postfix_2eservice>\n```\n\nEach interface has methods and properties, that can access directly as\n`unit.Service.MainPID`, the list of properties and methods is in `.properties`\nand `.methods` of each interface.\n\nThe above code operates on root user units by default. To operate on userspace units, explicitly pass in a user mode DBus instance:\n```\nfrom pystemd.dbuslib import DBus\nwith DBus(user_mode=True) as bus:\n    unit = Unit(b\"postfix.service\", bus=bus)\n    unit.load()\n```\n\nAlongside the `systemd1.Unit`, we also have a `systemd1.Manager`, that allows\nyou to interact with systemd manager.\n\n\n```\nIn [14]: from pystemd.systemd1 import Manager\n\nIn [15]: manager = Manager()\n\nIn [16]: manager.load()\n\nIn [17]: manager.Manager.ListUnitFiles()\nOut[17]:\n...\n(b'/usr/lib/systemd/system/rhel-domainname.service', b'disabled'),\n (b'/usr/lib/systemd/system/fstrim.timer', b'disabled'),\n (b'/usr/lib/systemd/system/getty.target', b'static'),\n (b'/usr/lib/systemd/system/systemd-user-sessions.service', b'static'),\n...\n\nIn [18]: manager.Manager.Architecture\nOut[18]: b'x86-64'\n\nIn [19]: manager.Manager.Virtualization\nOut[19]: b'kvm'\n\n```\n\nExtras:\n-------\nWe also include `pystemd.run`, the spiritual port of systemd-run\nto python. [example of usage](_docs/pystemd.run.md):\n\n```python\n# run this as root\n>>> import pystemd.run, sys\n>>> pystemd.run(\n    [b'/usr/bin/psql', b'postgres'],\n    machine=b'db1',\n    user=b'postgres',\n    wait=True,\n    pty=True,\n    stdin=sys.stdin, stdout=sys.stdout,\n    env={b'PGTZ': b'UTC'}\n)\n```\n\nwill open a postgres interactive prompt in a local nspawn-machine.\n\nYou also get an interface to `sd_notify` in the form of `pystemd.daemon.notify` [docs](_docs/daemon.md).\n\n```python\n# run this as root\n>>> import pystemd.daemon\n>>> pystemd.daemon.notify(False, ready=1, status='Gimme! Gimme! Gimme!')\n```\n\nAnd access to listen file descriptors for socket activation scripts.\n\n```python\n# run this as root\n>>> import pystemd.daemon\n>>> pystemd.daemon.LISTEN_FDS_START\n3\n>>> pystemd.daemon.listen_fds()\n1 # you normally only open 1 socket\n```\n\nAnd access if watchdog is enabled and ping it.\n\n```python\nimport time\nimport pystemd.daemon\n\nwatchdog_usec = pystemd.daemon.watchdog_enabled()\nwatchdog_sec = watchdog_usec/10**6\n\nif not watchdog_usec:\n  print(f'watchdog was not enabled!')\n\nfor i in range(20):\n    pystemd.daemon.notify(False, watchdog=1, status=f'count {i+1}')\n    time.sleep(watchdog_sec*0.5)\n\nprint('sleeping for 30 seconds')\ntime.sleep(watchdog_sec*2)\nprint('you will never reach me in a watchdog env')\n\n```\n\nWe also provide basic journal interaction with `pystemd.journal` [docs](_docs/journal.md)\n\n```python\nimport logging\nimport pystemd.journal\n\npystemd.journal.sendv(\n  f\"PRIORITY={logging.INFO}\",\n  MESSAGE=\"everything is awesome\",\n  SYSLOG_IDENTIFIER=\"tegan\"\n)\n```\n\nwill result in the message (shorten for sake of example).\n\n```json\n\n{\n\n  \"SYSLOG_IDENTIFIER\" : \"tegan\",\n  \"PRIORITY\" : \"20\",\n  \"MESSAGE\" : \"everything is awesome\",\n  ...\n}\n\n```\n\nInstall\n-------\n\nSo you like what you see, the simplest way to install pystemd is by:\n\n```bash\n$ pip install pystemd\n```\n\npystemd is packaged in a few distros like Fedora and Debian. As of Fedora 32 and in EPEL as of EPEL 8.\n\nIt can be installed with:\n\n```bash\n$ sudo dnf install python3-pystemd # fedora\n$ sudo apt install python3-pystemd # debian\n```\n\nwhich will also take care of installing any required dependencies. Keep in mind that most distros manage their own repos and version, and you may be getting old versions.\n\n\nBuild  from source\n------------------\n\n\nyou'll need to have:\n\n* Python headers: Just use your distro's package (e.g. python-dev).\n* systemd headers: Chances are you already have this. Normally, it is called\n`libsystemd-dev` or `systemd-devel`. You need to have at least v237.\nPlease note that CentOS 7 ships with version 219. To work around this, please read\n  [this](_docs/centos7.md).\n* systemd library: check if `pkg-config --cflags --libs libsystemd` returns\n`-lsystemd` if not you can install `systemd-libs` or\n`libsystemd` depending on your distribution, version needs to be at least\nv237.\n* gcc: or any compiler that `setup.py` will accept.\n* [`pkg-config`](https://www.freedesktop.org/wiki/Software/pkg-config/) command. Depending on your distro, the package is called \"pkg-config\", \"pkgconfig\" or a compatible substitute like \"pkgconf\"\n\nif you want to install from source then after you clone this repo all you need to do its `pip install . `\n\n\nIn addition to previous requirements you'll need:\n\n  * setuptools: Just use your distro's package (e.g. python-setuptools).\n  * Cython: at least version 0.21a1, just pip install it or use the official\n  installation guide from cython homepage to get latest\n   http://cython.readthedocs.io/en/latest/src/quickstart/install.html.\n\n\nLearning more\n-------------\n\nThis project has been covered in a number of conference talks:\n* [Using systemd in high level languages](https://www.youtube.com/watch?v=lBQgMGPxqNo) at [All Systems Go! 2018](https://all-systems-go.io)\n* [systemd: why you should care as a Python developer](https://www.youtube.com/watch?v=ZUX9Fx8Rwzg) at [PyCon 2018](https://us.pycon.org/2018/)\n* [Better security for Python with systemd](https://www.youtube.com/watch?v=o-OqslA5dkw) at [Pyninsula #10](https://www.meetup.com/Pyninsula-Python-Peninsula-Meetup/events/244939632/)\n\nA [Vagrant-based demo](https://github.com/aleivag/pycon2018) was also developed\nfor PyCon 2018.\n\nLicense\n-------\n\npystemd is licensed under LGPL 2.1 or later.\n",
    "bugtrack_url": null,
    "license": "LGPL-2.1+",
    "summary": "A systemd binding for python",
    "version": "0.13.2",
    "project_urls": {
        "changelog": "https://github.com/systemd/pystemd/blob/main/CHANGES.md",
        "homepage": "https://github.com/systemd/pystemd",
        "repository": "https://github.com/systemd/pystemd.git"
    },
    "split_keywords": [
        "systemd",
        "linux",
        "dbus"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "162fa3397229c357a982f7a198d7301372fb59bed2c2a89034f9d88b764f6441",
                "md5": "780fe0d823723085993bcc1680c31284",
                "sha256": "4dcfa4b13a55685c49d3d17c10631eca18c33770f66316f8ef2337b8951cc144"
            },
            "downloads": -1,
            "filename": "pystemd-0.13.2.tar.gz",
            "has_sig": false,
            "md5_digest": "780fe0d823723085993bcc1680c31284",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 308397,
            "upload_time": "2023-05-28T05:14:51",
            "upload_time_iso_8601": "2023-05-28T05:14:51.284705Z",
            "url": "https://files.pythonhosted.org/packages/16/2f/a3397229c357a982f7a198d7301372fb59bed2c2a89034f9d88b764f6441/pystemd-0.13.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-28 05:14:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "systemd",
    "github_project": "pystemd",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pystemd"
}
        
Elapsed time: 0.11054s