Split utility functions, fixing 06 a bit.
[cnetworkmanager.git] / cnetworkmanager
blob537d108e66c10b6053d65943b098a171bedc1811
1 #! /usr/bin/python
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
6 VERSION = "0.8.4"
7 print "cnetworkmanager %s - Command Line Interface for NetworkManager" % VERSION
9 norpm = False
10 import sys
11 # find other modules in our prefix, if specified
12 if len(sys.argv) > 2 and sys.argv[1] == "--prefix":
13 prefix = sys.argv[2]
14 sys.argv[1:] = sys.argv[3:]
15 sys.path.append(prefix + "/share/cnetworkmanager");
17 import os
18 from optparse import OptionParser
19 try:
20 import dbus
21 import dbus.service
22 import _dbus_bindings
23 except:
24 print "Install python-1-dbus.rpm or or python-dbus.rpm or python-dbus.deb"
25 norpm = True
26 try:
27 import gobject
28 except:
29 # todo - only if loop wanted
30 print "Install python-gobject2.rpm or pygobject2.rpm or python-gobject.deb"
31 norpm = True
32 # python-gnome.rpm has gconf for nm-applet...
33 if norpm:
34 sys.exit(1)
36 from dbus.mainloop.glib import DBusGMainLoop
37 DBusGMainLoop(set_as_default=True)
39 # private modules:
40 from monitor import Monitor
41 from configparser_knm import ConfigParserKNM
42 from mkconmap import *
43 from util import *
45 from object import *
46 from manager import *
47 from manager06 import cNM_06
48 from manager07 import cNM_07
49 from device import cDevice
50 from device06 import cDevice_06
51 from device07 import cDevice_07
52 from ap import cAP
53 from ap06 import cAP_06
54 from ap07 import cAP_07
55 from applet import cApplet, SSC, USC, NMIC
56 from applet06 import cApplet_06
57 from settings import cSettings
58 from svc_settings import UserSettings
59 from svc_settings06 import UserSettings_06
61 LOOP = False
63 bus = dbus.SystemBus()
65 # FOOC = connection (service) string
66 # FOOI = interface string
67 # fooo = object
68 # fooi = interface
69 # foopi = property interface
70 def introspect(obj):
71 ii = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
72 print ii.Introspect()
74 def make_nm(opath):
75 "Detects NM version and chooses appropriate class"
77 nmo = bus.get_object(NMC, opath)
78 nmi = dbus.Interface(nmo, NMI)
79 try:
80 dummy = nmi.getDevices()
81 return cNM_06(opath, options)
82 except dbus.exceptions.DBusException, e:
83 if e.get_dbus_name() == 'org.freedesktop.DBus.Error.AccessDenied':
84 raise
85 return cNM_07(opath, options)
87 # main
89 fail = False
91 op = OptionParser(version="%prog " + VERSION)
92 op.add_option("-d", "--dev",
93 action="store_true", default=False,
94 help="list devices")
95 op.add_option("-c", "--actcon",
96 action="store_true", default=False,
97 help="list active connections")
98 op.add_option("-u", "--usrcon",
99 action="store_true", default=False,
100 help="list user connection settings (can CRASH nm-applet)")
101 op.add_option("-s", "--syscon",
102 action="store_true", default=False,
103 help="list system connection settings")
104 op.add_option("-a", "--ap",
105 action="store_true", default=False,
106 help="list found access points")
107 op.add_option("-n", "--nets",
108 action="store_true", default=False,
109 help="list found wireless networks")
110 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
111 op.add_option("-w", "--wifi",
112 choices=["0","1","off","on","no","yes","false","true"],
113 metavar="BOOL",
114 help="enable or disable wireless")
115 op.add_option("-o", "--online",
116 choices=["0","1","off","on","no","yes","false","true"],
117 metavar="BOOL",
118 help="enable or disable network at all")
120 op.add_option("--activate-connection",
121 help="raw API: activate the KIND(user/system) connection CON on device DEV using AP",
122 metavar="[KIND],CON,DEV,[AP]")
123 op.add_option("-C", "--connect",
124 help="connect to a wireless network NET (using knetworkmanagerrc or the key options below)",
125 metavar="NET")
126 op.add_option("--unprotected",
127 action="store_true", default=False,
128 help="network does not require a key")
129 op.add_option("--wep-hex",
130 metavar="KEY",
131 help="use this WEP key of 26 hex digits")
132 op.add_option("--wep-pass",
133 metavar="KEY",
134 help="use this WEP passphrase")
135 op.add_option("--wpa-psk-hex",
136 metavar="KEY",
137 help="use this WPA key of 64 hex digits")
138 op.add_option("--wpa-pass",
139 metavar="KEY",
140 help="use this WPA passphrase")
141 op.add_option("-m", "--monitor",
142 action="store_true", default=False,
143 help="loop to show dbus signals")
146 (options, args) = op.parse_args()
148 if options.ap:
149 options.dev = True
150 if options.monitor:
151 LOOP = True
154 nmp = '/org/freedesktop/NetworkManager'
155 try:
156 nm = make_nm(nmp)
157 except dbus.exceptions.DBusException, e:
158 print "NetworkManager is not running or running as an other user"
159 fail = True
160 if options.dev or options.actcon:
161 nm.Dump()
163 true_choices = ["1", "on", "yes", "true"]
164 if options.wifi != None:
165 nm.SetWifiEnabled(options.wifi in true_choices)
166 if options.online != None:
167 nm.SetOnline(options.online in true_choices)
169 if options.nets:
170 nm.ListNets()
172 if options.syscon:
173 print "SYSTEM Connections"
174 if nm.Api() == "06":
175 print "Cannot do that with NM 0.6"
176 fail = True
177 else:
178 ss = cApplet(SSC, '/org/freedesktop/NetworkManagerSettings')
179 ss.Dump()
181 if options.usrcon:
182 print "USER Connections"
183 try:
184 if nm.Api() == "06":
185 us = cApplet_06(NMIC, "/org/freedesktop/NetworkManagerInfo")
186 else:
187 us = cApplet(USC, '/org/freedesktop/NetworkManagerSettings')
188 us.Dump()
189 except dbus.exceptions.DBusException, e:
190 print e
191 #if e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
192 print "Applet is not running"
193 fail = True
195 nmo = bus.get_object(NMC, nmp)
196 nmi = dbus.Interface(nmo, NMI)
198 def service_pid(name):
199 DBS = 'org.freedesktop.DBus'
200 DBI = DBS
201 dbo = bus.get_object(DBS, '/')
202 dbi = dbus.Interface(dbo, DBI)
203 owner = dbi.GetNameOwner(name)
204 pid = dbi.GetConnectionUnixProcessID(owner)
205 return pid
207 # TODO UserSettings_06
208 if options.connect != None:
209 if nm.Api() == "06":
210 name = NMIC
211 else:
212 name = USC
213 brn = bus.request_name(name, _dbus_bindings.NAME_FLAG_DO_NOT_QUEUE)
214 if brn == _dbus_bindings.REQUEST_NAME_REPLY_EXISTS:
215 print "Could not provide settings service, another applet is running (pid %s)" % service_pid(name)
216 sys.exit(1)
217 cfg = ConfigParserKNM()
218 if nm.Api() == "06":
219 us = UserSettings_06("/org/freedesktop/NetworkManagerInfo",
220 cfg.ConMaps())
221 else:
222 us = UserSettings("/org/freedesktop/NetworkManagerSettings",
223 cfg.ConMaps())
225 def Connect(wanted_net): # any. or take arg. net is config name or ssid name
226 # ... in general, look for string in all config data. ssid for wifi, whatever for dialup
227 # TODO also respect autoconnect
229 # ActivateConn wants setting device ap; can find device from ap? ap is "specific" for wifi devices
230 #print "Connection wanted to", wanted_net
231 found_con = found_ap = found_dev = None
232 for dev in nm.Devices():
233 for ap in dev.APs():
234 if wanted_net == ap.Ssid():
235 found_ap = ap
236 found_dev = dev
237 break # FIXME both loops
238 found_con = us.GetByNet(wanted_net)
239 if found_ap == None:
240 print "No AP found with SSID", wanted_net
241 return False
242 if found_con == None:
243 print "No settings for net %s, assuming no key is needed" % wanted_net
244 c = mkconmap_wifi(wanted_net)
245 found_con = us.addCon(c)
246 nm.ActivateConnection(found_con, found_dev, found_ap) # TODO async
247 # TODO run loop, exit it when we have serviced the required calls
248 return True
250 if options.connect != None:
251 if options.unprotected:
252 c = mkconmap_wifi(options.connect)
253 us.addCon(c)
254 if options.wep_hex != None:
255 c = mkconmap_wep(options.connect, options.wep_hex)
256 us.addCon(c)
257 if options.wep_pass != None:
258 c = mkconmap_wep_pass(options.connect, options.wep_pass)
259 us.addCon(c)
260 if options.wpa_psk_hex != None:
261 c = mkconmap_psk(options.connect, options.wpa_psk_hex)
262 us.addCon(c)
263 if options.wpa_pass != None:
264 c = mkconmap_psk(options.connect, options.wpa_pass)
265 us.addCon(c)
266 nm.WatchState()
267 if Connect(options.connect):
268 LOOP = True
269 else:
270 fail = True
272 if options.activate_connection != None:
273 (svc, conpath, devpath, appath) = options.activate_connection.split(',')
274 if svc == "" or svc == "user":
275 svc = USC
276 elif svc == "system":
277 svc = SSC
279 if devpath == "":
280 TODO
281 if appath == "":
282 appath = "/"
283 nm.WatchState()
284 nm.nmi.ActivateConnection(svc, conpath, devpath, appath,
285 reply_handler=nm.silent_handler,
286 error_handler=nm.err_handler,
288 LOOP = True
290 if options.monitor:
291 m = Monitor(bus)
293 def loop():
294 loop = gobject.MainLoop()
295 try:
296 loop.run()
297 except:
298 print "Loop exited"
300 if LOOP:
301 loop()
303 if fail:
304 sys.exit(1)