1
2
3
4
5
6
7
8
9
10
11
12
13
14 __doc__="""SshClient
15
16 SshClient runs commands on a remote box using ssh
17 and returns their results
18
19 $Id: SshClient.py,v 1.5 2004/04/05 02:05:30 edahl Exp $"""
20
21 __version__ = "$Revision: 1.5 $"[11:-2]
22
23 import os, getpass
24 import logging
25 log = logging.getLogger("zen.SshClient")
26
27 import Globals
28
29 from twisted.conch.ssh import transport, userauth, connection
30 from twisted.conch.ssh import common, keys, channel
31 from twisted.internet import defer, reactor
32
33 from Exceptions import *
34
35 import CollectorClient
36
52
53
55 lastPublicKey = False
56 - def __init__(self, user, instance, factory):
57 user = str(user)
58 if user == '':
59 user = os.getlogin()
60 log.debug('attempting to authenticate using username: %s' % user)
61 userauth.SSHUserAuthClient.__init__(self, user, instance)
62 self.user = user
63 self.factory = factory
64
72
85
94
96
101
102
105
107 """open a new command channel for each command in queue"""
108 ch = CommandChannel(cmd, conn=self)
109 self.openChannel(ch)
110
112
113
114 self.localToRemoteChannel[channel.id] = None
115 self.channelsToRemoteChannel[channel] = None
116 connection.SSHConnection.channelClosed(self, channel)
117
118
120 name = 'session'
121
126
128 log.warn('open of %s failed: %s' % (self.command, reason))
129
131 log.debug('opening command channel for %s' % self.command)
132 self.data = ''
133 log.debug('running command remotely: exec %s' % common.NS(self.command))
134 d = self.conn.sendRequest(self, 'exec', common.NS(self.command),
135 wantReply = 1)
136
138 import struct
139 self.exitCode = struct.unpack('>L', data)[0]
140
143
150
151
152 -class SshClient(CollectorClient.CollectorClient):
153
154 - def __init__(self, hostname, ip, port=22, commands=[], options=None,
155 device=None, datacollector=None):
161
162
164 """Start ssh collection.
165 """
166 reactor.connectTCP(self.ip, self.port, self, self.loginTimeout)
167
168
170 """run commands that are in the command queue"""
171 log.info("connected to device %s" % self.hostname)
172 self.connection = sshconn
173 for cmd in self.getCommands():
174 sshconn.addCommand(cmd)
175
176
184
187
188
189
191 import socket
192 parser = CollectorClient.buildOptions()
193 options = CollectorClient.parseOptions(parser,22)
194 client = SshClient(options.hostname,
195 socket.gethostbyname(options.hostname),
196 options.port,
197 commands=options.commands, options=options)
198 def stop():
199 if client.commandsFinished():
200 reactor.stop()
201 else:
202 reactor.callLater(1, stop)
203 stop()
204 client.run()
205 reactor.run()
206 import pprint
207 pprint.pprint(client.getResults())
208
209 if __name__ == '__main__':
210 main()
211