2 # cnetworkmanager: Command Line Interface for NetworkManager
3 # by: http://en.opensuse.org/User:Mvidner
4 # license: http://www.gnu.org/licenses/gpl-2.0.html or later
7 print "cnetworkmanager %s - Command Line Interface for NetworkManager" % VERSION
11 # find other modules in our prefix, if specified
12 if len(sys
.argv
) > 2 and sys
.argv
[1] == "--prefix":
14 sys
.argv
[1:] = sys
.argv
[3:]
15 sys
.path
.append(prefix
+ "/share/cnetworkmanager");
25 from binascii
import hexlify
26 import ConfigParser
# knm config
27 from optparse
import OptionParser
33 print "Install python-1-dbus.rpm or or python-dbus.rpm or python-dbus.deb"
35 import xml
.dom
.minidom
39 # todo - only if loop wanted
40 print "Install python-gobject2.rpm or pygobject2.rpm or python-gobject.deb"
42 # python-gnome.rpm has gconf for nm-applet...
46 from dbus
.mainloop
.glib
import DBusGMainLoop
47 DBusGMainLoop(set_as_default
=True)
51 bus
= dbus
.SystemBus()
53 # FOOC = connection (service) string
54 # FOOI = interface string
57 # foopi = property interface
58 NMC
= 'org.freedesktop.NetworkManager'
60 PI
= 'org.freedesktop.DBus.Properties'
61 SSC
= "org.freedesktop.NetworkManagerSystemSettings"
62 USC
= "org.freedesktop.NetworkManagerUserSettings"
63 NMIC
= "org.freedesktop.NetworkManagerInfo"
66 ii
= dbus
.Interface(obj
, 'org.freedesktop.DBus.Introspectable')
70 # TODO: pull them from introspection.xml
71 NM_STATE
= ["UNKNOWN", "ASLEEP", "CONNECTING", "CONNECTED", "DISCONNECTED",]
73 def __init__(self
, opath
):
75 self
.nmo
= bus
.get_object(NMC
, self
.opath
)
76 self
.nmi
= dbus
.Interface(self
.nmo
, NMI
)
77 self
.nmpi
= dbus
.Interface(self
.nmo
, PI
)
83 "Dumps its own info (not owned objects)."
89 for device
in self
.Devices():
93 print "Active Connections"
94 aconns
= self
.ActiveConnections()
99 print "Wifi Networks:"
100 for dev
in self
.Devices():
103 def reply_handler(self
, opath
):
104 print "Connected:", opath
106 def err_handler(self
, *args
):
109 def silent_handler(self
, *args
):
113 def quitter_handler(self
, *args
):
114 # exit the loop that runs only because of us
120 "Detects NM version and chooses appropriate class"
122 nmo
= bus
.get_object(NMC
, opath
)
123 nmi
= dbus
.Interface(nmo
, NMI
)
125 dummy
= nmi
.getDevices()
127 except dbus
.exceptions
.DBusException
:
134 def SetWifiEnabled(self
, v
):
135 # TODO: async call, catch the state signal and exit
136 # weird: synchronous call works, but times out
137 # asynchronous call does not work
138 self
.nmi
.setWirelessEnabled(v
,
139 reply_handler
=self
.quitter_handler
,
140 error_handler
=self
.quitter_handler
)
144 def SetOnline(self
, v
):
147 reply_handler
=self
.quitter_handler
,
148 error_handler
=self
.quitter_handler
)
151 reply_handler
=self
.quitter_handler
,
152 error_handler
=self
.quitter_handler
)
157 print "State:", self
.NM_STATE
[self
.nmi
.state()]
158 we
= self
.nmi
.getWirelessEnabled()
159 if isinstance(we
, tuple):
160 print "Wifi enabled:", bool(we
[0])
161 print "Wifi HW enabled:", bool(we
[1])
163 print "Wifi enabled:", bool(we
)
166 dup
= self
.nmi
.getDialup()
168 except dbus
.exceptions
.DBusException
, e
:
169 #if e.get_dbus_name() == "org.freedesktop.NetworkManager.NoDialup":
175 opaths
= self
.nmi
.getDevices()
176 return map(cDevice_06
, opaths
)
178 def ActiveConnections(self
):
179 return [] # at most one active connection, FIXME find it
181 def reply_handler(self
):
182 print "Connection requested"
184 def err_handler(self
, *args
):
187 def ActivateConnection(self
, conn
, device
, ap
):
188 # passing *_handler makes the call asynchronous
189 self
.nmi
.setActiveDevice(device
.opath
, ssid_str(conn
.Ssid()),
190 reply_handler
=self
.reply_handler
,
191 error_handler
=self
.err_handler
,
198 def SetWifiEnabled(self
, v
):
199 self
.nmpi
.Set(NMI
, "WirelessEnabled", v
)
201 def SetOnline(self
, v
):
202 self
.nmi
.Sleep(not v
)
205 print "State:", self
.NM_STATE
[self
.nmpi
.Get(NMI
, "State")]
206 print "Wifi enabled:", self
.nmpi
.Get(NMI
, "WirelessEnabled")
207 print "Wifi HW enabled:", self
.nmpi
.Get(NMI
, "WirelessHardwareEnabled")
210 opaths
= self
.nmi
.GetDevices()
211 return map(cDevice_07
, opaths
)
213 def ActiveConnections(self
):
214 aconns
= self
.nmpi
.Get(NMI
, "ActiveConnections")
215 return map(cActiveConnection
, aconns
)
217 def ActivateConnection(self
, conn
, device
, ap
):
218 # passing *_handler makes the call asynchronous
219 self
.nmi
.ActivateConnection(USC
,
220 conn
.__dbus
_object
_path
__,
223 reply_handler
=self
.reply_handler
,
224 error_handler
=self
.err_handler
,
228 class cActiveConnection
:
229 def __init__(self
, opath
):
234 co
= bus
.get_object(NMC
, self
.opath
)
235 copi
= dbus
.Interface(co
, PI
)
236 for P
in ["ServiceName", "Connection", "SpecificObject",]:
237 print " %s: %s" % (P
, copi
.Get(NMI
, P
))
238 devs
= copi
.Get(NMI
, "Devices")
243 def bitmask_str(map, value
):
245 for mask
in sorted(map.keys()):
246 if value
& mask
: ret
.append(map[mask
])
251 def __init__(self
, opath
):
253 self
.devo
= bus
.get_object(NMC
, self
.opath
)
254 self
.devi
= dbus
.Interface(self
.devo
, NMI
+ ".Device")
255 self
.devpi
= dbus
.Interface(self
.devo
, PI
)
259 DEVICE_TYPE
= ["UNKNOWN", "802_3_ETHERNET", "802_11_WIRELESS",
260 "GSM", "CDMA",] #OLPC: 3 is MESH
262 def DeviceType(self
):
263 return self
.DEVICE_TYPE
[self
.DeviceType0()]
265 def ip_str(self
, i32
):
267 ret
.append("%d" % (i32
% 256))
269 ret
.append("%d" % (i32
% 256))
271 ret
.append("%d" % (i32
% 256))
273 ret
.append("%d" % (i32
% 256))
277 def DumpIp4Config(self
, opath
):
278 print " Ip4Config:", opath
279 o
= bus
.get_object(NMC
, opath
)
280 pi
= dbus
.Interface(o
, PI
)
282 for P
in ["Address", "Netmask", "Broadcast", "Gateway",]: # beta2?
283 print " %s: %s" % (P
, self
.ip_str(pi
.Get(NMI
, P
)))
286 addrs
= pi
.Get(NMI
, "Addresses")
288 print " %s/%s via %s" % tuple(map(self
.ip_str
, addr
))
289 nss
= pi
.Get(NMI
, "Nameservers")
290 print " Nameservers:", " ".join(map(self
.ip_str
, nss
))
291 doms
= pi
.Get(NMI
, "Domains")
292 print " Domains:", " ".join(doms
)
294 NM_DEVICE_CAP
= {1: "NM_SUPPORTED", 2: "CARRIER_DETECT", 4: "SCANNING", }
298 print "Device:", self
.opath
301 IW_MODE
= ["AUTO", "ADHOC", "INFRA", "MASTER",
302 "REPEAT", "SECOND", "MONITOR",]
308 for ap
in self
.APs():
315 class cDevice_06(cDevice
):
316 def DeviceType0(self
):
318 self
.dt
= self
.devi
.getProperties()[2]
320 self
.__class
__ = cDeviceEth_06
322 self
.__class
__ = cDeviceWifi_06
326 "UNKNOWN", "DEVICE_PREPARE", "DEVICE_CONFIG", "NEED_USER_KEY",
327 "IP_CONFIG_START", "IP_CONFIG_GET", "IP_CONFIG_COMMIT",
328 "ACTIVATED", "FAILED", "CANCELLED", ]
332 print " Driver:", self
.devi
.getDriver()
333 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
334 print " Self:", props
[0] # o
335 print " Interface:", props
[1] # s
336 print " Type:", self
.DEVICE_TYPE
[props
[2]] # u
337 print " UDI:", props
[3] # s
338 print " Active:", bool(props
[4]) # b
339 print " Activation Stage:", self
.NM_ACT_STAGE
[props
[5]] # u
340 print " IP:", props
[6] # s
341 print " Mask:", props
[7] # s
342 print " Bcast:", props
[8] # s
343 print " HwAddress:", props
[9] # s
344 print " GW:", props
[10] # s
345 print " NS1:", props
[11] # s
346 print " NS2:", props
[12] # s
350 print " (unknown device type, not dumping more)"
352 class cDeviceEth_06(cDevice_06
, cDeviceEth
):
354 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
355 print " Link Active:", bool(props
[15]) # b
356 print " Speed:", props
[16] # i
357 print " Generic Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, props
[17]) # u
359 class cDeviceWifi_06(cDevice_06
):
361 0x00000001: "PROTO_NONE",
362 0x00000002: "PROTO_WEP",
363 0x00000004: "PROTO_WPA",
364 0x00000008: "PROTO_WPA2",
365 0x00000010: "RESERVED1",
366 0x00000020: "RESERVED2",
367 0x00000040: "KEY_MGMT_PSK",
368 0x00000080: "KEY_MGMT_802_1X",
369 0x00000100: "RESERVED3",
370 0x00000200: "RESERVED4",
371 0x00000400: "RESERVED5",
372 0x00000800: "RESERVED6",
373 0x00001000: "CIPHER_WEP40",
374 0x00002000: "CIPHER_WEP104",
375 0x00004000: "CIPHER_TKIP",
376 0x00008000: "CIPHER_CCMP",
380 self
.wdevi
= dbus
.Interface(self
.devo
, NMI
+ ".Device.Wireless")
381 aps
= self
.devi
.getProperties()[20]
382 return map(cAP_06
, aps
)
385 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
386 print " Mode:", self
.IW_MODE
[props
[13]] # i
387 print " Strength:", props
[14] # i
388 print " Link Active:", bool(props
[15]) # b
389 print " Speed:", props
[16] # i
390 print " Generic Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, props
[17]) # u
391 print " Capabilities:", bitmask_str(self
.NM_802_11_CAP
, props
[18]) # u
392 print " Current net:", props
[19] # s
393 nets
= props
[20] # as
394 print " Seen nets:", " ".join(nets
)
396 print " Access Points"
397 for ap
in self
.APs():
400 class cDevice_07(cDevice
):
401 def DeviceType0(self
):
403 self
.dt
= self
.devpi
.Get(NMI
, "DeviceType")
405 self
.__class
__ = cDeviceEth_07
407 self
.__class
__ = cDeviceWifi_07
411 "UNKNOWN", "UNMANAGED", "UNAVAILABLE", "DISCONNECTED", "PREPARE",
412 "CONFIG", "NEED_AUTH", "IP_CONFIG", "ACTIVATED", "FAILED",]
417 # "Ip4Config", only for NM_DEVICE_STATE_ACTIVATED
418 for P
in ["Udi", "Interface", "Driver",]:
419 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
420 addr
= self
.devpi
.Get(NMI
, "Ip4Address")
421 print " Ip4Address:", self
.ip_str(addr
)
422 caps
= self
.devpi
.Get(NMI
, "Capabilities")
423 print " Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, caps
)
424 state
= self
.NM_DEVICE_STATE
[self
.devpi
.Get(NMI
, "State")]
425 print " Dev State:", state
426 if state
== "ACTIVATED":
427 self
.DumpIp4Config(self
.devpi
.Get(NMI
, "Ip4Config"))
429 dt
= self
.DeviceType()
430 print " Dev Type:", dt
433 class cDeviceEth_07(cDevice_07
, cDeviceEth
):
435 for P
in ["HwAddress", "Speed", "Carrier"]:
436 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
438 class cDeviceWifi_07(cDevice_07
):
439 NM_802_11_DEVICE_CAP
= {1:"CIPHER_WEP40", 2:"CIPHER_WEP104",
440 4:"CIPHER_TKIP", 8:"CIPHER_CCMP",
444 self
.wdevi
= dbus
.Interface(self
.devo
, NMI
+ ".Device.Wireless")
445 aps
= self
.wdevi
.GetAccessPoints()
446 return map(cAP_07
, aps
)
449 print " Dev Mode:", self
.IW_MODE
[self
.devpi
.Get(NMI
, "Mode")]
450 wcaps
= self
.devpi
.Get(NMI
, "WirelessCapabilities")
451 print " Wifi Capabilities:", bitmask_str(self
.NM_802_11_DEVICE_CAP
, wcaps
)
452 for P
in ["HwAddress", "Bitrate", "ActiveAccessPoint"]:
453 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
455 print " Access Points"
456 for ap
in self
.APs():
459 """An AP found around us"""
461 def __init__(self
, opath
):
463 self
.apo
= bus
.get_object(NMC
, self
.opath
)
464 self
.appi
= dbus
.Interface(self
.apo
, PI
)
466 self
.devi
= dbus
.Interface(self
.apo
, NMI
+ ".Devices")
468 NM_802_11_AP_FLAGS
= {1: "PRIVACY",}
471 1: "PAIR_WEP40", 2: "PAIR_WEP104", 4: "PAIR_TKIP", 8: "PAIR_CCMP",
472 16: "GROUP_WEP40", 32: "GROUP_WEP104", 64: "GROUP_TKIP",
473 128: "GROUP_CCMP", 256: "KEY_MGMT_PSK", 512: "KEY_MGMT_802_1X",}
475 def ListNets(self
, marker
= " "):
477 mbr
= self
.Mbr() / 1024 # 07 1000, 06 1024?
478 priv_s
= self
.PrivS()
479 print "%s%3d: %s (%dMb%s)" % (marker
, self
.Strength(), self
.Ssid(), mbr
, priv_s
)
482 def Mbr(self
, props
=None):
484 props
= self
.devi
.getProperties()
489 props
= self
.devi
.getProperties()
490 caps_s
= bitmask_str(cDeviceWifi_06
.NM_802_11_CAP
, props
[7]) + ","
492 if caps_s
.find("PROTO_WEP,") != -1:
494 if caps_s
.find("PROTO_WPA,") != -1:
496 if caps_s
.find("PROTO_WPA2,") != -1:
498 if caps_s
.find("KEY_MGMT_802_1X,") != -1:
499 priv_s
+= " Enterprise"
502 def Strength(self
, props
=None):
504 props
= self
.devi
.getProperties()
507 def Ssid(self
, props
=None):
509 props
= self
.devi
.getProperties()
514 props
= self
.devi
.getProperties() # ossid iiib
515 print " Self:", props
[0]
516 print " Ssid:", self
.Ssid(props
)
517 print " HwAddress:", props
[2]
518 print " Strength:", self
.Strength(props
)
519 print " Frequency:", props
[4]
520 print " MaxBitrate:", self
.Mbr(props
)
521 print " AP Mode:", cDevice
.IW_MODE
[props
[6]]
522 print " Capabilities:", bitmask_str(cDeviceWifi_06
.NM_802_11_CAP
, props
[7])
523 print " Broadcast:", props
[8]
531 def opath_validchar(c
):
532 # _ is also escaped even though it is valid
534 string
.ascii_letters
.find(c
) != -1 or \
535 string
.digits
.find(c
) != -1
540 # TODO find a more elegant way
541 if not opath_validchar(c
):
547 def opath_unescape(s
):
549 unhex
= lambda xx
: chr(eval("0x"+xx
))
551 return re
.sub("_.._", lambda p
: unhex(p
.group()[1:3]), s
)
555 return self
.appi
.Get(NMI
, "MaxBitrate")
558 priv
= self
.appi
.Get(NMI
, "Flags") != 0
559 wpa
= self
.appi
.Get(NMI
, "WpaFlags") != 0
560 wpa2
= self
.appi
.Get(NMI
, "RsnFlags") != 0
563 if not wpa
and not wpa2
:
564 priv_s
= priv_s
+ " WEP"
566 priv_s
= priv_s
+ " WPA"
568 priv_s
= priv_s
+ " WPA2"
572 return int(self
.appi
.Get(NMI
, "Strength"))
575 return ssid_str(self
.appi
.Get(NMI
, "Ssid"))
578 print " AP:", self
.opath
579 print " Ssid:", self
.Ssid()
580 for P
in ["Frequency", "HwAddress", "MaxBitrate",]:
581 print " %s: %s" % (P
, self
.appi
.Get(NMI
, P
))
582 print " Strength:", self
.Strength()
583 print " AP Mode:", cDevice
.IW_MODE
[self
.appi
.Get(NMI
, "Mode")]
584 print " AP Flags:", bitmask_str(self
.NM_802_11_AP_FLAGS
,
585 self
.appi
.Get(NMI
, "Flags"))
586 print " AP WPA Flags:", bitmask_str(self
.NM_802_11_AP_SEC
,
587 self
.appi
.Get(NMI
, "WpaFlags"))
588 print " AP RSN Flags:", bitmask_str(self
.NM_802_11_AP_SEC
,
589 self
.appi
.Get(NMI
, "RsnFlags"))
591 # this is the client side of the applet; see also UserSettings
593 def __init__(self
, svc
, opath
):
596 self
.so
= bus
.get_object(self
.svc
, self
.opath
)
597 self
.si
= dbus
.Interface(self
.so
, 'org.freedesktop.NetworkManagerSettings')
600 return self
.svc
== SSC
;
603 for conn
in self
.Connections():
608 def DumpSystem(self
):
609 sspi
= dbus
.Interface(self
.so
, PI
)
610 print "Unmanaged Devices"
611 umds
= sspi
.Get(NMI
, "UnmanagedDevices")
614 # dump_settings_conn(svc, conn) umd?
617 def myConnection(self
, opath
):
618 return cConnection(self
.svc
, opath
)
620 def Connections(self
):
621 opaths
= self
.si
.ListConnections()
622 return map(self
.myConnection
, opaths
)
624 NETWORK_TYPE_ALLOWED
= 1
625 class cApplet_06(cApplet
):
626 def __init__(self
, svc
, opath
):
629 self
.io
= bus
.get_object(self
.svc
, self
.opath
)
630 self
.ii
= dbus
.Interface(self
.io
, 'org.freedesktop.NetworkManagerInfo')
635 def myConnection(self
, opath
):
636 return cConnection_06(self
, opath
)
638 # TODO also VPN conns
639 def Connections(self
):
640 names
= self
.ii
.getNetworks(NETWORK_TYPE_ALLOWED
)
641 return map(self
.myConnection
, names
)
644 def __init__(self
, svc
, opath
):
647 self
.co
= bus
.get_object(self
.svc
, self
.opath
)
648 self
.ci
= dbus
.Interface(self
.co
, 'org.freedesktop.NetworkManagerSettings.Connection')
651 print "Conn:", self
.opath
652 settings
= self
.Settings()
655 si
= dbus
.Interface(self
.co
, 'org.freedesktop.NetworkManagerSettings.Connection.Secrets')
656 security
= settings
.Security()
658 print " SECRETS:", security
661 secrets
= cSettings(si
.GetSecrets(security
,[],False))
663 except dbus
.exceptions
.DBusException
, e
:
664 if e
.get_dbus_name() == "org.freedesktop.DBus.Error.AccessDenied":
665 print " Access denied"
668 print " FIXME figure out 802-1x secrets"
671 return cSettings(self
.ci
.GetSettings())
673 def dump_time(unixtime
):
674 return time
.asctime(time
.localtime(unixtime
))
676 class cConnection_06
:
677 def __init__(self
, applet
, id):
682 print "Conn:", self
.id
684 np
= self
.applet
.ii
.getNetworkProperties(self
.id, NETWORK_TYPE_ALLOWED
)
687 print " time:", dump_time(np
[1])
688 print " trusted:", bool(np
[2])
689 print " bssids:", ", ".join(np
[3])
691 print " we_cipher:", enctype
693 print " secret:", np
[5]
695 print " wep_auth_algorithm:", np
[6]
697 print " wpa_psk_key_mgt:", np
[6]
698 print " wpa_psk_wpa_version:", np
[7]
700 return # nm-applet will not tell kfn anyway
701 devp
= "/org/freedesktop/NetworkManager/Devices/ath0" #FIXME
702 netp
= devp
+ "/Networks/" + opath_escape(self
.id)
705 kfn
= self
.applet
.ii
.getKeyForNetwork(devp
, netp
, ssid
, attempt
, newkey
)
710 NM_AUTH_TYPE_WPA_PSK_AUTO
= 0x00000000
711 NM_AUTH_TYPE_NONE
= 0x00000001
712 NM_AUTH_TYPE_WEP40
= 0x00000002
713 NM_AUTH_TYPE_WPA_PSK_TKIP
= 0x00000004
714 NM_AUTH_TYPE_WPA_PSK_CCMP
= 0x00000008
715 NM_AUTH_TYPE_WEP104
= 0x00000010
716 NM_AUTH_TYPE_WPA_EAP
= 0x00000020
717 NM_AUTH_TYPE_LEAP
= 0x00000040
719 IW_AUTH_ALG_OPEN_SYSTEM
= 0x00000001
720 IW_AUTH_ALG_SHARED_KEY
= 0x00000002
721 IW_AUTH_ALG_LEAP
= 0x00000004
724 def __init__(self
, conmap
):
725 #print "INIT", conmap
729 return self
.conmap
["connection"]["type"]
732 return self
.conmap
["connection"]["id"]
736 return self
.conmap
["802-11-wireless"]["ssid"]
739 # probably 802-3-ethernet
744 return self
.conmap
["connection"]["timestamp"]
752 def SeenBssids(self
):
754 return self
.conmap
["802-11-wireless"]["seen-bssids"]
762 return NM_AUTH_TYPE_WEP104
764 return NM_AUTH_TYPE_WPA_PSK_AUTO
766 return NM_AUTH_TYPE_NONE
767 print "Defaulting cipher type to none"
768 return NM_AUTH_TYPE_NONE
772 return self
.conmap
["802-11-wireless-security"]["psk"]
776 return self
.conmap
["802-11-wireless-security"]["wep-key0"]
782 def WepAuthAlgorithm(self
):
783 print "FIXME Defaulting WEP auth alg to open"
784 return IW_AUTH_ALG_OPEN_SYSTEM
787 print "FIXME Defaulting PSK key mgmt to 2"
790 def PskWpaVersion(self
):
791 print "FIXME Defaulting WPA version to 2"
796 return self
.conmap
[self
.Type()]["security"]
800 def isNet(self
, net_name
):
801 return self
.ID() == net_name
or self
.Ssid() == net_name
803 # FIXME check spec/NM what to censor
804 secrets
= dict.fromkeys(["wep-key0", "psk"])
807 "For GetSettings: censor secrets."
810 for n1
, v1
in self
.conmap
.iteritems():
812 for n2
, v2
in v1
.iteritems():
814 if self
.secrets
.has_key(n2
):
820 "For GetSecrets: only secrets."
829 for n1
, v1
in self
.conmap
.iteritems():
831 for n2
, v2
in v1
.iteritems():
832 print " %s: %s" % (n2
, v2
)
834 def mkconmap_wifi(ssid
):
837 'id': '_cnm_handcrafted_',
838 'uuid': str(uuid
.uuid1()), # new in oS 11.1
839 'type': '802-11-wireless',
842 'ssid': dbus
.ByteArray(ssid
),
843 'mode': 'infrastructure',
847 def elongate(s
, tlen
):
848 "repeat string s to target length tlen"
851 copies_needed
= int(math
.ceil(tlen
/ float(len(s
))))
852 return (s
* copies_needed
)[:tlen
]
854 # http://www.mail-archive.com/networkmanager-list@gnome.org/msg07935.html
855 def wep_passphrase_to_hash(p
):
856 return hashlib
.md5(elongate(p
, 64)).hexdigest()
858 def mkconmap_wep_pass(ssid
, key
):
859 cm
= mkconmap_wifi(ssid
)
860 cm
["802-11-wireless"]["security"] = "802-11-wireless-security"
861 cm
["802-11-wireless-security"] = {}
862 cm
["802-11-wireless-security"]["key-mgmt"] = "none"
863 cm
["802-11-wireless-security"]["wep-tx-keyidx"] = 0
864 cm
["802-11-wireless-security"]["wep-key0"] = wep_passphrase_to_hash(key
)
867 def mkconmap_wep(ssid
, key
):
868 cm
= mkconmap_wifi(ssid
)
869 cm
["802-11-wireless"]["security"] = "802-11-wireless-security"
870 cm
["802-11-wireless-security"] = {}
871 cm
["802-11-wireless-security"]["key-mgmt"] = "none"
872 cm
["802-11-wireless-security"]["wep-tx-keyidx"] = 0
873 cm
["802-11-wireless-security"]["wep-key0"] = key
876 def mkconmap_psk(ssid
, key
):
877 cm
= mkconmap_wifi(ssid
)
878 cm
["802-11-wireless"]["security"] = "802-11-wireless-security"
879 cm
["802-11-wireless-security"] = {}
880 cm
["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"
881 cm
["802-11-wireless-security"]["psk"] = key
882 cm
["802-11-wireless-security"]["group"] = ["tkip", "ccmp"]
883 cm
["802-11-wireless-security"]["pairwise"] = ["tkip", "ccmp"]
887 # server analog of cApplet
888 class UserSettings(dbus
.service
.Object
):
890 def __init__(self
, opath
, conmaps
):
891 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
892 #print "CONMAPS:", conmaps
893 self
.conns
= map(self
.newCon
, conmaps
)
895 def addCon(self
, conmap
):
896 c
= self
.newCon(conmap
)
901 def newCon(self
, conmap
):
902 cpath
= "/MyConnection/%d" % self
.counter
903 self
.counter
= self
.counter
+ 1
904 c
= Connection(cpath
, conmap
)
905 self
.NewConnection(cpath
) # announce it
908 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings',
909 in_signature
='', out_signature
='ao')
910 def ListConnections(self
):
911 return [c
.__dbus
_object
_path
__ for c
in self
.conns
]
913 #this is for EMITTING a signal, not receiving it
914 @dbus.service
.signal(dbus_interface
='org.freedesktop.NetworkManagerSettings',
916 def NewConnection(self
, opath
):
918 #print "signalling newconn:", opath
920 def GetByNet(self
, net_name
):
921 "Returns connection, or None"
923 if c
.isNet(net_name
):
928 class UserSettings_06(UserSettings
):
930 def __init__(self
, opath
, conmaps
):
931 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
932 #print "CONMAPS:", conmaps
933 self
.conns
= map(self
.newCon
, conmaps
)
936 def newCon(self
, conmap
):
937 cpath
= "/MyConnection/%d" % self
.counter
938 self
.counter
= self
.counter
+ 1
939 c
= Connection_06(cpath
, conmap
)
940 #self.NewConnection(cpath) # announce it
943 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
944 in_signature
="i", out_signature
='as')
945 def getNetworks(self
, i
):
946 # FIXME bytearray to str WHERE?
947 #n = [ssid_str(c.Ssid()) for c in self.conns]
948 n
= [c
.ID() for c
in self
.conns
]
949 print "getNetworks:", n
952 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
953 in_signature
="", out_signature
='ao') # out??
954 def getVPNConnections(self
):
957 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
959 #out_signature='sibasi') #varies
960 def getNetworkProperties(self
, net
, type):
962 # type is 1, NETWORK_TYPE_ALLOWED
963 c
= self
.GetByNet(net
)
965 return c
.getNetworkProperties()
966 print "Oops, could not getNetworkProperties for " + net
969 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
970 in_signature
="oosib")
971 #out_signature="isi") varies
972 def getKeyForNetwork(self
, dev
, net
, ssid
, attempt
, newkey
):
973 print "GKFN", dev
, net
, ssid
, attempt
, bool(newkey
)
975 m
= "Cannot ask for key"
977 raise dbus
.exceptions
.DBusException(m
)
979 snet
= opath_unescape(net
[net
.rfind("/")+1 : ]) # only stuff after /
980 c
= self
.GetByNet(snet
)
982 return c
.getKeyForNetwork()
983 print "Oops, could not getKeyForNetwork " + net
985 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
987 #in_signature="sbs isi", varies
988 def updateNetworkInfo(self
, ssid
, automatic
, bssid
, *security
):
989 print "Connected successfully"
993 print " automatic:", bool(automatic
)
994 print " bssid:", bssid
995 print " security:", security
998 def GetByNet(self
, net_name
):
999 "Returns connection, or None"
1000 for c
in self
.conns
:
1001 if c
.isNet(net_name
):
1006 # server analog of cConnection
1007 class Connection(dbus
.service
.Object
):
1008 def __init__(self
, opath
, conmap
):
1009 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
1010 self
.settings
= cSettings(conmap
)
1012 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection',
1013 sender_keyword
='sender',
1014 in_signature
='', out_signature
='a{sa{sv}}')
1015 def GetSettings(self
, sender
):
1016 #print "Getting settings:", self. __dbus_object_path__
1017 # return self.settings.ConMap()
1018 # grr, censoring secrets makes NM complain!?
1019 # bnc#479566#c3: Until I figure out how to make it work with
1020 # censored secrets, only pass the settings to the same user.
1021 sender_uid
= bus
.get_unix_user(sender
)
1022 if sender_uid
!= 0 and sender_uid
!= os
.geteuid():
1023 e
= "User %u is not permitted to read the settings" % sender_uid
1025 raise dbus
.exceptions
.DBusException(e
) # could do NM_SETTINGS_ERROR_* instead
1026 return self
.settings
.conmap
1028 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection.Secrets',
1029 in_signature
='sasb', out_signature
='a{sa{sv}}')
1030 def GetSecrets(self
, tag
, hints
, ask
):
1031 # FIXME respect args
1032 print "Getting secrets:", self
.__dbus
_object
_path
__
1033 return self
.settings
.SecMap()
1035 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection',
1036 in_signature
='', out_signature
='s')
1038 return self
.settings
.ID()
1041 return self
.settings
.Ssid()
1043 def isNet(self
, net_name
):
1044 return self
.settings
.isNet(net_name
)
1046 class Connection_06(Connection
):
1047 def __init__(self
, opath
, conmap
):
1048 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
1050 self
.settings
= cSettings(conmap
)
1052 # dbus.service.method
1053 def getNetworkProperties(self
):
1054 # essid, timestamp, ?, bssids, we_cipher, ?, ...
1055 # we_cipher=16: i wep_auth_algorithm
1056 # we_cipher=0: i wpa_psk_key_mgt, i wpa_psk_wpa_version
1057 ssid
= ssid_str(self
.settings
.Ssid())
1058 time
= self
.settings
.Timestamp() # last sucessfully connected? seen?
1059 trusted
= self
.settings
.Trusted()
1060 bssids
= dbus
.Array(self
.settings
.SeenBssids(), signature
="s")
1061 r
= [ssid
, time
, trusted
, bssids
]
1062 security
= self
.getKeyForNetwork("fake key")
1066 # dbus.service.method
1067 def getKeyForNetwork(self
, fake
="no"):
1069 key
= self
.settings
.Key()
1074 cip
= self
.settings
.WeCipher()
1075 if cip
== NM_AUTH_TYPE_NONE
:
1076 security
= tuple([cip
])
1077 elif cip
== NM_AUTH_TYPE_WEP40
or cip
== NM_AUTH_TYPE_WEP104
:
1078 wep_auth_algorithm
= self
.settings
.WepAuthAlgorithm()
1079 security
= (cip
, key
, wep_auth_algorithm
)
1080 elif cip
== NM_AUTH_TYPE_WPA_PSK_AUTO
or cip
== NM_AUTH_TYPE_TKIP
or \
1081 cip
== NM_AUTH_TYPE_CCMP
:
1082 wpa_psk_key_mgt
= self
.settings
.PskKeyMgt()
1083 wpa_psk_wpa_version
= self
.settings
.PskWpaVersion()
1084 security
= (cip
, key
, wpa_psk_key_mgt
, wpa_psk_wpa_version
)
1085 elif cip
== NM_AUTH_TYPE_WPA_EAP
:
1086 security
= tuple([cip
]) # TODO more...
1087 elif cip
== NM_AUTH_TYPE_LEAP
:
1088 security
= tuple([cip
]) # TODO more...
1092 class ConfigParserKNM
:
1093 "Parse ~/.kde/share/config/knetworkmanagerrc"
1096 p
= ConfigParser
.RawConfigParser()
1097 ok
= p
.read(os
.getenv("HOME") + "/.kde/share/config/knetworkmanagerrc")
1100 for s
in p
.sections():
1103 if path
[0] in ["ConnectionSetting", "ConnectionSecrets"]:
1105 self
.conmaps_d
.setdefault(cid
, {})
1109 for (n
, v
) in p
.items(s
):
1110 # WTF, Value_ is transfrmed to value_
1111 if n
[:6] == "value_":
1113 v
= self
.ParseValue(v
)
1115 if len(values
) != 0: # empty 802-1x confuses NM!?
1116 self
.conmaps_d
[cid
].setdefault(part
, {})
1117 self
.conmaps_d
[cid
][part
].update(**values
)
1118 #print "PARSED", cid, part, values
1121 return self
.conmaps_d
.values()
1123 def ParseValue(self
, v
):
1124 v
= eval('"%s"' % v
) # unescape backslashes
1125 dom
= xml
.dom
.minidom
.parseString(v
)
1126 return self
.ParseNode(dom
.documentElement
)
1128 def ParseNode(self
, n
):
1131 v
= self
.NodeText(n
)
1136 return dbus
.Byte(int(v
))
1139 elif t
== "int32" or t
== "uint32":
1145 if c
.localName
!= None: # whitespace
1146 v
.append(self
.ParseNode(c
))
1150 def NodeText(self
, n
):
1151 if n
.hasChildNodes():
1152 return n
.firstChild
.wholeText
1160 bus
.add_signal_receiver(self
.abbr_h
,
1161 path_keyword
="path",
1162 interface_keyword
="interface",
1163 member_keyword
="member")
1165 def ignore(self
, dbus_interface
, signal_name
):
1166 self
.watch(self
.null_h
, dbus_interface
, signal_name
)
1168 def null_h(self
, *args
, **kwargs
):
1171 def watch(self
, handler
, dbus_interface
, signal_name
):
1172 self
.specific
[dbus_interface
+"."+ signal_name
] = True
1173 bus
.add_signal_receiver(handler
,
1174 dbus_interface
=dbus_interface
,
1175 signal_name
=signal_name
,
1176 path_keyword
="path")
1178 def abbr_h(self
, *args
, **kwargs
):
1179 ifc
= kwargs
["interface"]
1180 sig
= kwargs
["member"]
1181 if self
.specific
.has_key(ifc
+"."+ sig
):
1184 opath
= kwargs
["path"]
1185 line
= "SIG %s: %s.%s%s" % (self
.abbrev(opath
,"/"),
1186 self
.abbrev(ifc
,"."),
1190 def abbrev(self
, s
, sep
):
1191 words
= s
.split(sep
)
1192 words
= map (self
.a1
, words
)
1193 result
= sep
.join(words
)
1194 if self
.amap
.has_key(result
):
1195 if self
.amap
[result
] != s
:
1196 print "ABBR COLLISION %s was %s now %s" % (result
, self
.amap
[result
], s
)
1198 print "ABBR %s is %s" % (result
, s
)
1199 self
.amap
[result
] = s
1206 # first char, delete lowercase and _ from the rest
1207 return s
[0] + s
[1:].translate(string
.maketrans("", ""),
1208 string
.lowercase
+ "_")
1210 class Monitor(MonitorBase
):
1212 MonitorBase
.__init
__(self
)
1216 dbus_interface
="org.freedesktop.NetworkManager.Device.Wireless",
1217 signal_name
="PropertiesChanged")
1220 dbus_interface
="org.freedesktop.NetworkManager.AccessPoint",
1221 signal_name
="PropertiesChanged")
1223 self
.ignore("org.freedesktop.Hal.Device", "PropertyModified")
1224 self
.ignore("fi.epitest.hostap.WPASupplicant.Interface", "ScanResultsAvailable")
1225 self
.ignore("com.redhat.PrinterSpooler", "QueueChanged")
1226 self
.ignore("org.freedesktop.NetworkManager", "StateChange") # deprecated
1227 self
.watch(self
.nm_sc_h
, "org.freedesktop.NetworkManager", "StateChanged")
1228 self
.watch(self
.wpas_isc_h
, "fi.epitest.hostap.WPASupplicant.Interface", "StateChange")
1229 self
.watch(self
.nmd_sc_h
, "org.freedesktop.NetworkManager.Device", "StateChanged")
1230 self
.watch(self
.bus_noc_h
, "org.freedesktop.DBus", "NameOwnerChanged")
1232 def bus_noc_h(self
, *args
, **kwargs
):
1233 (name
, old
, new
) = args
1238 print "\tBUS NOC\t%s %s" % (name
, new
)
1240 def wpas_isc_h(self
, *args
, **kwargs
):
1241 opath
= kwargs
["path"]
1243 print "\tWPAS %s\t(%s, was %s)" % (new
, opath
, old
.lower())
1245 def nmd_sc_h(self
, *args
, **kwargs
):
1246 opath
= kwargs
["path"]
1247 (new
, old
, reason
) = args
1248 news
= cDevice_07
.NM_DEVICE_STATE
[new
]
1249 olds
= cDevice_07
.NM_DEVICE_STATE
[old
]
1252 reasons
= "reason %d" % reason
1253 print "\tDevice State %s\t(%s, was %s%s)" % (news
, opath
, olds
.lower(), reasons
)
1255 def nm_sc_h(self
, *args
, **kwargs
):
1257 ss
= cNM
.NM_STATE
[s
]
1258 print "\tNM State:", ss
1260 def propc_h(self
, *args
, **kwargs
):
1261 opath
= kwargs
["path"]
1263 for k
, v
in props
.iteritems():
1266 line
= "\tPROP\t%s\t%s\t(%s)" % (k
, v
, opath
)
1272 op
= OptionParser(version
="%prog " + VERSION
)
1273 op
.add_option("-d", "--dev",
1274 action
="store_true", default
=False,
1275 help="list devices")
1276 op
.add_option("-c", "--actcon",
1277 action
="store_true", default
=False,
1278 help="list active connections")
1279 op
.add_option("-u", "--usrcon",
1280 action
="store_true", default
=False,
1281 help="list user connection settings (can CRASH nm-applet)")
1282 op
.add_option("-s", "--syscon",
1283 action
="store_true", default
=False,
1284 help="list system connection settings")
1285 op
.add_option("-a", "--ap",
1286 action
="store_true", default
=False,
1287 help="list found access points")
1288 op
.add_option("-n", "--nets",
1289 action
="store_true", default
=False,
1290 help="list found wireless networks")
1291 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
1292 op
.add_option("-w", "--wifi",
1293 choices
=["0","1","off","on","no","yes","false","true"],
1295 help="enable or disable wireless")
1296 op
.add_option("-o", "--online",
1297 choices
=["0","1","off","on","no","yes","false","true"],
1299 help="enable or disable network at all")
1301 op
.add_option("-C", "--connect",
1302 help="connect to a wireless network NET (using knetworkmanagerrc or the key options below)",
1304 op
.add_option("--unprotected",
1305 action
="store_true", default
=False,
1306 help="network does not require a key")
1307 op
.add_option("--wep-hex",
1309 help="use this WEP key of 26 hex digits")
1310 op
.add_option("--wep-pass",
1312 help="use this WEP passphrase")
1313 op
.add_option("--wpa-psk-hex",
1315 help="use this WPA key of 64 hex digits")
1316 op
.add_option("--wpa-pass",
1318 help="use this WPA passphrase")
1319 op
.add_option("-m", "--monitor",
1320 action
="store_true", default
=False,
1321 help="loop to show dbus signals")
1324 (options
, args
) = op
.parse_args()
1332 nmp
= '/org/freedesktop/NetworkManager'
1335 except dbus
.exceptions
.DBusException
, e
:
1337 print "NetworkManager is not running"
1339 if options
.dev
or options
.actcon
:
1342 true_choices
= ["1", "on", "yes", "true"]
1343 if options
.wifi
!= None:
1344 nm
.SetWifiEnabled(options
.wifi
in true_choices
)
1345 if options
.online
!= None:
1346 nm
.SetOnline(options
.online
in true_choices
)
1352 print "SYSTEM Connections"
1353 if nm
.Api() == "06":
1354 print "Cannot do that with NM 0.6"
1356 ss
= cApplet(SSC
, '/org/freedesktop/NetworkManagerSettings')
1360 print "USER Connections"
1362 if nm
.Api() == "06":
1363 us
= cApplet_06(NMIC
, "/org/freedesktop/NetworkManagerInfo")
1365 us
= cApplet(USC
, '/org/freedesktop/NetworkManagerSettings')
1367 except dbus
.exceptions
.DBusException
, e
:
1369 #if e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
1370 print "Applet is not running"
1372 nmo
= bus
.get_object(NMC
, nmp
)
1373 nmi
= dbus
.Interface(nmo
, NMI
)
1375 def service_pid(name
):
1376 DBS
= 'org.freedesktop.DBus'
1378 dbo
= bus
.get_object(DBS
, '/')
1379 dbi
= dbus
.Interface(dbo
, DBI
)
1380 owner
= dbi
.GetNameOwner(name
)
1381 pid
= dbi
.GetConnectionUnixProcessID(owner
)
1384 # TODO UserSettings_06
1385 if options
.connect
!= None:
1386 if nm
.Api() == "06":
1390 brn
= bus
.request_name(name
, _dbus_bindings
.NAME_FLAG_DO_NOT_QUEUE
)
1391 if brn
== _dbus_bindings
.REQUEST_NAME_REPLY_EXISTS
:
1392 print "Could not provide settings service, another applet is running (pid %s)" % service_pid(name
)
1394 cfg
= ConfigParserKNM()
1395 if nm
.Api() == "06":
1396 us
= UserSettings_06("/org/freedesktop/NetworkManagerInfo",
1399 us
= UserSettings("/org/freedesktop/NetworkManagerSettings",
1402 def Connect(wanted_net
): # any. or take arg. net is config name or ssid name
1403 # ... in general, look for string in all config data. ssid for wifi, whatever for dialup
1404 # TODO also respect autoconnect
1406 # ActivateConn wants setting device ap; can find device from ap? ap is "specific" for wifi devices
1407 #print "Connection wanted to", wanted_net
1408 found_con
= found_ap
= found_dev
= None
1409 for dev
in nm
.Devices():
1410 for ap
in dev
.APs():
1411 if wanted_net
== ap
.Ssid():
1414 break # FIXME both loops
1415 found_con
= us
.GetByNet(wanted_net
)
1416 if found_ap
== None:
1417 print "No AP found with SSID", wanted_net
1419 if found_con
== None:
1420 print "No settings for net %s, assuming no key is needed" % wanted_net
1421 c
= mkconmap_wifi(wanted_net
)
1422 found_con
= us
.addCon(c
)
1423 nm
.ActivateConnection(found_con
, found_dev
, found_ap
) # TODO async
1424 # TODO run loop, exit it when we have serviced the required calls
1427 if options
.connect
!= None:
1428 if options
.unprotected
:
1429 c
= mkconmap_wifi(options
.connect
)
1431 if options
.wep_hex
!= None:
1432 c
= mkconmap_wep(options
.connect
, options
.wep_hex
)
1434 if options
.wep_pass
!= None:
1435 c
= mkconmap_wep_pass(options
.connect
, options
.wep_pass
)
1437 if options
.wpa_psk_hex
!= None:
1438 c
= mkconmap_psk(options
.connect
, options
.wpa_psk_hex
)
1440 if options
.wpa_pass
!= None:
1441 wpa_psk_hex
= hexlify(pbkdf2
.pbkdf2(options
.wpa_pass
, options
.connect
, 4096, 32))
1442 print "pbkdf2", wpa_psk_hex
1443 c
= mkconmap_psk(options
.connect
, wpa_psk_hex
)
1445 if Connect(options
.connect
):
1452 loop
= gobject
.MainLoop()