forked from mjun/gnome-connection-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgnome_connection_manager.py
executable file
·3238 lines (2781 loc) · 134 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 python3
# -*- coding: UTF-8 -*-
# Python module simple_connection_manager.py
#
# Simple Connection Manager by Luis Armando Medina Avitia (lamedina@gmail.com)
#
# based on Gnome Connection Manager (2012) by Renzo Bertuzzi (kuthulu@gmail.com) - CHILE
# Last change: 20191219
#
#
#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
#
from __future__ import with_statement
import os
import operator
import sys
import base64
import time
import shlex
import traceback
import webbrowser
import codecs
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Vte', '2.91')
from gi.repository import Gtk
from gi.repository import Vte, GLib, Gio, Gdk, GdkPixbuf
from gi.repository import GObject
#Ver si expect esta instalado
try:
e = os.system("expect >/dev/null 2>&1 -v")
except:
e = -1
if e != 0:
error = Gtk.MessageDialog (parent=None, flags=0, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text='You must install expect')
error.run()
sys.exit (1)
Gdk.threads_init()
from SimpleGladeApp import SimpleGladeApp
from SimpleGladeApp import bindtextdomain
import configparser
from gi.repository import Pango as pango
import hashlib
try:
from Crypto.Cipher import AES
except:
print >> sys.stderr, "pycrypto >= 2.6.1 required"
print("pycrypto >= 2.6.1 required", file=sys.stderr)
sys.exit(1)
app_name = "Gnome Connection Manager"
app_version = "1.3.1"
app_web = "https://www.comoinstalarlinux.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"]
DESKTOP_SESSION = os.environ["DESKTOP_SESSION"]
CURRENT_DESKTOP = os.environ["XDG_CURRENT_DESKTOP"]
TERMINAL = ""
if os.path.exists("/usr/bin/x-terminal-emulator"):
TERMINAL = os.popen("grep exec /usr/bin/x-terminal-emulator | awk -F \"'\" '{ print $2 }' ").read()
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
_QUIT = ["quit"]
_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=parent,
modal=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text=text)
msgBox.set_icon_from_file(ICON_PATH)
msgBox.run()
msgBox.destroy()
def msgconfirm(text):
msgBox = Gtk.MessageDialog(parent=None,
modal=True,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.OK_CANCEL,
text=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.ResponseType.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.ResponseType.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.ResponseType.CANCEL)
dlg.add_button(Gtk.STOCK_SAVE if action==Gtk.FileChooserAction.SAVE else Gtk.STOCK_OPEN, Gtk.ResponseType.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.ResponseType.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+"
print(name + Gdk.keyval_name(event.keyval).upper())
return name + Gdk.keyval_name(event.keyval).upper()
def get_username():
return os.getenv('USER') or os.getenv('LOGNAME') or os.getenv('USERNAME')
def get_password():
global enc_passwd
#return get_username() + enc_passwd
return 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
x0 = int(str(random.random())[2:])
y0 = int(str(random.random())[2:])
x1 = int(str(random.random())[2:])
y1 = int(str(random.random())[2:])
p1 = "%x" % (x0*y0)
p2 = "%x" % (x1*y1)
enc_passwd = (p1+p2)[0:32]
try:
with os.fdopen(os.open(KEY_FILE, os.O_WRONLY | os.O_CREAT, 0o600), 'w') as f:
f.write(enc_passwd)
except:
msgbox("Error initialising key_file")
def encrypt(passw, string):
sha256 = hashlib.sha256()
sha256.update(passw.encode('utf-8'))
iv = str(sha256.hexdigest()[0:16])
pwd_bkey32 = "{: <32}".format(passw).encode('utf-8')
lenstr =len(string)
strfill = ""
if lenstr % 16 != 0 :
strfill = " " * (16 - lenstr % 16)
obj = AES.new(pwd_bkey32, AES.MODE_CBC, iv )
ciphertext = obj.encrypt(string + strfill)
print(passw, string, ciphertext.hex())
return ciphertext.hex()
def decrypt(passw, string):
sha256 = hashlib.sha256()
sha256.update(passw.encode('utf-8'))
iv = str(sha256.hexdigest()[0:16])
pwd_bkey32 = "{: <32}".format(passw).encode('utf-8')
byte_ciphertext = bytes.fromhex(string)
obj2 = AES.new(pwd_bkey32, AES.MODE_CBC, iv )
deciphertext = obj2.decrypt(byte_ciphertext)
print(passw, string, deciphertext, deciphertext.decode('utf-8'))
return deciphertext.decode('utf-8').strip()
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_name('default')
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.StateType.NORMAL, Gdk.Color(0.66, 0.66, 0.66)) # 'darkgray
if conf.STARTUP_LOCAL:
self.addTab(self.nbConsole,'local')
# Code for other initialization actions should be added here.
self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
#-- 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 }glade
#-- 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 == Gdk.EventType.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 get_key_name(event) in shortcuts :
cmd = shortcuts[get_key_name(event)]
if type(cmd) == list:
#comandos predefinidos
if cmd == _QUIT:
self.terminal_copy(widget)
elif 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()
#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
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)
text = str(host.host)
self.clipboard.set_text( text , -1)
self.clipboard.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()
#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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_COPY, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_PASTE, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_INDEX, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_SELECT_ALL, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_SELECT_ALL, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_SAVE, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_NEW, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_CLEAR, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_COPY, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_CLOSE, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_EXECUTE, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_COPY, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_EDIT, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_DND_MULTIPLE, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_EDIT, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_NEW, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_CLEAR, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_CONNECT, Gtk.IconSize.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))
menuItem.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_COPY, Gtk.IconSize.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.remove_all()
#for custom in self.menuCustomCommands:
# custom.remove()
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()
terminal.copy_clipboard_format(Vte.Format.TEXT)
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:
text = terminal.get_text_range(terminal.last_logged_row, terminal.last_logged_col, row, col, lambda *args: True, None, None)
terminal.last_logged_row = row
terminal.last_logged_col = col
terminal.log.write(text[:-1])
def set_terminal_logger(self, terminal, enable_logging=True):
if enable_logging:
terminal.last_logged_col, terminal.last_logged_row = terminal.get_cursor_position()
if hasattr(terminal, "log_handler_id"):
if terminal.log_handler_id == 0:
terminal.log_handler_id = terminal.connect('contents-changed', self.on_contents_changed)
return True
terminal.log_handler_id = terminal.connect('contents-changed', self.on_contents_changed)
p = terminal.get_parent()
title = p.get_parent().get_tab_label(p).get_text().strip()
prefix = "%s/%s-%s" % (os.path.expanduser(conf.LOG_PATH), title, time.strftime("%Y%m%d"))
filename = ''
for i in range(1,1000):
if not os.path.exists("%s-%03i.log" % (prefix,i)):
filename = "%s-%03i.log" % (prefix,i)
break
filename == "%s-%03i.log" % (prefix,1)
try:
terminal.log = open(filename, 'w', 0)
terminal.log.write("Session '%s' opened at %s\n%s\n" % (title, time.strftime("%Y-%m-%d %H:%M:%S"), "-"*80))
except:
msgbox("%s\n%s" % (_("No se puede abrir el archivo de log para escritura"), filename))
terminal.disconnect(terminal.log_handler_id)
del terminal.log_handler_id
return False
else:
if hasattr(terminal, "log_handler_id") and terminal.log_handler_id != 0:
terminal.disconnect(terminal.log_handler_id)
terminal.log_handler_id = 0
return True
def addTab(self, notebook, host):
try:
v = Vte.Terminal()
#v.set_word_chars(conf.WORD_SEPARATORS)
v.set_scrollback_lines(conf.BUFFER_LINES)
#if v.get_emulation() != os.getenv("TERM"):
# os.environ['TERM'] = v.get_emulation()
if isinstance(host, str):
host = Host('', host)
fcolor = Gdk.RGBA()
bcolor = Gdk.RGBA()
if host.font_color == '' or host.font_color == None or host.back_color == '' or host.back_color == None:
fcolor.parse(conf.FONT_COLOR)
bcolor.parse(conf.BACK_COLOR)
else:
fcolor.parse(host.font_color)
bcolor.parse(host.back_color)
#if len(fcolor)>0 and len(bcolor)>0:
v.set_colors(fcolor, bcolor, [])
if len(conf.FONT)==0:
conf.FONT = 'monospace'
else:
v.set_font(pango.FontDescription(conf.FONT))
scrollPane = Gtk.ScrolledWindow()
scrollPane.connect('button_press_event', lambda *args: True)
scrollPane.set_property('hscrollbar-policy', Gtk.PolicyType.NEVER)
if host.name == 'local':
tab = NotebookTabLabel(" %s " % (host.name), self.nbConsole, scrollPane, self.popupMenuTab )
else:
txtHint = ''