1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 """\
21 X2GoControlSessionSTDOUT class - core functions for handling your individual X2Go sessions.
22
23 This backend handles X2Go server implementations that respond via server-side STDOUT.
24
25 """
26 __NAME__ = 'x2gocontrolsession-pylib'
27
28
29 import os
30 import types
31 import paramiko
32 import gevent
33 import copy
34 import string
35 import random
36 import re
37 import locale
38 import threading
39 import cStringIO
40
41 from gevent import socket
42
43
44 import x2go.sshproxy as sshproxy
45 import x2go.log as log
46 import x2go.utils as utils
47 import x2go.x2go_exceptions as x2go_exceptions
48 import x2go.defaults as defaults
49 import x2go.checkhosts as checkhosts
50
51 from x2go.backends.terminal import X2GoTerminalSession as _X2GoTerminalSession
52 from x2go.backends.info import X2GoServerSessionInfo as _X2GoServerSessionInfo
53 from x2go.backends.info import X2GoServerSessionList as _X2GoServerSessionList
54 from x2go.backends.proxy import X2GoProxy as _X2GoProxy
55
56 import x2go._paramiko
57 x2go._paramiko.monkey_patch_paramiko()
60 """\
61 In command strings X2Go server scripts expect blanks being rewritten to ,,X2GO_SPACE_CHAR''.
62 Commands get rewritten in the terminal sessions. This re-rewrite function helps
63 displaying command string in log output.
64
65 @param cmd: command that has to be rewritten for log output
66 @type cmd: C{str}
67
68 @return: the command with ,,X2GO_SPACE_CHAR'' re-replaced by blanks
69 @rtype: C{str}
70
71 """
72
73 if cmd:
74 cmd = cmd.replace("X2GO_SPACE_CHAR", " ")
75 return cmd
76
78 """\
79 In command strings Python X2Go replaces some macros with actual values:
80
81 - X2GO_USER -> the user name under which the user is authenticated via SSH
82 - X2GO_PASSWORD -> the password being used for SSH authentication
83
84 Both macros can be used to on-the-fly authenticate via RDP.
85
86 @param cmd: command that is to be sent to an X2Go server script
87 @type cmd: C{str}
88 @param user: the SSH authenticated user name
89 @type password: the password being used for SSH authentication
90
91 @return: the command with macros replaced
92 @rtype: C{str}
93
94 """
95
96
97 if cmd and user:
98 cmd = cmd.replace('X2GO_USER', user)
99
100
101 if cmd and password:
102 cmd = cmd.replace('X2GO_PASSWORD', password)
103 return cmd
104
107 """\
108 In the Python X2Go concept, X2Go sessions fall into two parts: a control session and one to many terminal sessions.
109
110 The control session handles the SSH based communication between server and client. It is mainly derived from
111 C{paramiko.SSHClient} and adds on X2Go related functionality.
112
113 """
114 associated_terminals = None
115
116 - def __init__(self,
117 profile_name='UNKNOWN',
118 add_to_known_hosts=False,
119 known_hosts=None,
120 forward_sshagent=False,
121 unique_hostkey_aliases=False,
122 terminal_backend=_X2GoTerminalSession,
123 info_backend=_X2GoServerSessionInfo,
124 list_backend=_X2GoServerSessionList,
125 proxy_backend=_X2GoProxy,
126 client_rootdir=os.path.join(defaults.LOCAL_HOME, defaults.X2GO_CLIENT_ROOTDIR),
127 sessions_rootdir=os.path.join(defaults.LOCAL_HOME, defaults.X2GO_SESSIONS_ROOTDIR),
128 ssh_rootdir=os.path.join(defaults.LOCAL_HOME, defaults.X2GO_SSH_ROOTDIR),
129 logger=None, loglevel=log.loglevel_DEFAULT,
130 published_applications_no_submenus=0,
131 low_latency=False,
132 **kwargs):
133 """\
134 Initialize an X2Go control session. For each connected session profile there will be one SSH-based
135 control session and one to many terminal sessions that all server-client-communicate via this one common control
136 session.
137
138 A control session normally gets set up by an L{X2GoSession} instance. Do not use it directly!!!
139
140 @param profile_name: the profile name of the session profile this control session works for
141 @type profile_name: C{str}
142 @param add_to_known_hosts: Auto-accept server host validity?
143 @type add_to_known_hosts: C{bool}
144 @param known_hosts: the underlying Paramiko/SSH systems C{known_hosts} file
145 @type known_hosts: C{str}
146 @param forward_sshagent: forward SSH agent authentication requests to the X2Go client-side
147 @type forward_sshagent: C{bool}
148 @param unique_hostkey_aliases: instead of storing [<hostname>]:<port> in known_hosts file, use the
149 (unique-by-design) profile ID
150 @type unique_hostkey_aliases: C{bool}
151 @param terminal_backend: X2Go terminal session backend to use
152 @type terminal_backend: C{class}
153 @param info_backend: backend for handling storage of server session information
154 @type info_backend: C{X2GoServerSessionInfo*} instance
155 @param list_backend: backend for handling storage of session list information
156 @type list_backend: C{X2GoServerSessionList*} instance
157 @param proxy_backend: backend for handling the X-proxy connections
158 @type proxy_backend: C{X2GoProxy*} instance
159 @param client_rootdir: client base dir (default: ~/.x2goclient)
160 @type client_rootdir: C{str}
161 @param sessions_rootdir: sessions base dir (default: ~/.x2go)
162 @type sessions_rootdir: C{str}
163 @param ssh_rootdir: ssh base dir (default: ~/.ssh)
164 @type ssh_rootdir: C{str}
165 @param published_applications_no_submenus: published applications menus with less items than C{published_applications_no_submenus}
166 are rendered without submenus
167 @type published_applications_no_submenus: C{int}
168 @param logger: you can pass an L{X2GoLogger} object to the
169 L{X2GoControlSessionSTDOUT} constructor
170 @type logger: L{X2GoLogger} instance
171 @param loglevel: if no L{X2GoLogger} object has been supplied a new one will be
172 constructed with the given loglevel
173 @type loglevel: C{int}
174 @param low_latency: set this boolean switch for weak connections, it will double all timeout values.
175 @type low_latency: C{bool}
176 @param kwargs: catch any non-defined parameters in C{kwargs}
177 @type kwargs: C{dict}
178
179 """
180 self.associated_terminals = {}
181 self.terminated_terminals = []
182
183 self.profile_name = profile_name
184 self.add_to_known_hosts = add_to_known_hosts
185 self.known_hosts = known_hosts
186 self.forward_sshagent = forward_sshagent
187 self.unique_hostkey_aliases = unique_hostkey_aliases
188
189 self.hostname = None
190 self.port = None
191
192 self.sshproxy_session = None
193
194 self._session_auth_rsakey = None
195 self._remote_home = None
196 self._remote_group = {}
197 self._remote_username = None
198 self._remote_peername = None
199
200 self._server_versions = None
201 self._server_features = None
202
203 if logger is None:
204 self.logger = log.X2GoLogger(loglevel=loglevel)
205 else:
206 self.logger = copy.deepcopy(logger)
207 self.logger.tag = __NAME__
208
209 self._terminal_backend = terminal_backend
210 self._info_backend = info_backend
211 self._list_backend = list_backend
212 self._proxy_backend = proxy_backend
213
214 self.client_rootdir = client_rootdir
215 self.sessions_rootdir = sessions_rootdir
216 self.ssh_rootdir = ssh_rootdir
217
218 self._published_applications_menu = {}
219
220 self.agent_chan = None
221 self.agent_handler = None
222
223 paramiko.SSHClient.__init__(self)
224 if self.add_to_known_hosts:
225 self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
226
227 self.session_died = False
228
229 self.low_latency = low_latency
230
231 self.published_applications_no_submenus = published_applications_no_submenus
232 self._already_querying_published_applications = threading.Lock()
233
234 self._transport_lock = threading.Lock()
235
237 """\
238 Get the hostname as stored in the properties of this control session.
239
240 @return: the hostname of the connected X2Go server
241 @rtype: C{str}
242
243 """
244 return self.hostname
245
247 """\
248 Get the port number of the SSH connection as stored in the properties of this control session.
249
250 @return: the server-side port number of the control session's SSH connection
251 @rtype: C{str}
252
253 """
254 return self.port
255
257 """\
258 Load known SSH host keys from the C{known_hosts} file.
259
260 If the file does not exist, create it first.
261
262 """
263 if self.known_hosts is not None:
264 utils.touch_file(self.known_hosts)
265 self.load_host_keys(self.known_hosts)
266
268 """\
269 On instance descruction, do a proper session disconnect from the server.
270
271 """
272 self.disconnect()
273
275 """
276 Put a local file on the remote server via sFTP.
277
278 During sFTP operations, remote command execution gets blocked.
279
280 @param local_path: full local path name of the file to be put on the server
281 @type local_path: C{str}
282 @param remote_path: full remote path name of the server-side target location, path names have to be Unix-compliant
283 @type remote_path: C{str}
284
285 @raise X2GoControlSessionException: if the SSH connection dropped out
286
287 """
288 ssh_transport = self.get_transport()
289 self._transport_lock.acquire()
290 if ssh_transport and ssh_transport.is_authenticated():
291 self.logger('sFTP-put: %s -> %s:%s' % (os.path.normpath(local_path), self.remote_peername(), remote_path), loglevel=log.loglevel_DEBUG)
292 self.sftp_client = paramiko.SFTPClient.from_transport(ssh_transport)
293 try:
294 self.sftp_client.put(os.path.normpath(local_path), remote_path)
295 except (x2go_exceptions.SSHException, socket.error, IOError):
296
297 self.session_died = True
298 self._transport_lock.release()
299 raise x2go_exceptions.X2GoControlSessionException('The SSH connection was dropped during an sFTP put action.')
300 self.sftp_client = None
301 self._transport_lock.release()
302
304 """
305 Create a text file on the remote server via sFTP.
306
307 During sFTP operations, remote command execution gets blocked.
308
309 @param remote_path: full remote path name of the server-side target location, path names have to be Unix-compliant
310 @type remote_path: C{str}
311 @param content: a text file, multi-line files use Unix-link EOL style
312 @type content: C{str}
313
314 @raise X2GoControlSessionException: if the SSH connection dropped out
315
316 """
317 ssh_transport = self.get_transport()
318 self._transport_lock.acquire()
319 if ssh_transport and ssh_transport.is_authenticated():
320 self.logger('sFTP-write: opening remote file %s on host %s for writing' % (remote_path, self.remote_peername()), loglevel=log.loglevel_DEBUG)
321 self.sftp_client = paramiko.SFTPClient.from_transport(ssh_transport)
322 try:
323 remote_fileobj = self.sftp_client.open(remote_path, 'w')
324 self.logger('sFTP-write: writing content: %s' % content, loglevel=log.loglevel_DEBUG_SFTPXFER)
325 remote_fileobj.write(content)
326 remote_fileobj.close()
327 except (x2go_exceptions.SSHException, socket.error, IOError):
328 self.session_died = True
329 self._transport_lock.release()
330 self.logger('sFTP-write: opening remote file %s on host %s failed' % (remote_path, self.remote_peername()), loglevel=log.loglevel_WARN)
331 raise x2go_exceptions.X2GoControlSessionException('The SSH connection was dropped during an sFTP write action.')
332 self.sftp_client = None
333 self._transport_lock.release()
334
336 """
337 Remote a remote file from the server via sFTP.
338
339 During sFTP operations, remote command execution gets blocked.
340
341 @param remote_path: full remote path name of the server-side file to be removed, path names have to be Unix-compliant
342 @type remote_path: C{str}
343
344 @raise X2GoControlSessionException: if the SSH connection dropped out
345
346 """
347 ssh_transport = self.get_transport()
348 self._transport_lock.acquire()
349 if ssh_transport and ssh_transport.is_authenticated():
350 self.logger('sFTP-write: removing remote file %s on host %s' % (remote_path, self.remote_peername()), loglevel=log.loglevel_DEBUG)
351 self.sftp_client = paramiko.SFTPClient.from_transport(ssh_transport)
352 try:
353 self.sftp_client.remove(remote_path)
354 except (x2go_exceptions.SSHException, socket.error, IOError):
355 self.session_died = True
356 self._transport_lock.release()
357 self.logger('sFTP-write: removing remote file %s on host %s failed' % (remote_path, self.remote_peername()), loglevel=log.loglevel_WARN)
358 raise x2go_exceptions.X2GoControlSessionException('The SSH connection was dropped during an sFTP remove action.')
359 self.sftp_client = None
360 self._transport_lock.release()
361
363 """
364 Execute an X2Go server-side command via SSH.
365
366 During SSH command executions, sFTP operations get blocked.
367
368 @param cmd_line: the command to be executed on the remote server
369 @type cmd_line: C{str} or C{list}
370 @param loglevel: use this loglevel for reporting about remote command execution
371 @type loglevel: C{int}
372 @param timeout: if commands take longer than C{<timeout>} to be executed, consider the control session connection
373 to have died.
374 @type timeout: C{int}
375 @param kwargs: parameters that get passed through to the C{paramiko.SSHClient.exec_command()} method.
376 @type kwargs: C{dict}
377
378 @return: C{True} if the command could be successfully executed on the remote X2Go server
379 @rtype: C{bool}
380
381 @raise X2GoControlSessionException: if the command execution failed (due to a lost connection)
382
383 """
384 if type(cmd_line) == types.ListType:
385 cmd = " ".join(cmd_line)
386 else:
387 cmd = cmd_line
388
389 cmd = 'sh -c \"%s\"' % cmd
390
391 if self.session_died:
392 self.logger("control session seams to be dead, not executing command ,,%s'' on X2Go server %s" % (_rerewrite_blanks(cmd), self.profile_name,), loglevel=loglevel)
393 return (cStringIO.StringIO(), cStringIO.StringIO(), cStringIO.StringIO('failed to execute command'))
394
395 self._transport_lock.acquire()
396
397 _retval = None
398
399 ssh_transport = self.get_transport()
400 if ssh_transport and ssh_transport.is_authenticated():
401
402 if self.low_latency: timeout = timeout * 2
403 timer = gevent.Timeout(timeout)
404 timer.start()
405 try:
406 self.logger("executing command on X2Go server ,,%s'': %s" % (self.profile_name, _rerewrite_blanks(cmd)), loglevel=loglevel)
407 _retval = self.exec_command(_rewrite_password(cmd, user=self.get_transport().get_username(), password=self._session_password), **kwargs)
408 except AttributeError:
409 self.session_died = True
410 self._transport_lock.release()
411 if self.sshproxy_session:
412 self.sshproxy_session.stop_thread()
413 raise x2go_exceptions.X2GoControlSessionException('the X2Go control session has died unexpectedly')
414 except EOFError:
415 self.session_died = True
416 self._transport_lock.release()
417 if self.sshproxy_session:
418 self.sshproxy_session.stop_thread()
419 raise x2go_exceptions.X2GoControlSessionException('the X2Go control session has died unexpectedly')
420 except x2go_exceptions.SSHException:
421 self.session_died = True
422 self._transport_lock.release()
423 if self.sshproxy_session:
424 self.sshproxy_session.stop_thread()
425 raise x2go_exceptions.X2GoControlSessionException('the X2Go control session has died unexpectedly')
426 except gevent.timeout.Timeout:
427 self.session_died = True
428 self._transport_lock.release()
429 if self.sshproxy_session:
430 self.sshproxy_session.stop_thread()
431 raise x2go_exceptions.X2GoControlSessionException('the X2Go control session command timed out')
432 except socket.error:
433 self.session_died = True
434 self._transport_lock.release()
435 if self.sshproxy_session:
436 self.sshproxy_session.stop_thread()
437 raise x2go_exceptions.X2GoControlSessionException('the X2Go control session has died unexpectedly')
438 finally:
439 timer.cancel()
440
441 else:
442 self._transport_lock.release()
443 raise x2go_exceptions.X2GoControlSessionException('the X2Go control session is not connected')
444
445 self._transport_lock.release()
446 return _retval
447
448 @property
450 """\
451 Render a dictionary of server-side X2Go components and their versions. Results get cached
452 once there has been one successful query.
453
454 """
455 if self._server_versions is None:
456 self._server_versions = {}
457 (stdin, stdout, stderr) = self._x2go_exec_command('which x2goversion >/dev/null && x2goversion')
458 _lines = stdout.read().split('\n')
459 for _line in _lines:
460 if ':' not in _line: continue
461 comp = _line.split(':')[0].strip()
462 version = _line.split(':')[1].strip()
463 self._server_versions.update({comp: version})
464 self.logger('server-side X2Go components and their versions are: %s' % self._server_versions, loglevel=log.loglevel_DEBUG)
465 return self._server_versions
466
468 """\
469 Do a query for the server-side list of X2Go components and their versions.
470
471 @param force: do not use the cached component list, really ask the server (again)
472 @type force: C{bool}
473
474 @return: dictionary of X2Go components (as keys) and their versions (as values)
475 @rtype: C{list}
476
477 """
478 if force:
479 self._server_versions = None
480 return self._x2go_server_versions
481 get_server_versions = query_server_versions
482
483 @property
485 """\
486 Render a list of server-side X2Go features. Results get cached once there has been one successful query.
487
488 """
489 if self._server_features is None:
490 (stdin, stdout, stderr) = self._x2go_exec_command('which x2gofeaturelist >/dev/null && x2gofeaturelist')
491 self._server_features = stdout.read().split('\n')
492 self._server_features = [ f for f in self._server_features if f ]
493 self._server_features.sort()
494 self.logger('server-side X2Go features are: %s' % self._server_features, loglevel=log.loglevel_DEBUG)
495 return self._server_features
496
498 """\
499 Do a query for the server-side list of X2Go features.
500
501 @param force: do not use the cached feature list, really ask the server (again)
502 @type force: C{bool}
503
504 @return: list of X2Go feature names
505 @rtype: C{list}
506
507 """
508 if force:
509 self._server_features = None
510 return self._x2go_server_features
511 get_server_features = query_server_features
512
513 @property
515 """\
516 Retrieve and cache the remote home directory location.
517
518 """
519 if self._remote_home is None:
520 (stdin, stdout, stderr) = self._x2go_exec_command('echo $HOME')
521 stdout_r = stdout.read()
522 if stdout_r:
523 self._remote_home = stdout_r.split()[0]
524 self.logger('remote user\' home directory: %s' % self._remote_home, loglevel=log.loglevel_DEBUG)
525 return self._remote_home
526 else:
527 return self._remote_home
528
530 """\
531 Retrieve and cache the members of a server-side POSIX group.
532
533 @param group: remote POSIX group name
534 @type group: C{str}
535
536 @return: list of POSIX group members
537 @rtype: C{list}
538
539 """
540 if not self._remote_group.has_key(group):
541 (stdin, stdout, stderr) = self._x2go_exec_command('getent group %s | cut -d":" -f4' % group)
542 self._remote_group[group] = stdout.read().split('\n')[0].split(',')
543 self.logger('remote %s group: %s' % (group, self._remote_group[group]), loglevel=log.loglevel_DEBUG)
544 return self._remote_group[group]
545 else:
546 return self._remote_group[group]
547
549 """\
550 Is the remote user allowed to launch X2Go sessions?
551
552 FIXME: this method is currently non-functional.
553
554 @param username: remote user name
555 @type username: C{str}
556
557 @return: C{True} if the remote user is allowed to launch X2Go sessions
558 @rtype: C{bool}
559
560 """
561
562
563
564
565
566
567 return True
568
570 """\
571 Check if the remote user is allowed to use SSHFS mounts.
572
573 @return: C{True} if the user is allowed to connect client-side shares to the X2Go session
574 @rtype: C{bool}
575
576 """
577 if self.remote_username() in self._x2go_remote_group('fuse'):
578 return True
579 return False
580
582 """\
583 Returns (and caches) the control session's remote username.
584
585 @return: SSH transport's user name
586 @rtype: C{str}
587
588 @raise X2GoControlSessionException: on SSH connection loss
589
590 """
591 if self._remote_username is None:
592 if self.get_transport() is not None:
593 try:
594 self._remote_username = self.get_transport().get_username()
595 except:
596 self.session_died = True
597 raise x2go_exceptions.X2GoControlSessionException('Lost connection to X2Go server')
598 return self._remote_username
599
601 """\
602 Returns (and caches) the control session's remote host (name or ip).
603
604 @return: SSH transport's peer name
605 @rtype: C{tuple}
606
607 @raise X2GoControlSessionException: on SSH connection loss
608
609 """
610 if self._remote_peername is None:
611 if self.get_transport() is not None:
612 try:
613 self._remote_peername = self.get_transport().getpeername()
614 except:
615 self.session_died = True
616 raise x2go_exceptions.X2GoControlSessionException('Lost connection to X2Go server')
617 return self._remote_peername
618
619 @property
621 """\
622 Generate (and cache) a temporary RSA host key for the lifetime of this control session.
623
624 """
625 if self._session_auth_rsakey is None:
626 self._session_auth_rsakey = paramiko.RSAKey.generate(defaults.RSAKEY_STRENGTH)
627 return self._session_auth_rsakey
628
630 """\
631 Manipulate the control session's profile name.
632
633 @param profile_name: new profile name for this control session
634 @type profile_name: C{str}
635
636 """
637 self.profile_name = profile_name
638
640 """\
641 Wraps around a Paramiko/SSH host key check.
642
643 @param hostname: the remote X2Go server's hostname
644 @type hostname: C{str}
645 @param port: the SSH port of the remote X2Go server
646 @type port: C{int}
647
648 @return: C{True} if the host key check succeeded, C{False} otherwise
649 @rtype: C{bool}
650
651 """
652
653 hostname = hostname.strip()
654
655
656 if hostname in ('localhost', 'localhost.localdomain'):
657 hostname = '127.0.0.1'
658
659 return checkhosts.check_ssh_host_key(self, hostname, port=port)
660
661 - def connect(self, hostname, port=22, username='', password='', pkey=None,
662 key_filename=None, timeout=None, allow_agent=False, look_for_keys=False,
663 use_sshproxy=False, sshproxy_host='', sshproxy_port=22, sshproxy_user='', sshproxy_password='', sshproxy_force_password_auth=False,
664 sshproxy_key_filename='', sshproxy_pkey=None, sshproxy_look_for_keys=False, sshproxy_allow_agent=False,
665 sshproxy_tunnel='',
666 forward_sshagent=None,
667 unique_hostkey_aliases=None,
668 session_instance=None,
669 add_to_known_hosts=False, force_password_auth=False):
670 """\
671 Connect to an X2Go server and authenticate to it. This method is directly
672 inherited from the C{paramiko.SSHClient} class. The features of the Paramiko
673 SSH client connect method are recited here. The parameters C{add_to_known_hosts},
674 C{force_password_auth}, C{session_instance} and all SSH proxy related parameters
675 have been added as X2Go specific parameters
676
677 The server's host key is checked against the system host keys
678 (see C{load_system_host_keys}) and any local host keys (C{load_host_keys}).
679 If the server's hostname is not found in either set of host keys, the missing host
680 key policy is used (see C{set_missing_host_key_policy}). The default policy is
681 to reject the key and raise an C{SSHException}.
682
683 Authentication is attempted in the following order of priority:
684
685 - The C{pkey} or C{key_filename} passed in (if any)
686 - Any key we can find through an SSH agent
687 - Any "id_rsa" or "id_dsa" key discoverable in C{~/.ssh/}
688 - Plain username/password auth, if a password was given
689
690 If a private key requires a password to unlock it, and a password is
691 passed in, that password will be used to attempt to unlock the key.
692
693 @param hostname: the server to connect to
694 @type hostname: C{str}
695 @param port: the server port to connect to
696 @type port: C{int}
697 @param username: the username to authenticate as (defaults to the
698 current local username)
699 @type username: C{str}
700 @param password: a password to use for authentication or for unlocking
701 a private key
702 @type password: C{str}
703 @param key_filename: the filename, or list of filenames, of optional
704 private key(s) to try for authentication
705 @type key_filename: C{str} or list(str)
706 @param pkey: an optional private key to use for authentication
707 @type pkey: C{PKey}
708 @param forward_sshagent: forward SSH agent authentication requests to the X2Go client-side
709 (will update the class property of the same name)
710 @type forward_sshagent: C{bool}
711 @param unique_hostkey_aliases: update the unique_hostkey_aliases class property
712 @type unique_hostkey_aliases: C{bool}
713 @param timeout: an optional timeout (in seconds) for the TCP connect
714 @type timeout: float
715 @param look_for_keys: set to C{True} to enable searching for discoverable
716 private key files in C{~/.ssh/}
717 @type look_for_keys: C{bool}
718 @param allow_agent: set to C{True} to enable connecting to a local SSH agent
719 for acquiring authentication information
720 @type allow_agent: C{bool}
721 @param add_to_known_hosts: non-paramiko option, if C{True} paramiko.AutoAddPolicy()
722 is used as missing-host-key-policy. If set to C{False} paramiko.RejectPolicy()
723 is used
724 @type add_to_known_hosts: C{bool}
725 @param force_password_auth: non-paramiko option, disable pub/priv key authentication
726 completely, even if the C{pkey} or the C{key_filename} parameter is given
727 @type force_password_auth: C{bool}
728 @param session_instance: an instance L{X2GoSession} using this L{X2GoControlSessionSTDOUT}
729 instance.
730 @type session_instance: C{obj}
731 @param use_sshproxy: connect through an SSH proxy
732 @type use_sshproxy: C{True} if an SSH proxy is to be used for tunneling the connection
733 @param sshproxy_host: hostname of the SSH proxy server
734 @type sshproxy_host: C{str}
735 @param sshproxy_port: port of the SSH proxy server
736 @type sshproxy_port: C{int}
737 @param sshproxy_user: username that we use for authenticating against C{<sshproxy_host>}
738 @type sshproxy_user: C{str}
739 @param sshproxy_password: a password to use for SSH proxy authentication or for unlocking
740 a private key
741 @type sshproxy_password: C{str}
742 @param sshproxy_force_password_auth: enforce using a given C{sshproxy_password} even if a key(file) is given
743 @type sshproxy_force_password_auth: C{bool}
744 @param sshproxy_key_filename: local file location of the private key file
745 @type sshproxy_key_filename: C{str}
746 @param sshproxy_pkey: an optional private key to use for SSH proxy authentication
747 @type sshproxy_pkey: C{PKey}
748 @param sshproxy_look_for_keys: set to C{True} to enable connecting to a local SSH agent
749 for acquiring authentication information (for SSH proxy authentication)
750 @type sshproxy_look_for_keys: C{bool}
751 @param sshproxy_allow_agent: set to C{True} to enable connecting to a local SSH agent
752 for acquiring authentication information (for SSH proxy authentication)
753 @type sshproxy_allow_agent: C{bool}
754 @param sshproxy_tunnel: the SSH proxy tunneling parameters, format is: <local-address>:<local-port>:<remote-address>:<remote-port>
755 @type sshproxy_tunnel: C{str}
756
757 @return: C{True} if an authenticated SSH transport could be retrieved by this method
758 @rtype: C{bool}
759
760 @raise BadHostKeyException: if the server's host key could not be
761 verified
762 @raise AuthenticationException: if authentication failed
763 @raise SSHException: if there was any other error connecting or
764 establishing an SSH session
765 @raise socket.error: if a socket error occurred while connecting
766 @raise X2GoSSHProxyException: any SSH proxy exception is passed through while establishing the SSH proxy connection and tunneling setup
767 @raise X2GoSSHAuthenticationException: any SSH proxy authentication exception is passed through while establishing the SSH proxy connection and tunneling setup
768 @raise X2GoRemoteHomeException: if the remote home directory does not exist or is not accessible
769
770 """
771 _fake_hostname = None
772
773 if unique_hostkey_aliases is not None:
774 self.unique_hostkey_aliases = unique_hostkey_aliases
775
776
777 if self.unique_hostkey_aliases:
778 _fake_hostname = "[%s]:%s" % (hostname, port)
779
780 if use_sshproxy and sshproxy_host and sshproxy_user:
781 try:
782
783 if not sshproxy_tunnel:
784 sshproxy_tunnel = "localhost:44444:%s:%s" % (hostname, port)
785 self.sshproxy_session = sshproxy.X2GoSSHProxy(known_hosts=self.known_hosts,
786 sshproxy_host=sshproxy_host,
787 sshproxy_port=sshproxy_port,
788 sshproxy_user=sshproxy_user,
789 sshproxy_password=sshproxy_password,
790 sshproxy_force_password_auth=sshproxy_force_password_auth,
791 sshproxy_key_filename=sshproxy_key_filename,
792 sshproxy_pkey=sshproxy_pkey,
793 sshproxy_look_for_keys=sshproxy_look_for_keys,
794 sshproxy_allow_agent=sshproxy_allow_agent,
795 sshproxy_tunnel=sshproxy_tunnel,
796 session_instance=session_instance,
797 logger=self.logger,
798 )
799 hostname = self.sshproxy_session.get_local_proxy_host()
800 port = self.sshproxy_session.get_local_proxy_port()
801 _fake_hostname = self.sshproxy_session.get_remote_host()
802 _fake_port = self.sshproxy_session.get_remote_port()
803 _fake_hostname = "[%s]:%s" % (_fake_hostname, _fake_port)
804
805 except:
806 if self.sshproxy_session:
807 self.sshproxy_session.stop_thread()
808 self.sshproxy_session = None
809 raise
810
811 if self.sshproxy_session is not None:
812 self.sshproxy_session.start()
813
814
815
816 gevent.sleep(.1)
817 port = self.sshproxy_session.get_local_proxy_port()
818
819 if not add_to_known_hosts and session_instance:
820 self.set_missing_host_key_policy(checkhosts.X2GoInteractiveAddPolicy(caller=self, session_instance=session_instance, fake_hostname=_fake_hostname))
821
822 if add_to_known_hosts:
823 self.set_missing_host_key_policy(checkhosts.X2GoAutoAddPolicy(caller=self, session_instance=session_instance, fake_hostname=_fake_hostname))
824
825
826 if force_password_auth:
827 key_filename = None
828 pkey = None
829
830
831 hostname = hostname.strip()
832
833 self.logger('connecting to [%s]:%s' % (hostname, port), loglevel=log.loglevel_NOTICE)
834
835 self.load_session_host_keys()
836
837 _hostname = hostname
838
839 if _hostname in ('localhost', 'localhost.localdomain'):
840 _hostname = '127.0.0.1'
841
842
843 if forward_sshagent is not None:
844 self.forward_sshagent = forward_sshagent
845
846 if timeout and self.low_latency:
847 timeout = timeout * 2
848
849 if key_filename or pkey or look_for_keys or allow_agent or (password and force_password_auth):
850 try:
851 if password and force_password_auth:
852 self.logger('trying keyboard-interactive SSH authentication with server', loglevel=log.loglevel_DEBUG)
853 paramiko.SSHClient.connect(self, _hostname, port=port, username=username, pkey=None, password=password,
854 key_filename=None, timeout=timeout, allow_agent=False,
855 look_for_keys=False)
856 elif (key_filename and os.path.exists(os.path.normpath(key_filename))) or pkey:
857 self.logger('trying SSH pub/priv key authentication with server', loglevel=log.loglevel_DEBUG)
858 paramiko.SSHClient.connect(self, _hostname, port=port, username=username, pkey=pkey,
859 key_filename=key_filename, timeout=timeout, allow_agent=allow_agent,
860 look_for_keys=look_for_keys)
861 else:
862 self.logger('trying SSH key discovery or agent authentication with server', loglevel=log.loglevel_DEBUG)
863 try:
864 paramiko.SSHClient.connect(self, _hostname, port=port, username=username, pkey=None,
865 key_filename=None, timeout=timeout, allow_agent=allow_agent,
866 look_for_keys=look_for_keys)
867 except paramiko.SSHException, e:
868 if str(e) == 'No authentication methods available':
869 raise paramiko.AuthenticationException('Interactive password authentication required!')
870 else:
871 self.close()
872 if self.sshproxy_session:
873 self.sshproxy_session.stop_thread()
874 raise(e)
875
876
877 t = self.get_transport()
878 if x2go._paramiko.PARAMIKO_FEATURE['use-compression']:
879 t.use_compression(compress=True)
880
881 except paramiko.AuthenticationException, e:
882 self.close()
883 if password:
884 self.logger('next auth mechanism we\'ll try is keyboard-interactive authentication', loglevel=log.loglevel_DEBUG)
885 try:
886 paramiko.SSHClient.connect(self, _hostname, port=port, username=username, password=password,
887 key_filename=None, pkey=None, timeout=timeout, allow_agent=False, look_for_keys=False)
888 except:
889 self.close()
890 if self.sshproxy_session:
891 self.sshproxy_session.stop_thread()
892 raise
893 else:
894 self.close()
895 if self.sshproxy_session:
896 self.sshproxy_session.stop_thread()
897 raise(e)
898
899 except:
900 self.close()
901 if self.sshproxy_session:
902 self.sshproxy_session.stop_thread()
903 raise
904
905
906 else:
907
908 if not password:
909 password = "".join([random.choice(string.letters+string.digits) for x in range(1, 20)])
910 self.logger('performing SSH keyboard-interactive authentication with server', loglevel=log.loglevel_DEBUG)
911 try:
912 paramiko.SSHClient.connect(self, _hostname, port=port, username=username, password=password,
913 timeout=timeout, allow_agent=False, look_for_keys=False)
914 except paramiko.AuthenticationException, e:
915 self.close()
916 if self.sshproxy_session:
917 self.sshproxy_session.stop_thread()
918 raise e
919 except:
920 self.close()
921 if self.sshproxy_session:
922 self.sshproxy_session.stop_thread()
923 raise
924
925 self.set_missing_host_key_policy(paramiko.RejectPolicy())
926
927 self.hostname = hostname
928 self.port = port
929
930
931 ssh_transport = self.get_transport()
932 ssh_transport.reverse_tunnels = {}
933
934
935 ssh_transport._x2go_session_marker = True
936 self._session_password = password
937
938 if ssh_transport is not None:
939 self.session_died = False
940 self.query_server_features(force=True)
941 if self.forward_sshagent:
942 if x2go._paramiko.PARAMIKO_FEATURE['forward-ssh-agent']:
943 self.agent_chan = ssh_transport.open_session()
944 self.agent_handler = paramiko.agent.AgentRequestHandler(self.agent_chan)
945 self.logger('Requesting SSH agent forwarding for control session of connected session profile %s' % self.profile_name, loglevel=log.loglevel_INFO)
946 else:
947 self.logger('SSH agent forwarding is not available in the Paramiko version used with this instance of Python X2Go', loglevel=log.loglevel_WARN)
948 else:
949 self.close()
950 if self.sshproxy_session:
951 self.sshproxy_session.stop_thread()
952
953 self._remote_home = None
954 if not self.home_exists():
955 self.close()
956 if self.sshproxy_session:
957 self.sshproxy_session.stop_thread()
958 raise x2go_exceptions.X2GoRemoteHomeException('remote home directory does not exist')
959
960 return (self.get_transport() is not None)
961
963 """\
964 Drop an associated terminal session.
965
966 @param terminal_session: the terminal session object to remove from the list of associated terminals
967 @type terminal_session: C{X2GoTerminalSession*}
968
969 """
970 for t_name in self.associated_terminals.keys():
971 if self.associated_terminals[t_name] == terminal_session:
972 del self.associated_terminals[t_name]
973 if self.terminated_terminals.has_key(t_name):
974 del self.terminated_terminals[t_name]
975
977 """\
978 Disconnect this control session from the remote server.
979
980 @return: report success or failure after having disconnected
981 @rtype: C{bool}
982
983 """
984 if self.associated_terminals:
985 t_names = self.associated_terminals.keys()
986 for t_obj in self.associated_terminals.values():
987 try:
988 if not self.session_died:
989 t_obj.suspend()
990 except x2go_exceptions.X2GoTerminalSessionException:
991 pass
992 except x2go_exceptions.X2GoControlSessionException:
993 self.session_died
994 t_obj.__del__()
995 for t_name in t_names:
996 try:
997 del self.associated_terminals[t_name]
998 except KeyError:
999 pass
1000
1001 self._remote_home = None
1002 self._remote_group = {}
1003
1004 self._session_auth_rsakey = None
1005
1006
1007 self._transport_lock.release()
1008
1009
1010 if self.agent_handler is not None:
1011 self.agent_handler.close()
1012
1013 if self.agent_chan is not None:
1014 self.agent_chan.close()
1015
1016 retval = False
1017 try:
1018 if self.get_transport() is not None:
1019 retval = self.get_transport().is_active()
1020 try:
1021 self.close()
1022 except IOError:
1023 pass
1024 except AttributeError:
1025
1026
1027 pass
1028
1029
1030 if self.sshproxy_session is not None:
1031 self.sshproxy_session.stop_thread()
1032
1033 return retval
1034
1036 """\
1037 Test if the remote home directory exists.
1038
1039 @return: C{True} if the home directory exists, C{False} otherwise
1040 @rtype: C{bool}
1041
1042 """
1043 (_stdin, _stdout, _stderr) = self._x2go_exec_command('stat -tL "%s"' % self._x2go_remote_home, loglevel=log.loglevel_DEBUG)
1044 if _stdout.read():
1045 return True
1046 return False
1047
1048
1050 """\
1051 Test if the connection to the remote X2Go server is still alive.
1052
1053 @return: C{True} if the connection is still alive, C{False} otherwise
1054 @rtype: C{bool}
1055
1056 """
1057 try:
1058 if self._x2go_exec_command('echo', loglevel=log.loglevel_DEBUG):
1059 return True
1060 except x2go_exceptions.X2GoControlSessionException:
1061 self.session_died = True
1062 self.disconnect()
1063 return False
1064
1066 """\
1067 Test if the connection to the remote X2Go server died on the way.
1068
1069 @return: C{True} if the connection has died, C{False} otherwise
1070 @rtype: C{bool}
1071
1072 """
1073 return self.session_died
1074
1076 """\
1077 Retrieve the menu tree of published applications from the remote X2Go server.
1078
1079 The C{raw} option lets this method return a C{list} of C{dict} elements. Each C{dict} elements has a
1080 C{desktop} key containing a shortened version of the text output of a .desktop file and an C{icon} key
1081 which contains the desktop base64-encoded icon data.
1082
1083 The {very_raw} lets this method return the output of the C{x2gogetapps} script as is.
1084
1085 @param lang: locale/language identifier
1086 @type lang: C{str}
1087 @param refresh: force reload of the menu tree from X2Go server
1088 @type refresh: C{bool}
1089 @param raw: retrieve a raw output of the server list of published applications
1090 @type raw: C{bool}
1091 @param very_raw: retrieve a very raw output of the server list of published applications
1092 @type very_raw: C{bool}
1093
1094 @return: an i18n capable menu tree packed as a Python dictionary
1095 @rtype: C{list}
1096
1097 """
1098 self._already_querying_published_applications.acquire()
1099
1100 if defaults.X2GOCLIENT_OS != 'Windows' and lang is None:
1101 lang = locale.getdefaultlocale()[0]
1102 elif lang is None:
1103 lang = 'en'
1104
1105 if 'X2GO_PUBLISHED_APPLICATIONS' in self.get_server_features():
1106 if self._published_applications_menu is {} or \
1107 not self._published_applications_menu.has_key(lang) or \
1108 raw or very_raw or refresh or \
1109 (self.published_applications_no_submenus != max_no_submenus):
1110
1111 self.published_applications_no_submenus = max_no_submenus
1112
1113
1114
1115 self.logger('querying server (%s) for list of published applications' % self.profile_name, loglevel=log.loglevel_NOTICE)
1116 (stdin, stdout, stderr) = self._x2go_exec_command('which x2gogetapps >/dev/null && x2gogetapps')
1117 _raw_output = stdout.read()
1118
1119 if very_raw:
1120 self.logger('published applications query for %s finished, return very raw output' % self.profile_name, loglevel=log.loglevel_NOTICE)
1121 self._already_querying_published_applications.release()
1122 return _raw_output
1123
1124
1125
1126 _raw_menu_items = _raw_output.split('</desktop>\n')
1127 _raw_menu_items = [ i.replace('<desktop>\n', '') for i in _raw_menu_items ]
1128 _menu = []
1129 for _raw_menu_item in _raw_menu_items:
1130 if '<icon>\n' in _raw_menu_item and '</icon>' in _raw_menu_item:
1131 _menu_item = _raw_menu_item.split('<icon>\n')[0] + _raw_menu_item.split('</icon>\n')[1]
1132 _icon_base64 = _raw_menu_item.split('<icon>\n')[1].split('</icon>\n')[0]
1133 else:
1134 _menu_item = _raw_menu_item
1135 _icon_base64 = None
1136 if _menu_item:
1137 _menu.append({ 'desktop': _menu_item, 'icon': _icon_base64, })
1138 _menu_item = None
1139 _icon_base64 = None
1140
1141 if raw:
1142 self.logger('published applications query for %s finished, returning raw output' % self.profile_name, loglevel=log.loglevel_NOTICE)
1143 self._already_querying_published_applications.release()
1144 return _menu
1145
1146 if len(_menu) > max_no_submenus >= 0:
1147 _render_submenus = True
1148 else:
1149 _render_submenus = False
1150
1151
1152
1153 _category_map = {
1154 lang: {
1155 'Multimedia': [],
1156 'Development': [],
1157 'Education': [],
1158 'Games': [],
1159 'Graphics': [],
1160 'Internet': [],
1161 'Office': [],
1162 'System': [],
1163 'Utilities': [],
1164 'Other Applications': [],
1165 'TOP': [],
1166 }
1167 }
1168 _empty_menus = _category_map[lang].keys()
1169
1170 for item in _menu:
1171
1172 _menu_entry_name = ''
1173 _menu_entry_fallback_name = ''
1174 _menu_entry_comment = ''
1175 _menu_entry_fallback_comment = ''
1176 _menu_entry_exec = ''
1177 _menu_entry_cat = ''
1178 _menu_entry_shell = False
1179
1180 lang_regio = lang
1181 lang_only = lang_regio.split('_')[0]
1182
1183 for line in item['desktop'].split('\n'):
1184 if re.match('^Name\[%s\]=.*' % lang_regio, line) or re.match('Name\[%s\]=.*' % lang_only, line):
1185 _menu_entry_name = line.split("=")[1].strip()
1186 elif re.match('^Name=.*', line):
1187 _menu_entry_fallback_name = line.split("=")[1].strip()
1188 elif re.match('^Comment\[%s\]=.*' % lang_regio, line) or re.match('Comment\[%s\]=.*' % lang_only, line):
1189 _menu_entry_comment = line.split("=")[1].strip()
1190 elif re.match('^Comment=.*', line):
1191 _menu_entry_fallback_comment = line.split("=")[1].strip()
1192 elif re.match('^Exec=.*', line):
1193 _menu_entry_exec = line.split("=")[1].strip()
1194 elif re.match('^Terminal=.*(t|T)(r|R)(u|U)(e|E).*', line):
1195 _menu_entry_shell = True
1196 elif re.match('^Categories=.*', line):
1197 if 'X2Go-Top' in line:
1198 _menu_entry_cat = 'TOP'
1199 elif 'Audio' in line or 'Video' in line:
1200 _menu_entry_cat = 'Multimedia'
1201 elif 'Development' in line:
1202 _menu_entry_cat = 'Development'
1203 elif 'Education' in line:
1204 _menu_entry_cat = 'Education'
1205 elif 'Game' in line:
1206 _menu_entry_cat = 'Games'
1207 elif 'Graphics' in line:
1208 _menu_entry_cat = 'Graphics'
1209 elif 'Network' in line:
1210 _menu_entry_cat = 'Internet'
1211 elif 'Office' in line:
1212 _menu_entry_cat = 'Office'
1213 elif 'Settings' in line:
1214 continue
1215 elif 'System' in line:
1216 _menu_entry_cat = 'System'
1217 elif 'Utility' in line:
1218 _menu_entry_cat = 'Utilities'
1219 else:
1220 _menu_entry_cat = 'Other Applications'
1221
1222 if not _menu_entry_exec:
1223 continue
1224 else:
1225
1226 _menu_entry_exec = _menu_entry_exec.replace('%f', '').replace('%F','').replace('%u','').replace('%U','')
1227 if _menu_entry_shell:
1228 _menu_entry_exec = "x-terminal-emulator -e '%s'" % _menu_entry_exec
1229
1230 if not _menu_entry_cat:
1231 _menu_entry_cat = 'Other Applications'
1232
1233 if not _render_submenus:
1234 _menu_entry_cat = 'TOP'
1235
1236 if _menu_entry_cat in _empty_menus:
1237 _empty_menus.remove(_menu_entry_cat)
1238
1239 if not _menu_entry_name: _menu_entry_name = _menu_entry_fallback_name
1240 if not _menu_entry_comment: _menu_entry_comment = _menu_entry_fallback_comment
1241 if not _menu_entry_comment: _menu_entry_comment = _menu_entry_name
1242
1243 _menu_entry_icon = item['icon']
1244
1245 _category_map[lang][_menu_entry_cat].append(
1246 {
1247 'name': _menu_entry_name,
1248 'comment': _menu_entry_comment,
1249 'exec': _menu_entry_exec,
1250 'icon': _menu_entry_icon,
1251 }
1252 )
1253
1254 for _cat in _empty_menus:
1255 del _category_map[lang][_cat]
1256
1257 for _cat in _category_map[lang].keys():
1258 _sorted = sorted(_category_map[lang][_cat], key=lambda k: k['name'])
1259 _category_map[lang][_cat] = _sorted
1260
1261 self._published_applications_menu.update(_category_map)
1262 self.logger('published applications query for %s finished, return menu tree' % self.profile_name, loglevel=log.loglevel_NOTICE)
1263
1264 else:
1265
1266 pass
1267
1268 self._already_querying_published_applications.release()
1269 return self._published_applications_menu
1270
1271 - def start(self, **kwargs):
1272 """\
1273 Start a new X2Go session.
1274
1275 The L{X2GoControlSessionSTDOUT.start()} method accepts any parameter
1276 that can be passed to any of the C{X2GoTerminalSession} backend class
1277 constructors.
1278
1279 @param kwargs: parameters that get passed through to the control session's
1280 L{resume()} method, only the C{session_name} parameter will get removed
1281 before pass-through
1282 @type kwargs: C{dict}
1283
1284 @return: return value of the cascaded L{resume()} method, denoting the success or failure
1285 of the session startup
1286 @rtype: C{bool}
1287
1288 """
1289 if 'session_name' in kwargs.keys():
1290 del kwargs['session_name']
1291 return self.resume(**kwargs)
1292
1293 - def resume(self, session_name=None, session_instance=None, session_list=None, **kwargs):
1294 """\
1295 Resume a running/suspended X2Go session.
1296
1297 The L{X2GoControlSessionSTDOUT.resume()} method accepts any parameter
1298 that can be passed to any of the C{X2GoTerminalSession*} backend class constructors.
1299
1300 @return: True if the session could be successfully resumed
1301 @rtype: C{bool}
1302
1303 @raise X2GoUserException: if the remote user is not allowed to launch/resume X2Go sessions.
1304
1305 """
1306 if not self.is_x2gouser(self.get_transport().get_username()):
1307 raise x2go_exceptions.X2GoUserException('remote user %s is not allowed to run X2Go commands' % self.get_transport().get_username())
1308
1309 session_info = None
1310 try:
1311 if session_name is not None:
1312 if session_list:
1313 session_info = session_list[session_name]
1314 else:
1315 session_info = self.list_sessions()[session_name]
1316 except KeyError:
1317 _success = False
1318
1319 _terminal = self._terminal_backend(self,
1320 profile_name=self.profile_name,
1321 session_info=session_info,
1322 info_backend=self._info_backend,
1323 list_backend=self._list_backend,
1324 proxy_backend=self._proxy_backend,
1325 client_rootdir=self.client_rootdir,
1326 session_instance=session_instance,
1327 sessions_rootdir=self.sessions_rootdir,
1328 **kwargs)
1329
1330 _success = False
1331 try:
1332 if session_name is not None:
1333 _success = _terminal.resume()
1334 else:
1335 _success = _terminal.start()
1336 except x2go_exceptions.X2GoTerminalSessionException:
1337 _success = False
1338
1339 if _success:
1340 while not _terminal.ok():
1341 gevent.sleep(.2)
1342
1343 if _terminal.ok():
1344 self.associated_terminals[_terminal.get_session_name()] = _terminal
1345 self.get_transport().reverse_tunnels[_terminal.get_session_name()] = {
1346 'sshfs': (0, None),
1347 'snd': (0, None),
1348 }
1349
1350 return _terminal or None
1351
1352 return None
1353
1354 - def share_desktop(self, desktop=None, user=None, display=None, share_mode=0, **kwargs):
1355 """\
1356 Share another already running desktop session. Desktop sharing can be run
1357 in two different modes: view-only and full-access mode.
1358
1359 @param desktop: desktop ID of a sharable desktop in format C{<user>@<display>}
1360 @type desktop: C{str}
1361 @param user: user name and display number can be given separately, here give the
1362 name of the user who wants to share a session with you
1363 @type user: C{str}
1364 @param display: user name and display number can be given separately, here give the
1365 number of the display that a user allows you to be shared with
1366 @type display: C{str}
1367 @param share_mode: desktop sharing mode, 0 stands for VIEW-ONLY, 1 for FULL-ACCESS mode
1368 @type share_mode: C{int}
1369
1370 @return: True if the session could be successfully shared
1371 @rtype: C{bool}
1372
1373 @raise X2GoDesktopSharingException: if C{username} and C{dislpay} do not relate to a
1374 sharable desktop session
1375
1376 """
1377 if desktop:
1378 user = desktop.split('@')[0]
1379 display = desktop.split('@')[1]
1380 if not (user and display):
1381 raise x2go_exceptions.X2GoDesktopSharingException('Need user name and display number of shared desktop.')
1382
1383 cmd = '%sXSHAD%sXSHAD%s' % (share_mode, user, display)
1384
1385 kwargs['cmd'] = cmd
1386 kwargs['session_type'] = 'shared'
1387
1388 return self.start(**kwargs)
1389
1391 """\
1392 List all desktop-like sessions of current user (or of users that have
1393 granted desktop sharing) on the connected server.
1394
1395 @param raw: if C{True}, the raw output of the server-side X2Go command
1396 C{x2golistdesktops} is returned.
1397 @type raw: C{bool}
1398
1399 @return: a list of X2Go desktops available for sharing
1400 @rtype: C{list}
1401
1402 @raise X2GoTimeOutException: on command execution timeouts, with the server-side C{x2golistdesktops}
1403 command this can sometimes happen. Make sure you ignore these time-outs and to try again
1404
1405 """
1406 if raw:
1407 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && x2golistdesktops")
1408 return stdout.read(), stderr.read()
1409
1410 else:
1411
1412
1413
1414
1415 if self.low_latency:
1416 maxwait = maxwait * 2
1417
1418 timeout = gevent.Timeout(maxwait)
1419 timeout.start()
1420 try:
1421 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && x2golistdesktops")
1422 _stdout_read = stdout.read()
1423 _listdesktops = _stdout_read.split('\n')
1424 except gevent.timeout.Timeout:
1425
1426
1427
1428 raise x2go_exceptions.X2GoTimeOutException('x2golistdesktop command timed out')
1429 finally:
1430 timeout.cancel()
1431
1432 return _listdesktops
1433
1434 - def list_mounts(self, session_name, raw=False, maxwait=20):
1435 """\
1436 List all mounts for a given session of the current user on the connected server.
1437
1438 @param session_name: name of a session to query a list of mounts for
1439 @type session_name: C{str}
1440 @param raw: if C{True}, the raw output of the server-side X2Go command
1441 C{x2golistmounts} is returned.
1442 @type raw: C{bool}
1443 @param maxwait: stop processing C{x2golistmounts} after C{<maxwait>} seconds
1444 @type maxwait: C{int}
1445
1446 @return: a list of client-side mounts for X2Go session C{<session_name>} on the server
1447 @rtype: C{list}
1448
1449 @raise X2GoTimeOutException: on command execution timeouts, queries with the server-side
1450 C{x2golistmounts} query should normally be processed quickly, a time-out may hint that the
1451 control session has lost its connection to the X2Go server
1452
1453 """
1454 if raw:
1455 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && x2golistmounts %s" % session_name)
1456 return stdout.read(), stderr.read()
1457
1458 else:
1459
1460 if self.low_latency:
1461 maxwait = maxwait * 2
1462
1463
1464
1465 timeout = gevent.Timeout(maxwait)
1466 timeout.start()
1467 try:
1468 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && x2golistmounts %s" % session_name)
1469 _stdout_read = stdout.read()
1470 _listmounts = {session_name: [ line for line in _stdout_read.split('\n') if line ] }
1471 except gevent.timeout.Timeout:
1472
1473
1474 raise x2go_exceptions.X2GoTimeOutException('x2golistmounts command timed out')
1475 finally:
1476 timeout.cancel()
1477
1478 return _listmounts
1479
1481 """\
1482 List all sessions of current user on the connected server.
1483
1484 @param raw: if C{True}, the raw output of the server-side X2Go command
1485 C{x2golistsessions} is returned.
1486 @type raw: C{bool}
1487
1488 @return: normally an instance of a C{X2GoServerSessionList*} backend is returned. However,
1489 if the raw argument is set, the plain text output of the server-side C{x2golistsessions}
1490 command is returned
1491 @rtype: C{X2GoServerSessionList} instance or str
1492
1493 @raise X2GoControlSessionException: on command execution timeouts, if this happens the control session will
1494 be interpreted as disconnected due to connection loss
1495 """
1496 if raw:
1497 if 'X2GO_LIST_SHADOWSESSIONS' in self._x2go_server_features:
1498 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && { x2golistsessions; x2golistshadowsessions; }")
1499 else:
1500 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && x2golistsessions")
1501 return stdout.read(), stderr.read()
1502
1503 else:
1504
1505
1506
1507 _listsessions = {}
1508 _success = False
1509 _count = 0
1510 _maxwait = 20
1511
1512
1513
1514 while not _success and _count < _maxwait:
1515 _count += 1
1516 try:
1517 if 'X2GO_LIST_SHADOWSESSIONS' in self._x2go_server_features:
1518 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && { x2golistsessions; x2golistshadowsessions; }")
1519 else:
1520 (stdin, stdout, stderr) = self._x2go_exec_command("export HOSTNAME && x2golistsessions")
1521 _stdout_read = stdout.read()
1522 _listsessions = self._list_backend(_stdout_read, info_backend=self._info_backend).sessions
1523 _success = True
1524 except KeyError:
1525 gevent.sleep(1)
1526 except IndexError:
1527 gevent.sleep(1)
1528 except ValueError:
1529 gevent.sleep(1)
1530
1531 if _count >= _maxwait:
1532 self.session_died = True
1533 self.disconnect()
1534 raise x2go_exceptions.X2GoControlSessionException('x2golistsessions command failed after we have tried 20 times')
1535
1536
1537 for _session_name, _terminal in self.associated_terminals.items():
1538 if _session_name in _listsessions.keys():
1539
1540 if hasattr(self.associated_terminals[_session_name], 'session_info') and not self.associated_terminals[_session_name].is_session_info_protected():
1541 self.associated_terminals[_session_name].session_info.update(_listsessions[_session_name])
1542 else:
1543 try: del self.associated_terminals[_session_name]
1544 except KeyError: pass
1545 self.terminated_terminals.append(_session_name)
1546 if _terminal.is_suspended():
1547 try: del self.associated_terminals[_session_name]
1548 except KeyError: pass
1549
1550
1551 return _listsessions
1552
1553 - def clean_sessions(self, destroy_terminals=True, published_applications=False):
1554 """\
1555 Find X2Go terminals that have previously been started by the
1556 connected user on the remote X2Go server and terminate them.
1557
1558 @param destroy_terminals: destroy the terminal session instances after cleanup
1559 @type destroy_terminals: C{bool}
1560 @param published_applications: also clean up published applications providing sessions
1561 @type published_applications: C{bool}
1562
1563 """
1564 session_list = self.list_sessions()
1565 if published_applications:
1566 session_names = session_list.keys()
1567 else:
1568 session_names = [ _sn for _sn in session_list.keys() if not session_list[_sn].is_published_applications_provider() ]
1569 for session_name in session_names:
1570 self.terminate(session_name=session_name, destroy_terminals=destroy_terminals)
1571
1573 """\
1574 Returns C{True} if this control session is connected to the remote server (that
1575 is: if it has a valid Paramiko/SSH transport object).
1576
1577 @return: X2Go session connected?
1578 @rtype: C{bool}
1579
1580 """
1581 return self.get_transport() is not None and self.get_transport().is_authenticated()
1582
1584 """\
1585 Returns C{True} if the given X2Go session is in running state,
1586 C{False} else.
1587
1588 @param session_name: X2Go name of the session to be queried
1589 @type session_name: C{str}
1590
1591 @return: X2Go session running? If C{<session_name>} is not listable by the L{list_sessions()} method then C{None} is returned
1592 @rtype: C{bool} or C{None}
1593
1594 """
1595 session_infos = self.list_sessions()
1596 if session_name in session_infos.keys():
1597 return session_infos[session_name].is_running()
1598 return None
1599
1601 """\
1602 Returns C{True} if the given X2Go session is in suspended state,
1603 C{False} else.
1604
1605 @return: X2Go session suspended? If C{<session_name>} is not listable by the L{list_sessions()} method then C{None} is returned
1606 @rtype: C{bool} or C{None}
1607
1608 """
1609 session_infos = self.list_sessions()
1610 if session_name in session_infos.keys():
1611 return session_infos[session_name].is_suspended()
1612 return None
1613
1615 """\
1616 Returns C{True} if the X2Go session with name C{<session_name>} has been seen
1617 by this control session and--in the meantime--has been terminated.
1618
1619 If C{<session_name>} has not been seen, yet, the method will return C{None}.
1620
1621 @return: X2Go session has terminated?
1622 @rtype: C{bool} or C{None}
1623
1624 """
1625 session_infos = self.list_sessions()
1626 if session_name in self.terminated_terminals:
1627 return True
1628 if session_name not in session_infos.keys() and session_name in self.associated_terminals.keys():
1629
1630 self.terminate(session_name)
1631 return True
1632 if self.is_suspended(session_name) or self.is_running(session_name):
1633 return False
1634
1635 return None
1636
1638 """\
1639 Suspend X2Go session with name C{<session_name>} on the connected
1640 server.
1641
1642 @param session_name: X2Go name of the session to be suspended
1643 @type session_name: C{str}
1644
1645 @return: C{True} if the session could be successfully suspended
1646 @rtype: C{bool}
1647
1648 """
1649 _ret = False
1650 _session_names = [ t.get_session_name() for t in self.associated_terminals.values() ]
1651 if session_name in _session_names:
1652
1653 self.logger('suspending associated terminal session: %s' % session_name, loglevel=log.loglevel_DEBUG)
1654 (stdin, stdout, stderr) = self._x2go_exec_command("x2gosuspend-session %s" % session_name, loglevel=log.loglevel_DEBUG)
1655 stdout.read()
1656 stderr.read()
1657 if self.associated_terminals.has_key(session_name):
1658 if self.associated_terminals[session_name] is not None:
1659 self.associated_terminals[session_name].__del__()
1660 try: del self.associated_terminals[session_name]
1661 except KeyError: pass
1662 _ret = True
1663
1664 else:
1665
1666 self.logger('suspending non-associated terminal session: %s' % session_name, loglevel=log.loglevel_DEBUG)
1667 (stdin, stdout, stderr) = self._x2go_exec_command("x2gosuspend-session %s" % session_name, loglevel=log.loglevel_DEBUG)
1668 stdout.read()
1669 stderr.read()
1670 _ret = True
1671
1672 return _ret
1673
1674 - def terminate(self, session_name, destroy_terminals=True):
1675 """\
1676 Terminate X2Go session with name C{<session_name>} on the connected
1677 server.
1678
1679 @param session_name: X2Go name of the session to be terminated
1680 @type session_name: C{str}
1681
1682 @return: C{True} if the session could be successfully terminated
1683 @rtype: C{bool}
1684
1685 """
1686
1687 _ret = False
1688 _session_names = [ t.get_session_name() for t in self.associated_terminals.values() ]
1689 if session_name in _session_names:
1690
1691 self.logger('terminating associated session: %s' % session_name, loglevel=log.loglevel_DEBUG)
1692 (stdin, stdout, stderr) = self._x2go_exec_command("x2goterminate-session %s" % session_name, loglevel=log.loglevel_DEBUG)
1693 stdout.read()
1694 stderr.read()
1695 if self.associated_terminals.has_key(session_name):
1696 if self.associated_terminals[session_name] is not None and destroy_terminals:
1697 self.associated_terminals[session_name].__del__()
1698 try: del self.associated_terminals[session_name]
1699 except KeyError: pass
1700 self.terminated_terminals.append(session_name)
1701 _ret = True
1702
1703 else:
1704
1705 self.logger('terminating non-associated session: %s' % session_name, loglevel=log.loglevel_DEBUG)
1706 (stdin, stdout, stderr) = self._x2go_exec_command("x2goterminate-session %s" % session_name, loglevel=log.loglevel_DEBUG)
1707 stdout.read()
1708 stderr.read()
1709 _ret = True
1710
1711 return _ret
1712