Print result from dbus object - python

I want to print the result from the dbus.
In the command line i run this:
busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.DBus.Properties
And i get some results.
I try with python but no luck to print the results.
import dbus
bus = dbus.SystemBus()
eth0 = bus.get_object('org.freedesktop.NetworkManager',
'/org/freedesktop/NetworkManager/Devices/eth0')
eth0_dev_iface = dbus.Interface(eth0,
dbus_interface='org.freedesktop.NetworkManager.Devices')
props = eth0_dev_iface.getProperties()
But i get this error:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: No such method 'getProperties'

This was pretty aggravating. The interface is kinda crazy.
Try this:
import dbus
bus = dbus.SystemBus()
eth0 = bus.get_object('org.freedesktop.NetworkManager',
'/org/freedesktop/NetworkManager/Devices/eth0')
# Here's where we change things
eth0_dev_iface = dbus.Interface(eth0,
dbus_interface='org.freedesktop.DBus.Properties')
eth0_dev_iface.GetAll('org.freedesktop.NetworkManager.Devices')
Now why doesn't the documentation example code work as documented? That's a great question... The code above however, works fine.

Related

Retrieving the netnsid of a network namespace in Python

When trying to find the correct peer network interface of a veth pair that lives in a different namespace, that end is not only indicated by its iflink property, but also by a link-netnsid. This link-netnsid is a network namespace ID which is only meaningful within the current network namespace.
The Linux kernel doesn't offer to map a netnsid to a network namespace inode number, which is the only unique identification. However, Linux offers the RTM_GETNSID request that maps a network namespace identified either by fd (NETNSA_FD) or by PID (NETNSA_PID) to the local netnsid.
How do I make such a RTM_GETNSID request in Python, preferably using the pyroute2 library? So far, I could not successfully request the netnsid for the namespace identified by PID, but only get back an invalid argument error 22, using the following script:
from pyroute2 import IPRoute
from pyroute2.netlink import NLM_F_REQUEST
import pyroute2.netlink.rtnl as rtnl
import pyroute2.netlink.rtnl.nsidmsg as nsidmsg
netstack = IPRoute()
req = nsidmsg.nsidmsg()
req['rtgen_family'] = 0
# 12345 is PID of a process inside another network namespace
req['attrs'] = [('NETNSA_PID', 12345)]
ret = netstack.nlm_request(req, rtnl.RTM_GETNSID, NLM_F_REQUEST)
It turns out that my code actually is correct, but there's a bug in pyroute2 causing the RTNETLINK message to be a few octets too short (visible in strace). As a temporary hack around this library bug it is sufficient to set two attributes, so that the kernel accepts the RTNETLINK packet and works on it, even if it isn't fully correct.
from pyroute2 import IPRoute
from pyroute2.netlink import NLM_F_REQUEST
import pyroute2.netlink.rtnl as rtnl
import pyroute2.netlink.rtnl.nsidmsg as nsidmsg
netstack = IPRoute()
req = nsidmsg.nsidmsg()
req['rtgen_family'] = 0
# 12345 is PID of a process inside another network namespace
req['attrs'] = [('NETNSA_PID', 12345), ('NETNSA_PID', 0] # hack around pyroute 0.5.0 bug
ret = netstack.nlm_request(req, rtnl.RTM_GETNSID, NLM_F_REQUEST)

How to get Process Owner by Python using WMI?

I tried to get some information about Process Owner, using WMI. I tried to run this script:
import win32com.client
process_wmi = set()
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
process_list = objSWbemServices.ExecQuery("Select * from Win32_Process")
for process in process:
owner = process.GetOwner
if owner != 0:
print('Access denied')
else:
print('process: ',process.Name, 'PID: ', process.ProcessId, 'Owner: ', owner)
Of course, i get owner = 0 (Successful Completion)
When I tried to call process.GetOwner(), I get this error: TypeError: 'int' object is not callable
How to use this method without errors? With what parameters or with what flags maybe?
I try to actualize and use this method, here, but I can't convert code to my situation and get Process Owner. =(
Or may be someone know another method, how to get information about process owner. May be with WinApi methods?
Thank you for help!
The type error is because process_list from your code is an "unknown" COM object. Try this:
import win32com
from win32com.client import GetObject
wmi = win32com.client.GetObject("winmgmts:")
wmi = win32com.client.gencache.EnsureDispatch(wmi._oleobj_)
#Now execute your query
process = wmi.ExecQuery('select * from Win32_Process')
proc = process[0]
#Now I can do things like check properties
print proc.Properties_('ProcessId').Value
#Or use methods
parms = proc.ExecMethod_('GetOwner')
#Now I can do things with parms like
username = parms.Properties_('User').Value
Parms will be a com object of type SWbemObject just like process and proc are. It has other properties as well: return value and domain. I can poll it just like I did above for getting User from parms. Hope this helps.
Sorry, adding after the fact:
the properties for parms in the code above specifically are User, Domain, and ReturnValue
I would suggest using the psutil library. I was using the winapi, and wmi, but it's terribly slow :( psutil is much, much faster and gives you a convenient API for working with processes.
You can achieve the same thing like this:
import psutil
for process in psutil.get_process_list():
try:
print('Process: %s, PID: %s, Owner: %s' % (process.name, process.pid,
process.username))
except psutil.AccessDenied:
print('Access denied!')
And because only the username can give you Access denied you can in except do:
except psutil.AccessDenied:
print('Process: %s, PID: %s, Owner: DENIED' % (process.name, process.pid)
If you can use only pywin32 and wmi then this will work:
import wmi
for i in wmi.WMI().Win32_Process():
print('%s, %s, %s' % (i.Name, i.ProcessId, i.GetOwner()[2]))
According to the accepted answer:
for process in list(psutil.process_iter()):
Because of: Deprecate psutil.get_process_list() #273

udisks FilesystemUnmount appears to not exist when calling from python

I'm trying to unmount a filesystem that I mounted using FilesystemMount, but I keep getting UnknownMethod exceptions. I've verified that I can call the method on the Device interface via D-Feet, but trying to do it via dbus directly doesn't appear to work at all. I've tried using the following arguments:
''
None
[]
['']
The following code demonstrates the problem:
import dbus
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.UDisks', '/dev/fd0')
dev = dbus.Interface(proxy, 'org.freedesktop.UDisks.Device')
dev.FilesystemUnmount(['force'])
Exception:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: Method "FilesystemUmount" with signature "as" on interface "org.freedesktop.UDisks.Device" doesn't exist
Turns out that the problem is that FilesystemUnmount will only take an ObjectPath that udisks handed out. So by adding a check for that and then looking it up I got it to work. See the code below.
import dbus
path = '/dev/fd0'
bus = dbus.SystemBus()
if not isinstance(path, dbus.ObjectPath):
manager_obj = bus.get_object('org.freedesktop.UDisks',
'/org/freedesktop/UDisks')
manager = dbus.Interface(manager_obj, 'org.freedesktop.UDisks')
path = manager.FindDeviceByDeviceFile(path)
proxy = bus.get_object('org.freedesktop.UDisks', path)
dev = dbus.Interface(proxy, 'org.freedesktop.UDisks.Device')
dev.FilesystemUnmount('')

Python: Is it possible to set the clientport with xmlrpclib?

Is it possible to set the clientport for the xmlrpc-connection?
I want to say:
Client should make a ServerProxy-object to over a specific client port
or pseudocode something like this:
serv = xmlrpclib.ServerProxy("server:port","overSpecificClientPort").
Try to define a custom transport. This should be something like that:
import xmlrpclib, httplib
class sourcedTransport(xmlrpclib.Transport):
def setSource(self, src):
self.src = src
def make_connection(self, host):
h = httplib.HTTPConnection(host, source_address= self.src)
return h
srcPort = 43040
srcAddress = ('', srcPort)
p = sourcedTransport()
p.setSource(srcAddress)
server = xmlrpclib.ServerProxy("server:port", transport=p)
EDIT: bug fix httplib.HTTP => httplib.HTTPConnection
And checked that it works, in python 2.7 (but not before)
There is no option for this in module xmlrpclib, but you can create your own by modifying the original version. Assuming you use Linux, fetch /usr/lib/python2.7/xmlrpclib.py. Modify the method make_connection accordingly.
Providing a parameter source_address to HTTPConnection is supported by httplib not before Python version 2.7.
Have fun!

How to use startTLS with ldaptor?

I'm trying to use ldaptor to connect via startTLS to a LDAP server. Searching on internet and trying myself I arrived to this snippet of code:
from ldaptor.protocols.ldap import ldapclient, ldapsyntax, ldapconnector, distinguishedname
[...]
def main(base, serviceLocationOverrides):
c=ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient)
d = c.connect(base, serviceLocationOverrides)
d.addCallbacks(lambda proto: proto.startTLS(), error)
[...]
d.addErrback(error)
d.addBoth(lambda dummy: reactor.stop())
reactor.run()
but the code exits with an AssertionError:
[Failure instance: Traceback: <type 'exceptions.AssertionError'>:
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1167:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:789:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:361:callback
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:455:_startRunCallbacks
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:542:_runCallbacks
/usr/lib/pymodules/python2.7/ldaptor/protocols/ldap/ldapclient.py:239:_startTLS
/usr/lib/pymodules/python2.7/ldaptor/protocols/pureldap.py:1278:__init__
/usr/lib/pymodules/python2.7/ldaptor/protocols/pureldap.py:1144:__init__
]
I have tried to look in ldaptor code for the incriminated assertion but seems all ok.
Is there someone who succeded in using ldaptorClient startTLS?
A code snippet?
Thank you very much
Bye
I'm pretty certain that your problem is one I ran into a while back. In ldaptor/protocols/pureldap.py, line 1144 asserts that the LDAPExtendedRequest requestValue must be a string. But according to RFC 2251, that value is optional, and specifically should NOT be present in startTLS requests.
So your approach is correct; this is just a major bug in ldaptor. As far as I can tell, the author only tested using simple bind without TLS. You need to comment out that line in pureldap.py. If you're deploying this with the expectation that users will download or easy-install ldaptor, then you'll need to create a fixed copy of the LDAPExtendedRequest class in your own code, and sub it in at run-time.
Having had to maintain a project using ldaptor for several years, I would strongly urge you to switch to python-ldap if at all possible. Since it wraps the OpenLDAP libs, it can be much more difficult to build, especially with full support for SSL/SASL. But it's well worth it, because ldaptor has a lot more problems than just the one you ran across.
Using ldaptor 0.0.54 from https://github.com/twisted/ldaptor, I had no problems using StartTLS.
Here is the code:
#! /usr/bin/env python
from twisted.internet import reactor, defer
from ldaptor.protocols.ldap import ldapclient, ldapsyntax, ldapconnector
#defer.inlineCallbacks
def example():
serverip = 'your.server.name.or.ip'
basedn = 'o=Organization'
binddn = 'cn=admin,o=Organization'
bindpw = 'Sekret'
query = '(uid=jetsong)'
c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient)
overrides = {basedn: (serverip, 389)}
client = yield c.connect(basedn, overrides=overrides)
client = yield client.startTLS()
yield client.bind(binddn, bindpw)
o = ldapsyntax.LDAPEntry(client, basedn)
results = yield o.search(filterText=query)
for entry in results:
print entry
if __name__ == '__main__':
df = example()
df.addErrback(lambda err: err.printTraceback())
df.addCallback(lambda _: reactor.stop())
reactor.run()

Categories

Resources