Issue
I'm trying to retrieve the name of a connected VPN. I'm running Fedora 23, so the connection is nicely enumerated in /etc/NetworkManager/system-connections, with one file that lists out every parameter of the VPN config, including the id which is what I'm looking for.
However, this file is owned and readable only by root (permission is 600), and is recreated every time the VPN connection starts, so changing the permissions doesn't help either.
I just need the name where I can retrieve it in a Python script. I can even do a separate check to see if it's active by reading the pid file in /sys/class/net. Is there any way to do this without elevating to root?
Solution
You could use python-networkmanager - it wraps d-bus (on debian/ubuntu with default python it requires to install python3-dbus
)
import NetworkManager
for conn in NetworkManager.NetworkManager.ActiveConnections:
print('Name: %s; vpn?: %s' % (conn.Id, conn.Vpn))
Note that almost all classes are just proxycalls, so for description of properties take look on d-bus api documentation - for active connections https://developer.gnome.org/NetworkManager/unstable/gdbus-org.freedesktop.NetworkManager.Connection.Active.html.
And below pure dbus solution - a slightly modified, one of the examples in NetworkManager source (git://anongit.freedesktop.org/NetworkManager/NetworkManager.git)
import dbus, sys
bus = dbus.SystemBus()
m_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
manager = dbus.Interface(m_proxy, "org.freedesktop.NetworkManager")
mgr_props = dbus.Interface(m_proxy, "org.freedesktop.DBus.Properties")
s_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
settings = dbus.Interface(s_proxy, "org.freedesktop.NetworkManager.Settings")
active = mgr_props.Get("org.freedesktop.NetworkManager", "ActiveConnections")
for a in active:
a_proxy = bus.get_object("org.freedesktop.NetworkManager", a)
a_props = dbus.Interface(a_proxy, "org.freedesktop.DBus.Properties")
name = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Id")
vpn = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Vpn")
print('Name: %s; vpn?: %s' % (name, vpn))
# to get even more data
#connection_path = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection")
#c_proxy = bus.get_object("org.freedesktop.NetworkManager", connection_path)
#connection = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
#settings = connection.GetSettings()
#print("%s (%s)" % (name, settings['connection']))
Answered By - kwarunek Answer Checked By - Cary Denson (WPSolving Admin)