~bernd-sch/onehundredscopes/sshsearch

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
#! /usr/bin/python

#    Copyright (c) 2011 David Calle <davidc@framli.eu>
#    Copyright (c) 2011 Michael Hall <mhall119@gmail.com>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os.path
import paramiko
import sys

from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
# FIXME: Some weird bug in Dee or PyGI makes Dee fail unless we probe
#        it *before* we import the Unity module... ?!
_m = dir(Dee.SequenceModel)
from gi.repository import Unity

BUS_NAME = "net.launchpad.lens.sshsearch"

SSH_DEFAULT_PORT = '22'
SSHCONFIG = os.path.join('~', '.ssh', 'config')
SSHCONFIG_EXPAND = os.path.expanduser(SSHCONFIG)
KNOWN_HOSTS = os.path.join('~', '.ssh', 'known_hosts')
KNOWN_HOSTS_EXPAND = os.path.expanduser(KNOWN_HOSTS)

TERMINAL_APP = 'gnome-terminal'
TERMINAL_APP_MIMETYPE = 'application-x-desktop'

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ICON_FILE = os.path.join(SCRIPT_DIR, 'unity-lens-sshsearch.svg')


class Daemon:

    def __init__ (self):
        # The path for the Lens *must* also match the one in our .lens file
        self._lens = Unity.Lens.new ("/net/launchpad/lens/sshsearch", "sshsearch")
        self._scope = Unity.Scope.new ("/net/launchpad/lens/sshsearch/main")
        self._scope.connect ("notify::active-search", self.on_search_changed)
        self._scope.connect ("notify::active-global-search", self.on_global_search_changed)
        self._scope.connect ("filters-changed", self.on_search_changed);
        self._scope.connect ("notify::active", self.on_search_changed);
        self._scope.connect ("activate-uri", self.on_activate_uri);
        self._scope.export()

        self._lens.props.search_hint = "Search SSH connections"
        self._lens.props.visible = True;
        self._lens.props.search_in_global = True;
        
        # Populate categories
        cats = []
        cats.append(Unity.Category.new(SSHCONFIG,
                                       Gio.ThemedIcon.new(ICON_FILE),
                                       Unity.CategoryRenderer.VERTICAL_TILE))
        cats.append(Unity.Category.new(KNOWN_HOSTS,
                                       Gio.ThemedIcon.new(ICON_FILE),
                                       Unity.CategoryRenderer.VERTICAL_TILE))
        self._lens.props.categories = cats
        
        # Populate filters
        filters = []
        self._lens.props.filters = filters

        self._lens.add_local_scope (self._scope);
        self._lens.export ()

        # read/parse ssh-config file
        self._config_file = Gio.file_new_for_path(SSHCONFIG_EXPAND)
        self._config_monitor = self._config_file.monitor_file(flags=Gio.FileMonitorFlags.NONE, cancellable=None)
        self._config_monitor.connect('changed', self.__read_config)
        self._config_hosts = self.__read_config(None, self._config_file, None, Gio.FileMonitorEvent.CREATED)

        # read/parse ssh-known_hosts file
        self._knownhosts_file = Gio.file_new_for_path(KNOWN_HOSTS_EXPAND)
        self._knownhosts_monitor = self._knownhosts_file.monitor_file(flags=Gio.FileMonitorFlags.NONE, cancellable=None)
        self._known_hosts = self.__read_known_hosts(None, self._knownhosts_file, None, Gio.FileMonitorEvent.CREATED)
        
    def __read_config(self, filemonitor, file, other_file, event_type):
        config_hosts = []

        if not file.query_exists(None):
            return config_hosts

        if (event_type in (Gio.FileMonitorEvent.CREATED,
                           Gio.FileMonitorEvent.CHANGED,
                           Gio.FileMonitorEvent.CHANGES_DONE_HINT)): 
            c = paramiko.SSHConfig()
            c.parse(open(file.get_path()))
            config_hosts = [h['host'].lower() for h in c._config if h['host'] != '*']

        return config_hosts
        
    def __read_known_hosts(self, filemonitor, file, other_file, event_type):
        known_hosts = []
        if not file.query_exists(None):
            return known_hosts

        if (event_type in (Gio.FileMonitorEvent.CREATED,
                           Gio.FileMonitorEvent.CHANGED,
                           Gio.FileMonitorEvent.CHANGES_DONE_HINT)): 
            h = paramiko.HostKeys(KNOWN_HOSTS_EXPAND)
            known_hosts = [host for host in h.keys() if len(host) != 60]

        return known_hosts
        
    def on_search_changed (self, entry, *args):
        search = self._scope.props.active_search or None
        if search:
            search_string = search.props.search_string.lower() or None
        else:
            search_string = None
        results = self._scope.props.results_model
        self.update_results_model (search_string, results)

    def on_global_search_changed (self, entry, *args):
        search = self._scope.props.active_global_search or None
        if search:
            search_string = search.props.search_string.lower() or None
        else:
            search_string = None
        results = self._scope.props.global_results_model
        self.update_results_model(search_string, results)

    def __parse_hoststring(self, hoststring, user):
        # assign host and port
        host = hoststring
        port = SSH_DEFAULT_PORT
        if hoststring.startswith('['):
            host, port = hoststring[1:].split(']:')

        # assign target
        target = host
        if user:
            target = '%s@%s' % (user, host)

        # assign connection-description 
        conn_desc = target
        if port != SSH_DEFAULT_PORT:
            conn_desc = '%s:%s' % (target, port)

        return target, port, conn_desc

    def update_results_model(self, search, model):
        if search is None or search == '':
            return
         
        model.clear()
        searchparts = search.split('@')
        searchhost = searchparts[-1]
        searchuser = ''
        if len(searchparts) == 2:
            searchuser = searchparts[0]
            
        found = [host for host in self._config_hosts if host.find(searchhost) >= 0]
        for host in found:
            target, port, conn_desc = self.__parse_hoststring(host, searchuser)
            model.append('ssh://config/%s/%s' % (searchuser, host),
                         TERMINAL_APP,
                         0,
                         TERMINAL_APP_MIMETYPE,
                         conn_desc, conn_desc, '')
                         
        found = [host for host in self._known_hosts if host.find(searchhost) >= 0]
        for host in found:
            target, port, conn_desc = self.__parse_hoststring(host, searchuser)
            model.append('ssh://known_hosts/%s/%s' % (searchuser, host),
                         TERMINAL_APP,
                         1,
                         TERMINAL_APP_MIMETYPE,
                         conn_desc, conn_desc, '')

    def on_activate_uri (self, scope, uri):
        uri_splitted = uri.split('/')
        hoststring = uri_splitted[-1]
        user = uri_splitted[-2]
        target, port, conn_desc = self.__parse_hoststring(hoststring, user)

        if port == SSH_DEFAULT_PORT:
            # don't call with the port option, because the host definition
            # could be from the ~/.ssh/config file
            GLib.spawn_command_line_async('%s -e "ssh %s"' % (TERMINAL_APP, target))
        else:
            GLib.spawn_command_line_async('%s -e "ssh -p %s %s"' % (TERMINAL_APP, port, target))

        return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')


if __name__ == "__main__":
    session_bus_connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    session_bus = Gio.DBusProxy.new_sync(session_bus_connection, 0, None,
                                         'org.freedesktop.DBus',
                                         '/org/freedesktop/DBus',
                                         'org.freedesktop.DBus', None)
    result = session_bus.call_sync('RequestName',
                                   GLib.Variant("(su)", (BUS_NAME, 0x4)),
                                   0, -1, None)
                                   
    # Unpack variant response with signature "(u)". 1 means we got it.
    result = result.unpack()[0]
    
    if result != 1 :
        print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
        raise SystemExit (1)
    
    daemon = Daemon()
    GObject.MainLoop().run()