from os import fdopen
from dbus import SystemBus, Array


def run(host, cmd, user=None):
    bus = SystemBus()
    remote_object = bus.get_object('org.freedesktop.machine1',
                                   '/org/freedesktop/machine1',
                                   False,
                                   )
    if user is not None:
        cmd = ['/bin/su', '-', user, '-s', '/bin/bash', '-c', ' '.join(cmd)]
    res = remote_object.OpenMachineShell(host,
                                         '',
                                         cmd[0],
                                         Array(cmd, signature='s'),
                                         Array(['TERM=dumb'], signature='s'),
                                         dbus_interface='org.freedesktop.machine1.Manager',
                                         )
    fd = res[0].take()
    fh = fdopen(fd)
    while True:
        try:
            yield fh.readline().strip()
        except OSError as err:
            if err.errno != 5:
                raise err from err
            break
