-
Notifications
You must be signed in to change notification settings - Fork 34
/
gnome_connection_manager.py
executable file
·3169 lines (2764 loc) · 133 KB
/
gnome_connection_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Python module gnome_connection_manager.py
# Autogenerated from gnome-connection-manager.glade
# Generated on Tue Jul 6 11:10:43 2010
# Warning: Do not modify any context comment such as #--
# They are required to keep user's code
# Gnome Connection Manager
# Renzo Bertuzzi ([email protected]) - CHILE
#
#TODO
# - ayuda
# - drag'n drop hosts entre grupos
# - sftp
# - master password (al iniciar la aplicacion)
# - guardar estado de consolas abiertas (y estado de split)
# - revisar buscador, a veces no encuentra las palabras
# - sortcut para moverse entre notebooks
# - quitar los "accelerator" del archivo .glade (o dejarlos opcionales)
# - soporte picocom (o minicom, o pyserial, ser2net) para comunicación serial
# - Permitir modificar combinacion para cerrar aplicacion CTRL+Q
# - Icono en system tray
# - Quitar shortcut ALT+F para archivo
# - Permitir deshabilitar shortcuts
# - soporte proxy socks/http para ssh
# - cluster mode: would be nice to have a drop-down list on the cluster button and once selected \"the text to send to hosts box\" should be activated on the right of the cluster button. The box should stay on the toolbar and not over the terminal window
# - hide chars** in cluster mode (un checkbox para mostrar/ocultar entrada)
# - seleccionar varios hosts y conectarse
# - seleccionar varios hosts y editarlos
# - permitir establecer colores a nivel de grupos
# - permitir cambiar nombre de grupo
# - overwrite colors (like putty)
# - Cambiar charset en consola o en propiedades del host
# - One "nice to have" would be the ability for GCM to use my existing PuTTY sessions instead of entering everything a second time. External script for that that parses ~/putty/session files
# - Enter passwords in commands and hide them, #P=password (Angelo Corsaro). TextView doesnt support masking text, it needs a different implementation. Pending.
# - Persist history of cluster commands. is it really necessary?
# - Option to disable shortcuts
#
#Changelog:
# v1.1.0 - Bugfix: public key field was not saved (thanks to Benoît Georgelin for reporting the bug)
# - Bugfix: bug in AES library resulted in blank passwords randomly being replaced by some characters (thanks to Boyan Peychev for reporting the bug)
# - Bugfix: drag and release tab on the same notebook caused tab to be closed
# - Bugfix: Estado de nodos expandidos/contraidos se revertia a un estado anterior al editar por segunda vez un host
# - Bugfix: Cluster window had to be resized to show the text area in some setups
# - Bugfix: Blank lines in commands were removed when restarting application (thanks to Nicholas O'Neill for reporting the bug)
# - Se agrega traducción a koreano (thanks to Jong Hoon Lee)
# - Better indentation in server panel
# - Disabled the horizontal scroll bar in the console
# - Added option to open local console on application startup (thanks to Boaman Surebun for the implementation)
# - Se agrega opción para copiar todo el buffer al porta-papeles
# - Se usa la consola por defecto del usuario en vez de bash
# - Se exponen algunos shortcuts
# - Added menu with servers list
#
# v1.0.0 - Bugfix: last group was collapsed when adding/editing a new host. All collapsed nodes are preserved now. (thanks to Kevin Brennan for reporting the bug)
# - Bugfix: importing servers in another computer cleared all the passwords. (thanks to Simon Pitt for reporting the bug)
# - Bugfix: buttons to choose colors did not reflect the selected color (thanks to Sverre Rakkenes for reporting the bug)
# - Se implementa AES-256 para encriptar claves
# - Se agrega opcion para pasar parametros adicionales a la linea de comando (ssh/telnet)
# - Se agrega opcion para auto cerrar tab (nunca, siempre, solo si no hay errores) cuando se finaliza la sesion
# - Se agrega menu con opcion para ocultar toolbar y panel de servidores
# - Se agrega soporte para compression ssh (gracias a Boaman Surebun por la implementacion)
# - Se agrega configuracion en host para sequencia de teclas Backspace y Delete
#
# v0.9.8 - Bugfix: find_back shortcut was not working
# - Bugfix: double click on tabs or arrows in the tab bar opened a new local window
# - Se quita F10 como atajo para el menu
# - Se agrega texto de licencia en acerca de
# - Historial de comandos en cluster
# - Se agrega descripcion y tooltips sobre hosts
# - delay entre los comandos que se envian al inicio (por cada linea, usar una linea tipo comentario con el delay??)
# - Se agrega redireccionamiento dynamico de puertos
#
# v0.9.7 - Bugfix: error message "Error connecting to server: global name 'bolor' is not defined" when opening a host with custom colors (thanks to talos)
#
# v0.9.6 - Bugfix: error al duplicar un host en un subgrupo
# - Se agrega opcion para generar log de las sesiones
# - Si no existe el idioma, ingles por defecto
# - Se agrega opcion para habilitar Agent-forwarding
# - Se agrega soporte para private key files
#
# v0.9.5 - Se elimina mensaje "The package is of bad quality" al instalar en ubuntu 11.04 (lintian check)
# - Bugfix: el modo cluster no muestra los titulos correctos de las consolas cuando han sido renombradas
# - Se agrega opción de clonar consola
# - Archivo de configuración ahora se guarda al realizar cambios (antes se guardaba al salir de la aplicacion)
# - Se agrega opción de tener subgrupos, al editar un host se debe usar el formato grupo/subgrupo/subgrupo para el nombre de grupo
#
# v0.9.4 - Bugfix: Dejar el foco siempre en la nueva consola
# - Bugfix: Shortcut para console_previous se revertia a ctrl+shift+left
# - Se agrega traducción a italiano (gracias a Vincenzo Reale)
# - Bugfix: Telnet no funcionaba al usarlo sin usuario
#
# v0.9.3 - Bugfix: No funcionaba el boton "Local" luego de cerrar todas las consolas
# - Bugfix: se quita atajo CTRL+QUIT para salir de la aplicacion.
# - Se agrega traducción a ruso (gracias a Denis Fokin)
# - Se agrega traducción a portugues (gracias a Ericson Alexandre S.)
# - Se agrega menu contextual "copiar y pegar"
# - Se agrega shortcut para reconectar
# - Revisar si expect esta instalado al iniciar
# - Permitir conexiones locales al guardar un host (ssh, telnet, local)
#
# v0.9.2 - Bugfix: En algunos casos no se guardaban los passwords
# - Bugfix: Al conectarse a traves de una sesion remota (nomachine, X11) y abrir gcm se limpiaban los passwords
# - Se agrega traducción a polaco (gracias a Pawel)
#
# v0.9.1 - Bugfix: Se corrigen algunos textos en frances
# - Bugfix: Se corrige bug al importar servidores
# - Bugfix: opcion de reconectar desaparece para las demás consolas luego de reconectar a una consola
# - Se agrega opcion de cerrar consola con boton central del mouse sin pedir confirmacion
#
# v0.9.0 - Se agrega opcion de copiar texto seleccionado automaticamente al porta papeles
# - Se agrega menu para duplicar host
# - Se agrega modo cluster (permite enviar mismo comando a varios hosts a la vez)
# - Se agrega menu para reabrir una sesion cerrada
# - menu contextual en consola para enviar los comandos predefinidos
#
# v0.8.0 - Bugfix: ancho/alto incorrecto al dividir consola horizontal/vertical
# - Se agrega opcion para conservar tamaño de ventana entre ejecuciones
# - Se agrega opcion para resetear y resetear-limpiar consola (menu contextual y shortcut)
# - Soporte para autenticacion sin password/public key(se debe dejar el password en blanco)
# - X11 forwading para ssh
# - cambiar font de consola
# - Permitir ocultar boton para donar
#
# v0.7.1 - Bugfix: al cerrar consola con shortcut se mantenia abierta la sesion ssh
# - Bugfix: importar servers arrojaba mensaje "Archivo invalido"
#
# v0.7.0 - Se agrega menu contextual "copiar direccion" del host
# - Se agrega opcion de keep-alive por host
# - Se agrega colores configurables por host
# - Se agrega opción de renombrar tabs de consola
# - Se agrega traducción a francés (gracias a William M.)
# - Se agrega shortcut para cerrar consola
#
# v0.6.1 - Se agrega shortcuts para cambiar entre consolas (izq, der, y 01 a 09)
# - Correción de bug: no se podia editar un shortcut predefinido
#
# v0.6.0 - Se agrega opción para guardar buffer en archivo
# - Se agrega buscador
# - Boton para abrir consola local
# - ejecutar comando luego del login
# - guardar estado (abiertos/cerrados) de folders y posicion del panel
# - importar/exportar lista de servidores
# - menu contextual en grupos y servidores (expandir/contraer todo, editar host, agregar host)
# - shortcuts para comandos predefinidos (copia, pegar, etc) y para ejecutar comandos
# - comprobar actualizaciones
# - Corrección de bug: autologin no funcionaba para algunos servidores telnet
#
# v0.5.0 - Corrección de bug que mostraba mal las consolas ssh en algunos casos (no se ocupaba todo el espacio de la consola)
# - Corrección de bug que cerraba dos consolas al tener la pantalla dividida y cerrar consola de la derecha
# - Se agrega opción de menu contextual con boton derecho
# - Se agrega opción de confirmar al cerrar una consola
# - Se muestra mensaje en pantalla cuando cambia la key de un host para ssh
# - Boton donar
from __future__ import with_statement
import os
import operator
import sys
import base64
import time
import tempfile
import shlex
try:
import gtk
import gobject
except:
print >> sys.stderr, "pygtk required"
sys.exit(1)
try:
import vte
except:
error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
'You must install libvte for python')
error.run()
sys.exit (1)
#Ver si expect esta instalado
try:
e = os.system("expect >/dev/null 2>&1 -v")
except:
e = -1
if e != 0:
error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
'You must install expect')
error.run()
sys.exit (1)
gtk.gdk.threads_init()
from SimpleGladeApp import SimpleGladeApp
from SimpleGladeApp import bindtextdomain
import ConfigParser
import pango
import pyAES
app_name = "Gnome Connection Manager"
app_version = "1.1.0"
app_web = "http://www.kuthulu.com/gcm"
app_fileversion = "1"
BASE_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
SSH_BIN = 'ssh'
TEL_BIN = 'telnet'
SHELL = os.environ["SHELL"]
SSH_COMMAND = BASE_PATH + "/ssh.expect"
CONFIG_FILE = os.getenv("HOME") + "/.gcm/gcm.conf"
KEY_FILE = os.getenv("HOME") + "/.gcm/.gcm.key"
if not os.path.exists(os.getenv("HOME") + "/.gcm"):
os.makedirs(os.getenv("HOME") + "/.gcm")
domain_name="gcm-lang"
HSPLIT = 0
VSPLIT = 1
_COPY = ["copy"]
_PASTE = ["paste"]
_COPY_ALL = ["copy_all"]
_SAVE = ["save"]
_FIND = ["find"]
_CLEAR = ["reset"]
_FIND_NEXT = ["find_next"]
_FIND_BACK = ["find_back"]
_CONSOLE_PREV = ["console_previous"]
_CONSOLE_NEXT = ["console_next"]
_CONSOLE_1 = ["console_1"]
_CONSOLE_2 = ["console_2"]
_CONSOLE_3 = ["console_3"]
_CONSOLE_4 = ["console_4"]
_CONSOLE_5 = ["console_5"]
_CONSOLE_6 = ["console_6"]
_CONSOLE_7 = ["console_7"]
_CONSOLE_8 = ["console_8"]
_CONSOLE_9 = ["console_9"]
_CONSOLE_CLOSE = ["console_close"]
_CONSOLE_RECONNECT = ["console_reconnect"]
_CONNECT = ["connect"]
ICON_PATH = BASE_PATH + "/icon.png"
glade_dir = ""
locale_dir = BASE_PATH + "/lang"
bindtextdomain(domain_name, locale_dir)
groups={}
shortcuts={}
enc_passwd=''
#Variables de configuracion
class conf():
WORD_SEPARATORS="-A-Za-z0-9,./?%&#:_=+@~"
BUFFER_LINES=2000
STARTUP_LOCAL=True
CONFIRM_ON_EXIT=True
FONT_COLOR = ""
BACK_COLOR = ""
TRANSPARENCY = 0
PASTE_ON_RIGHT_CLICK = 1
CONFIRM_ON_CLOSE_TAB = 0
AUTO_CLOSE_TAB = 0
COLLAPSED_FOLDERS = ""
LEFT_PANEL_WIDTH = 100
CHECK_UPDATES=True
WINDOW_WIDTH = -1
WINDOW_HEIGHT = -1
FONT = ""
HIDE_DONATE = False
AUTO_COPY_SELECTION = 0
LOG_PATH = os.path.expanduser("~")
SHOW_TOOLBAR = True
SHOW_PANEL = True
VERSION = 0
def msgbox(text, parent=None):
msgBox = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, text)
msgBox.set_icon_from_file(ICON_PATH)
msgBox.run()
msgBox.destroy()
def msgconfirm(text):
msgBox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, text)
msgBox.set_icon_from_file(ICON_PATH)
response = msgBox.run()
msgBox.destroy()
return response
def inputbox(title, text, default='', password=False):
msgBox = EntryDialog(title, text, default, mask=password)
msgBox.set_icon_from_file(ICON_PATH)
if msgBox.run() == gtk.RESPONSE_OK:
response = msgBox.value
else:
response = None
msgBox.destroy()
return response
def show_font_dialog(parent, title, button):
if not hasattr(parent, 'dlgFont'):
parent.dlgFont = None
if parent.dlgFont == None:
parent.dlgFont = gtk.FontSelectionDialog(title)
fontsel = parent.dlgFont.fontsel
fontsel.set_font_name(button.selected_font.to_string())
response = parent.dlgFont.run()
if response == gtk.RESPONSE_OK:
button.selected_font = pango.FontDescription(fontsel.get_font_name())
button.set_label(button.selected_font.to_string())
button.get_child().modify_font(button.selected_font)
parent.dlgFont.hide()
def show_open_dialog(parent, title, action):
dlg = gtk.FileChooserDialog(title=title, parent=parent, action=action)
dlg.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
dlg.add_button(gtk.STOCK_SAVE if action==gtk.FILE_CHOOSER_ACTION_SAVE else gtk.STOCK_OPEN, gtk.RESPONSE_OK)
dlg.set_do_overwrite_confirmation(True)
if not hasattr(parent,'lastPath'):
parent.lastPath = os.path.expanduser("~")
dlg.set_current_folder( parent.lastPath )
if dlg.run() == gtk.RESPONSE_OK:
filename = dlg.get_filename()
parent.lastPath = os.path.dirname(filename)
else:
filename = None
dlg.destroy()
return filename
def get_key_name(event):
name = ""
if event.state & 4:
name = name + "CTRL+"
if event.state & 1:
name = name + "SHIFT+"
if event.state & 8:
name = name + "ALT+"
if event.state & 67108864:
name = name + "SUPER+"
return name + gtk.gdk.keyval_name(event.keyval).upper()
def get_username():
return os.getenv('USER') or os.getenv('LOGNAME') or os.getenv('USERNAME')
def get_password():
return get_username() + enc_passwd
def load_encryption_key():
global enc_passwd
try:
if os.path.exists(KEY_FILE):
with open(KEY_FILE) as f:
enc_passwd = f.read()
else:
enc_passwd = ''
except:
msgbox("Error trying to open key_file")
enc_passwd = ''
def initialise_encyption_key():
global enc_passwd
import random
x = int(str(random.random())[2:])
y = int(str(random.random())[2:])
enc_passwd = "%x" % (x*y)
try:
with os.fdopen(os.open(KEY_FILE, os.O_WRONLY | os.O_CREAT, 0600), 'w') as f:
f.write(enc_passwd)
except:
msgbox("Error initialising key_file")
## funciones para encryptar passwords - no son muy seguras, pero impiden que los pass se guarden en texto plano
def xor(pw, str1):
c = 0
liste = []
for k in xrange(len(str1)):
if c > len(pw)-1:
c = 0
fi = ord(pw[c])
c += 1
se = ord(str1[k])
fin = operator.xor(fi, se)
liste += [chr(fin)]
return liste
def encrypt_old(passw, string):
try:
ret = xor(passw, string)
s = base64.b64encode("".join(ret))
except:
s = ""
return s
def decrypt_old(passw, string):
try:
ret = xor(passw, base64.b64decode(string))
s = "".join(ret)
except:
s = ""
return s
def encrypt(passw, string):
try:
s = pyAES.encrypt(string, passw)
except:
s = ""
return s
def decrypt(passw, string):
try:
s = decrypt_old(passw, string) if conf.VERSION == 0 else pyAES.decrypt(string, passw)
except:
s = ""
return s
class Wmain(SimpleGladeApp):
def __init__(self, path="gnome-connection-manager.glade",
root="wMain",
domain=domain_name, **kwargs):
path = os.path.join(glade_dir, path)
SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
global wMain
wMain = self
load_encryption_key()
self.initLeftPane()
self.createMenu()
if conf.VERSION == 0:
initialise_encyption_key()
settings = gtk.settings_get_default()
settings.props.gtk_menu_bar_accel = None
self.real_transparency = False
if conf.TRANSPARENCY>0:
#Revisar si hay soporte para transparencia
screen = self.get_widget("wMain").get_screen()
colormap = screen.get_rgba_colormap()
if colormap != None and screen.is_composited():
self.get_widget("wMain").set_colormap(colormap)
self.real_transparency = True
if conf.WINDOW_WIDTH != -1 and conf.WINDOW_HEIGHT != -1:
self.get_widget("wMain").resize(conf.WINDOW_WIDTH, conf.WINDOW_HEIGHT)
else:
self.get_widget("wMain").maximize()
self.get_widget("wMain").show()
#Just added children in glade to eliminate GTK warning, remove all children
for x in self.nbConsole.get_children():
self.nbConsole.remove(x)
self.nbConsole.set_scrollable(True)
self.nbConsole.set_group_id(11)
self.nbConsole.connect('page_removed', self.on_page_removed)
self.nbConsole.connect("page-added", self.on_page_added)
self.hpMain.previous_position = 150
if conf.LEFT_PANEL_WIDTH!=0:
self.set_panel_visible(conf.SHOW_PANEL)
self.set_toolbar_visible(conf.SHOW_TOOLBAR)
#a veces no se posiciona correctamente con 400 ms, asi que se repite el llamado
gobject.timeout_add(400, lambda : self.hpMain.set_position(conf.LEFT_PANEL_WIDTH))
gobject.timeout_add(900, lambda : self.hpMain.set_position(conf.LEFT_PANEL_WIDTH))
if conf.HIDE_DONATE:
self.get_widget("btnDonate").hide_all()
if conf.CHECK_UPDATES:
gobject.timeout_add(2000, lambda: self.check_updates())
#Por cada parametro de la linea de comandos buscar el host y agregar un tab
for arg in sys.argv[1:]:
i = arg.rfind("/")
if i!=-1:
group = arg[:i]
name = arg[i+1:]
if group!='' and name!='' and groups.has_key(group):
for h in groups[group]:
if h.name==name:
self.addTab(self.nbConsole, h)
break
self.get_widget('txtSearch').modify_text(gtk.STATE_NORMAL, gtk.gdk.Color('darkgray'))
if conf.STARTUP_LOCAL:
self.addTab(self.nbConsole,'local')
#-- Wmain.new {
def new(self):
self.hpMain = self.get_widget("hpMain")
self.nbConsole = self.get_widget("nbConsole")
self.treeServers = self.get_widget("treeServers")
self.menuServers = self.get_widget("menuServers")
self.menuCustomCommands = self.get_widget("menuCustomCommands")
self.current = None
self.count = 0
#-- Wmain.new }
#-- Wmain custom methods {
# Write your own methods here
def check_updates(self):
checker = CheckUpdates(self)
checker.start()
def on_terminal_click(self, widget, event, *args):
if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
if conf.PASTE_ON_RIGHT_CLICK:
widget.paste_clipboard()
else:
self.popupMenu.mnuCopy.set_sensitive(widget.get_has_selection())
self.popupMenu.mnuLog.set_active( hasattr(widget, "log_handler_id") and widget.log_handler_id != 0 )
self.popupMenu.terminal = widget
self.popupMenu.popup( None, None, None, event.button, event.time)
return True
def on_terminal_keypress(self, widget, event, *args):
if shortcuts.has_key(get_key_name(event)):
cmd = shortcuts[get_key_name(event)]
if type(cmd) == list:
#comandos predefinidos
if cmd == _COPY:
self.terminal_copy(widget)
elif cmd == _PASTE:
self.terminal_paste(widget)
elif cmd == _COPY_ALL:
self.terminal_copy_all(widget)
elif cmd == _SAVE:
self.show_save_buffer(widget)
elif cmd == _FIND:
self.get_widget('txtSearch').select_region(0, -1)
self.get_widget('txtSearch').grab_focus()
elif cmd == _FIND_NEXT:
if hasattr(self, 'search'):
self.find_word()
elif cmd == _CLEAR:
widget.reset(True, True)
elif cmd == _FIND_BACK:
if hasattr(self, 'search'):
self.find_word(backwards=True)
elif cmd == _CONSOLE_PREV:
widget.get_parent().get_parent().prev_page()
elif cmd == _CONSOLE_NEXT:
widget.get_parent().get_parent().next_page()
elif cmd == _CONSOLE_CLOSE:
wid = widget.get_parent()
page = widget.get_parent().get_parent().page_num(wid)
if page != -1:
widget.get_parent().get_parent().remove_page(page)
wid.destroy()
elif cmd == _CONSOLE_RECONNECT:
if not hasattr(widget, "command"):
widget.fork_command(SHELL)
else:
widget.fork_command(widget.command[0], widget.command[1])
while gtk.events_pending():
gtk.main_iteration(False)
#esperar 2 seg antes de enviar el pass para dar tiempo a que se levante expect y prevenir que se muestre el pass
if widget.command[2]!=None and widget.command[2]!='':
gobject.timeout_add(2000, self.send_data, widget, widget.command[2])
widget.get_parent().get_parent().get_tab_label(widget.get_parent()).mark_tab_as_active()
return True
elif cmd == _CONNECT:
self.on_btnConnect_clicked(None)
elif cmd[0][0:8] == "console_":
page = int(cmd[0][8:]) - 1
widget.get_parent().get_parent().set_current_page(page)
else:
#comandos del usuario
widget.feed_child(cmd)
return True
return False
def on_terminal_selection(self, widget, *args):
if conf.AUTO_COPY_SELECTION:
self.terminal_copy(widget)
return True
def find_word(self, backwards=False):
pos=-1
if backwards:
lst = range(0, self.search['index'])
lst.reverse()
lst.extend(reversed(range(self.search['index'], len(self.search['lines']))))
else:
lst = range(self.search['index'], len(self.search['lines']))
lst.extend(range(0, self.search['index']))
for i in lst:
pos = self.search['lines'][i].find(self.search['word'])
if pos != -1:
self.search['index'] = i if backwards else i + 1
#print 'found at line %d column %d, index=%d' % (i, pos, self.search['index'])
gobject.timeout_add(0, lambda: self.search['terminal'].get_adjustment().set_value(i))
self.search['terminal'].queue_draw()
break
if pos==-1:
self.search['index'] = len(self.search['lines']) if backwards else 0
def init_search(self):
if hasattr(self, 'search') and self.get_widget('txtSearch').get_text() == self.search['word'] and self.current == self.search['terminal']:
return True
terminal = self.find_active_terminal(self.hpMain)
if terminal == None:
terminal = self.current
else:
self.current = terminal
if terminal==None:
return False
self.search = {}
self.search['lines'] = terminal.get_text_range(0, 0, terminal.get_property('scrollback-lines'), terminal.get_column_count(), lambda *args: True, None, None ).rstrip().splitlines()
self.search['index'] = len(self.search['lines'])
self.search['terminal'] = terminal
self.search['word'] = self.get_widget('txtSearch').get_text()
return True
def on_popupmenu(self, widget, item, *args):
if item == 'V': #PASTE
self.terminal_paste(self.popupMenu.terminal)
return True
elif item == 'C': #COPY
self.terminal_copy(self.popupMenu.terminal)
return True
elif item == 'CV': #COPY and PASTE
self.terminal_copy_paste(self.popupMenu.terminal)
return True
elif item == 'A': #SELECT ALL
self.terminal_select_all(self.popupMenu.terminal)
return True
elif item == 'CA': #COPY ALL
self.terminal_copy_all(self.popupMenu.terminal)
return True
elif item == 'X': #CLOSE CONSOLE
widget = self.popupMenu.terminal.get_parent()
notebook = widget.get_parent()
page=notebook.page_num(widget)
notebook.remove_page(page)
return True
elif item == 'CP': #CUSTOM COMMANDS
self.popupMenu.terminal.feed_child(args[0])
elif item == 'S': #SAVE BUFFER
self.show_save_buffer(self.popupMenu.terminal)
return True
elif item == 'H': #COPY HOST ADDRESS TO CLIPBOARD
if self.treeServers.get_selection().get_selected()[1]!=None and not self.treeModel.iter_has_child(self.treeServers.get_selection().get_selected()[1]):
host = self.treeModel.get_value(self.treeServers.get_selection().get_selected()[1],1)
cb = gtk.Clipboard()
cb.set_text(host.host)
cb.store()
return True
elif item == 'D': #DUPLICATE HOST
if self.treeServers.get_selection().get_selected()[1]!=None and not self.treeModel.iter_has_child(self.treeServers.get_selection().get_selected()[1]):
selected = self.treeServers.get_selection().get_selected()[1]
group = self.get_group(selected)
host = self.treeModel.get_value(selected, 1)
newname = '%s (copy)' % (host.name)
newhost = host.clone()
for h in groups[group]:
if h.name == newname:
newname = '%s (copy)' % (newname)
newhost.name = newname
groups[group].append( newhost )
self.updateTree()
self.writeConfig()
return True
elif item == 'R': #RENAME TAB
text = inputbox(_('Renombrar consola'), _('Ingrese nuevo nombre'), self.popupMenuTab.label.get_text().strip())
if text != None and text != '':
self.popupMenuTab.label.set_text(" %s " % (text))
return True
elif item == 'RS' or item == 'RS2': #RESET CONSOLE
if (item == 'RS'):
tab = self.popupMenuTab.label.get_parent().get_parent()
term = tab.widget.get_child()
else:
term = self.popupMenu.terminal
term.reset(True, False)
return True
elif item == 'RC' or item == 'RC2': #RESET AND CLEAR CONSOLE
if (item == 'RC'):
tab = self.popupMenuTab.label.get_parent().get_parent()
term = tab.widget.get_child()
else:
term = self.popupMenu.terminal
term.reset(True, True)
return True
elif item == 'RO': #REOPEN SESION
tab = self.popupMenuTab.label.get_parent().get_parent()
term = tab.widget.get_child()
if not hasattr(term, "command"):
term.fork_command(SHELL)
else:
term.fork_command(term.command[0], term.command[1])
while gtk.events_pending():
gtk.main_iteration(False)
#esperar 2 seg antes de enviar el pass para dar tiempo a que se levante expect y prevenir que se muestre el pass
if term.command[2]!=None and term.command[2]!='':
gobject.timeout_add(2000, self.send_data, term, term.command[2])
tab.mark_tab_as_active()
return True
elif item == 'CC' or item == 'CC2': #CLONE CONSOLE
if item == 'CC':
tab = self.popupMenuTab.label.get_parent().get_parent()
term = tab.widget.get_child()
ntbk = tab.get_parent()
else:
term = self.popupMenu.terminal
ntbk = term.get_parent().get_parent()
tab = ntbk.get_tab_label(term.get_parent())
if not hasattr(term, "host"):
self.addTab(ntbk, tab.get_text())
else:
host = term.host.clone()
host.name = tab.get_text()
host.log = hasattr(term, "log_handler_id") and term.log_handler_id != 0
self.addTab(ntbk, host)
return True
elif item == 'L' or item == 'L2': #ENABLE/DISABLE LOG
if item == 'L':
tab = self.popupMenuTab.label.get_parent().get_parent()
term = tab.widget.get_child()
else:
term = self.popupMenu.terminal
if not self.set_terminal_logger(term, widget.get_active()):
widget.set_active(False)
return True
def createMenu(self):
self.popupMenu = gtk.Menu()
self.popupMenu.mnuCopy = menuItem = gtk.ImageMenuItem(_("Copiar"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_COPY, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'C')
menuItem.show()
self.popupMenu.mnuPaste = menuItem = gtk.ImageMenuItem(_("Pegar"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_PASTE, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'V')
menuItem.show()
self.popupMenu.mnuCopyPaste = menuItem = gtk.ImageMenuItem(_("Copiar y Pegar"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_INDEX, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'CV')
menuItem.show()
self.popupMenu.mnuSelect = menuItem = gtk.ImageMenuItem(_("Seleccionar todo"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_SELECT_ALL, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'A')
menuItem.show()
self.popupMenu.mnuCopyAll = menuItem = gtk.ImageMenuItem(_("Copiar todo"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_SELECT_ALL, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'CA')
menuItem.show()
self.popupMenu.mnuSelect = menuItem = gtk.ImageMenuItem(_("Guardar buffer en archivo"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'S')
menuItem.show()
menuItem = gtk.MenuItem()
self.popupMenu.append(menuItem)
menuItem.show()
self.popupMenu.mnuReset = menuItem = gtk.ImageMenuItem(_("Reiniciar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_NEW, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'RS2')
menuItem.show()
self.popupMenu.mnuClear = menuItem = gtk.ImageMenuItem(_("Reiniciar y Limpiar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'RC2')
menuItem.show()
self.popupMenu.mnuClone = menuItem = gtk.ImageMenuItem(_("Clonar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_COPY, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'CC2')
menuItem.show()
self.popupMenu.mnuLog = menuItem = gtk.CheckMenuItem(_("Habilitar log"))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'L2')
menuItem.show()
self.popupMenu.mnuClose = menuItem = gtk.ImageMenuItem(_("Cerrar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU))
self.popupMenu.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'X')
menuItem.show()
menuItem = gtk.MenuItem()
self.popupMenu.append(menuItem)
menuItem.show()
#Menu de comandos personalizados
self.popupMenu.mnuCommands = gtk.Menu()
self.popupMenu.mnuCmds = menuItem = gtk.ImageMenuItem(_("Comandos personalizados"))
menuItem.set_submenu(self.popupMenu.mnuCommands)
self.popupMenu.append(menuItem)
menuItem.show()
self.populateCommandsMenu()
#Menu contextual para panel de servidores
self.popupMenuFolder = gtk.Menu()
self.popupMenuFolder.mnuConnect = menuItem = gtk.ImageMenuItem(_("Conectar"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", self.on_btnConnect_clicked)
menuItem.show()
self.popupMenuFolder.mnuCopyAddress = menuItem = gtk.ImageMenuItem(_("Copiar Direccion"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_COPY, gtk.ICON_SIZE_MENU))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'H')
menuItem.show()
self.popupMenuFolder.mnuAdd = menuItem = gtk.ImageMenuItem(_("Agregar Host"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_MENU))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", self.on_btnAdd_clicked)
menuItem.show()
self.popupMenuFolder.mnuEdit = menuItem = gtk.ImageMenuItem(_("Editar"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_EDIT, gtk.ICON_SIZE_MENU))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", self.on_bntEdit_clicked)
menuItem.show()
self.popupMenuFolder.mnuDel = menuItem = gtk.ImageMenuItem(_("Eliminar"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_MENU))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", self.on_btnDel_clicked)
menuItem.show()
self.popupMenuFolder.mnuDup = menuItem = gtk.ImageMenuItem(_("Duplicar Host"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_DND_MULTIPLE, gtk.ICON_SIZE_MENU))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'D')
menuItem.show()
menuItem = gtk.MenuItem()
self.popupMenuFolder.append(menuItem)
menuItem.show()
self.popupMenuFolder.mnuExpand = menuItem = gtk.ImageMenuItem(_("Expandir todo"))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", lambda *args: self.treeServers.expand_all())
menuItem.show()
self.popupMenuFolder.mnuCollapse = menuItem = gtk.ImageMenuItem(_("Contraer todo"))
self.popupMenuFolder.append(menuItem)
menuItem.connect("activate", lambda *args: self.treeServers.collapse_all())
menuItem.show()
#Menu contextual para tabs
self.popupMenuTab = gtk.Menu()
self.popupMenuTab.mnuRename = menuItem = gtk.ImageMenuItem(_("Renombrar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_EDIT, gtk.ICON_SIZE_MENU))
self.popupMenuTab.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'R')
menuItem.show()
self.popupMenuTab.mnuReset = menuItem = gtk.ImageMenuItem(_("Reiniciar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_NEW, gtk.ICON_SIZE_MENU))
self.popupMenuTab.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'RS')
menuItem.show()
self.popupMenuTab.mnuClear = menuItem = gtk.ImageMenuItem(_("Reiniciar y Limpiar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_MENU))
self.popupMenuTab.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'RC')
menuItem.show()
self.popupMenuTab.mnuReopen = menuItem = gtk.ImageMenuItem(_("Reconectar al host"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_MENU))
self.popupMenuTab.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'RO')
#menuItem.show()
self.popupMenuTab.mnuClone = menuItem = gtk.ImageMenuItem(_("Clonar consola"))
menuItem.set_image(gtk.image_new_from_stock(gtk.STOCK_COPY, gtk.ICON_SIZE_MENU))
self.popupMenuTab.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'CC')
menuItem.show()
self.popupMenuTab.mnuLog = menuItem = gtk.CheckMenuItem(_("Habilitar log"))
self.popupMenuTab.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'L')
menuItem.show()
def createMenuItem(self, shortcut, label):
menuItem = gtk.MenuItem('')
menuItem.get_child().set_markup("<span color='blue' size='x-small'>[%s]</span> %s" % (shortcut, label))
menuItem.show()
return menuItem
def populateCommandsMenu(self):
self.popupMenu.mnuCommands.foreach(lambda x: self.popupMenu.mnuCommands.remove(x))
self.menuCustomCommands.foreach(lambda x: self.menuCustomCommands.remove(x))
for x in shortcuts:
if type(shortcuts[x]) != list:
menuItem = self.createMenuItem(x, shortcuts[x][0:30])
self.popupMenu.mnuCommands.append(menuItem)
menuItem.connect("activate", self.on_popupmenu, 'CP', shortcuts[x])
menuItem = self.createMenuItem(x, shortcuts[x][0:30])
self.menuCustomCommands.append(menuItem)
menuItem.connect("activate", self.on_menuCustomCommands_activate, shortcuts[x])
def on_menuCustomCommands_activate(self, widget, command):
terminal = self.find_active_terminal(self.hpMain)
if terminal:
terminal.feed_child(command)
def terminal_copy(self, terminal):
terminal.copy_clipboard()
def terminal_paste(self, terminal):
terminal.paste_clipboard()
def terminal_copy_paste(self, terminal):
terminal.copy_clipboard()
terminal.paste_clipboard()
def terminal_select_all(self, terminal):
terminal.select_all()
def terminal_copy_all(self, terminal):
terminal.select_all()
terminal.copy_clipboard()
terminal.select_none()
def on_menuCopy_activate(self, widget):
terminal = self.find_active_terminal(self.hpMain)
if terminal:
self.terminal_copy(terminal)
def on_menuPaste_activate(self, widget):
terminal = self.find_active_terminal(self.hpMain)
if terminal:
self.terminal_paste(terminal)
def on_menuCopyPaste_activate(self, widget):
terminal = self.find_active_terminal(self.hpMain)
if terminal:
self.terminal_copy_paste(terminal)
def on_menuSelectAll_activate(self, widget):
terminal = self.find_active_terminal(self.hpMain)
if terminal:
self.terminal_select_all(terminal)
def on_menuCopyAll_activate(self, widget):
terminal = self.find_active_terminal(self.hpMain)
if terminal:
self.terminal_copy_all(terminal)
def on_contents_changed(self, terminal):
col,row = terminal.get_cursor_position()
if terminal.last_logged_row != row: