ssh2shell 1.9.9 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +568 -749
- package/lib/ssh2shell.js +113 -88
- package/package.json +57 -57
- package/src/ssh2shell.coffee +112 -95
- package/test/Multiple primary hosts.js +4 -10
- package/test/devtest.js +5 -3
- package/test/issue69.js +24 -24
- package/test/keyboard-interactivetest.js +3 -20
- package/test/lots of commands.js +87 -0
- package/test/notificationstest.js +13 -10
- package/test/sshUserCommandsPosition.js +26 -0
- package/test/sudo no pass test.js +4 -4
- package/test/timeouttest.js +19 -63
- package/test/tunneltest.js +2 -2
- package/test/tunneltestSshUserCommands.js +71 -0
package/README.md
CHANGED
|
@@ -2,44 +2,8 @@ ssh2shell
|
|
|
2
2
|
=========
|
|
3
3
|
[](https://nodei.co/npm/ssh2shell/)
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*ssh2shell supports the following functionality:*
|
|
8
|
-
* SSH shell connection to one or more hosts.
|
|
9
|
-
* Run multiple commands sequentially within the context of the previous commands result.
|
|
10
|
-
* SSH tunnelling to multiple hosts using nested host objects.
|
|
11
|
-
* When tunnelling each host has its own connection parameters, commands, command handlers,
|
|
12
|
-
event handlers and debug or verbose settings.
|
|
13
|
-
* Supports `sudo`, `sudo su` and `su user` commands.
|
|
14
|
-
* Supports changing default prompt matching regular expressions for different prompt requirements
|
|
15
|
-
* Ability to respond to prompts resulting from a command as it is being run.
|
|
16
|
-
* Ability to check the last command and conditions within the response text before the
|
|
17
|
-
next command is run.
|
|
18
|
-
* Performing actions based on a command run and the response received.
|
|
19
|
-
Things like adding or removing commands, responding using stream.write() or processing the command response text.
|
|
20
|
-
* See progress messages, messages you define, error messages and debug messages of script process
|
|
21
|
-
or verbose output of responses from the host.
|
|
22
|
-
* Access to full session response text in the end event triggered when each host connection is closed.
|
|
23
|
-
* Run notification commands that are processed either as messages to the full session text only or
|
|
24
|
-
messages outputted to your console only.
|
|
25
|
-
* Add event handlers either to the class instance or define them within host object.
|
|
26
|
-
* Create bash scripts on the fly, run them and remove them.
|
|
27
|
-
* Server SSH fingerprint validation.
|
|
28
|
-
* Access to [SSH2.connect parameters](https://github.com/mscdex/ssh2#client-methods) for first host connection.
|
|
29
|
-
* Keyboard-interactive authentication.
|
|
30
|
-
* Pipe stream.data into another writeable stream using SSH2shell.pipe(writableStream). Pipe commands can be chained.
|
|
31
|
-
* Also process raw stream.data through SSH2shell.on('data') or host.onData event handlers as the stream receives each
|
|
32
|
-
character.
|
|
33
|
-
* Use a callback function to handle final session text. The callback function can be defined in the host object or
|
|
34
|
-
passed to SSH2shell.connect(callback). The callback function has access to the `this` keyword.
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
Code:
|
|
38
|
-
-----
|
|
39
|
-
The Class is written in coffee script which can be found here: `./src/ssh2shell.coffee`.
|
|
40
|
-
It has comments not found in the build output JavaScript file `./lib/ssh2shell.js`.
|
|
41
|
-
|
|
42
|
-
|
|
5
|
+
Ssh2shell uses [ssh2](https://www.npmjs.org/package/ssh2) to open a ssh shell session to a host/s to run multiple commands and process the responses.
|
|
6
|
+
|
|
43
7
|
Installation:
|
|
44
8
|
------------
|
|
45
9
|
```
|
|
@@ -52,18 +16,16 @@ Minimal Example:
|
|
|
52
16
|
```javascript
|
|
53
17
|
//host configuration with connection settings and commands
|
|
54
18
|
var host = {
|
|
55
|
-
server: {
|
|
19
|
+
server: {
|
|
56
20
|
host: "127.0.0.1",
|
|
57
21
|
userName: "test",
|
|
58
|
-
password: "
|
|
22
|
+
password: "password",
|
|
59
23
|
},
|
|
60
24
|
commands: [ "echo $(pwd)", "ls -l" ]
|
|
61
25
|
};
|
|
62
26
|
|
|
63
27
|
var SSH2Shell = require ('ssh2shell'),
|
|
64
|
-
|
|
65
|
-
SSH = new SSH2Shell(host),
|
|
66
|
-
//Use a callback function to process the full session text
|
|
28
|
+
SSH = new SSH2Shell(host),
|
|
67
29
|
callback = function(sessionText){
|
|
68
30
|
console.log(sessionText)
|
|
69
31
|
}
|
|
@@ -72,75 +34,61 @@ var SSH2Shell = require ('ssh2shell'),
|
|
|
72
34
|
SSH.connect(callback);
|
|
73
35
|
```
|
|
74
36
|
|
|
37
|
+
|
|
75
38
|
Host Configuration:
|
|
76
39
|
------------
|
|
77
|
-
SSH2Shell
|
|
40
|
+
SSH2Shell requires an object with the following structure:
|
|
78
41
|
```javascript
|
|
79
|
-
//Host
|
|
42
|
+
//Host cobfiguration
|
|
80
43
|
host = {
|
|
81
44
|
server: {
|
|
82
|
-
//
|
|
83
|
-
host: "
|
|
84
|
-
port: "
|
|
85
|
-
userName: "
|
|
86
|
-
//optional or required settings subject to authentication method
|
|
87
|
-
password: "
|
|
45
|
+
//host connection settings
|
|
46
|
+
host: "192.168.0.2",
|
|
47
|
+
port: "22", //optional
|
|
48
|
+
userName: "username",
|
|
49
|
+
//optional or required settings subject to authentication method
|
|
50
|
+
password: "password",
|
|
88
51
|
passPhrase: "privateKeyPassphrase",
|
|
89
52
|
privateKey: require('fs').readFileSync('/path/to/private/key/id_rsa'),
|
|
90
|
-
//Optional: ssh2.connect
|
|
53
|
+
//Optional: ssh2.connect options
|
|
91
54
|
//See https://github.com/mscdex/ssh2#client-methods
|
|
92
|
-
//ssh2.connect parameters are only valid for the first host connection.
|
|
93
|
-
//Other host connections use the ssh command/s to connect not ssh2.
|
|
94
55
|
|
|
95
|
-
//Optional: ssh options only for making secondary host ssh connections
|
|
96
|
-
//see http://man.openbsd.org/ssh for definitions of options
|
|
97
|
-
ssh: {
|
|
98
|
-
//Optional
|
|
99
|
-
forceProtocolVersion: true/false,
|
|
100
|
-
forceAddressType: true/false,
|
|
101
|
-
disablePseudoTTY: true/false,
|
|
102
|
-
forcePseudoTTY: true/false,
|
|
103
|
-
verbose: true/false,
|
|
104
|
-
cipherSpec: "",
|
|
105
|
-
escape: "",
|
|
106
|
-
logFile: "",
|
|
107
|
-
configFile: "",
|
|
108
|
-
identityFile: "",
|
|
109
|
-
loginName: "",
|
|
110
|
-
macSpec: "",
|
|
111
|
-
Options: {}
|
|
112
|
-
}
|
|
56
|
+
//Optional: ssh options only for making secondary host ssh connections.
|
|
57
|
+
//see http://man.openbsd.org/ssh for definitions of options.
|
|
58
|
+
ssh: { //Options }
|
|
113
59
|
},
|
|
114
60
|
//Optional: Array of host objects for multiple host connections
|
|
115
|
-
hosts: [
|
|
61
|
+
hosts: [],
|
|
116
62
|
|
|
117
63
|
//Optional: Characters used in prompt detection
|
|
64
|
+
//defaults
|
|
118
65
|
standardPrompt: ">$%#",
|
|
119
66
|
passwordPrompt: ":",
|
|
120
67
|
passphrasePrompt: ":",
|
|
121
68
|
passPromptText: "Password",
|
|
122
69
|
|
|
123
|
-
//Optional: exclude or include host banner after connection
|
|
70
|
+
//Optional: exclude or include host banner after connection
|
|
124
71
|
showBanner: false,
|
|
125
|
-
|
|
72
|
+
//https://github.com/mscdex/ssh2#pseudo-tty-settings
|
|
73
|
+
window: false,
|
|
126
74
|
|
|
127
75
|
//Optional: Enter key character to send as end of line.
|
|
128
|
-
enter: "\n",
|
|
76
|
+
enter: "\n",
|
|
129
77
|
|
|
130
78
|
//Optional: stream encoding
|
|
131
79
|
streamEncoding: "utf8",
|
|
132
80
|
|
|
133
|
-
//Optional: Regular expressions to
|
|
81
|
+
//Optional: Regular expressions to simplify response
|
|
82
|
+
//defaults:
|
|
134
83
|
asciiFilter: "[^\r\n\x20-\x7e]", //removes non-standard ASCII
|
|
135
84
|
disableColorFilter: false, //turns colour filtering on and off
|
|
136
85
|
textColorFilter: "(\[{1}[0-9;]+m{1})", //removes colour formatting codes
|
|
137
86
|
|
|
138
87
|
//Required: array of commands
|
|
139
|
-
commands: ["cd /var/logs", "ls -al"
|
|
88
|
+
commands: ["cd /var/logs", "ls -al"],
|
|
140
89
|
|
|
141
|
-
//Optional: Used by this.emit("msg", "my message")
|
|
142
|
-
msg: {
|
|
143
|
-
send: function( message ) {
|
|
90
|
+
//Optional: Used by this.emit("msg", "my message")
|
|
91
|
+
msg: function( message ) {
|
|
144
92
|
console.log(message);
|
|
145
93
|
}
|
|
146
94
|
},
|
|
@@ -149,121 +97,98 @@ host = {
|
|
|
149
97
|
verbose: false, //outputs all received content
|
|
150
98
|
debug: false, //outputs information about each process step
|
|
151
99
|
|
|
152
|
-
//Optional: Command time-out
|
|
100
|
+
//Optional: Command time-out to stop a command hanging and not returning to a command prompt
|
|
153
101
|
idleTimeOut: 5000, //integer
|
|
154
102
|
|
|
155
|
-
//Optional: timeout
|
|
103
|
+
//Optional: timeout interval when waiting for a host response.
|
|
156
104
|
dataIdleTimeOut: 500, //integer
|
|
157
105
|
|
|
158
106
|
//Optional: Messages returned on each connection event.
|
|
107
|
+
//default:
|
|
159
108
|
connectedMessage: "Connected",
|
|
160
109
|
readyMessage: "Ready",
|
|
161
110
|
closedMessage: "Closed",
|
|
162
111
|
|
|
163
|
-
//Optional: Host event handlers
|
|
164
|
-
//
|
|
165
|
-
//Host event function definitions replace the default event handlers defined
|
|
166
|
-
//in the class instead of adding another handler to the listeners.
|
|
167
|
-
//`this.` is correctly linked to the instance within host defined event handlers.
|
|
112
|
+
//Optional: Host event handlers .
|
|
113
|
+
//Host defined event handlers are set as the default event handlers.
|
|
168
114
|
|
|
169
|
-
//Optional:
|
|
170
|
-
//This event is only used for the first host connecting through ssh2.connect
|
|
171
|
-
//Required if the first host.server.tryKeyboard is set to true.
|
|
115
|
+
//Optional:
|
|
172
116
|
onKeyboardInteractive: function(name, instructions, instructionsLang, prompts, finish){
|
|
173
|
-
//See https://github.com/mscdex/ssh2#client-events
|
|
174
|
-
//name, instructions, instructionsLang don't seem to be of interest for authenticating
|
|
175
|
-
//prompts is an object of expected prompts and if they are to be shown to the user
|
|
176
|
-
//finish is the function to be called with an array of responses in the same order as
|
|
177
|
-
//the prompts parameter defined them.
|
|
178
|
-
//See [Client events](https://github.com/mscdex/ssh2#client-events) for more information
|
|
179
|
-
//if a non-standard prompt results from a successful connection then handle its
|
|
180
|
-
//detection and response in onCommandProcessing or commandTimeout.
|
|
181
|
-
//see text/keyboard-interactivetest.js
|
|
117
|
+
//See https://github.com/mscdex/ssh2#client-events
|
|
182
118
|
},
|
|
183
119
|
|
|
184
|
-
//Optional:
|
|
185
|
-
//without SSH2shell interacting with it.
|
|
120
|
+
//Optional:
|
|
186
121
|
onData: function( data ) {
|
|
187
|
-
//data is
|
|
122
|
+
//data is the raw response from the host
|
|
188
123
|
},
|
|
189
124
|
|
|
190
|
-
//Optional:
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
125
|
+
//Optional:
|
|
126
|
+
onPipe: function( stream ) {
|
|
127
|
+
//a read stream that will receive raw resonse data
|
|
128
|
+
},
|
|
195
129
|
|
|
196
|
-
//Optional:
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
//source is the read stream to remove from being able to write its output.
|
|
130
|
+
//Optional:
|
|
131
|
+
onUnpipe: function( steam ) {
|
|
132
|
+
//removes the steam added in onPipe.
|
|
200
133
|
},
|
|
201
134
|
|
|
202
|
-
//Optional:
|
|
203
|
-
//until prompt is detected.
|
|
135
|
+
//Optional:
|
|
204
136
|
onCommandProcessing: function( command, response, sshObj, stream ) {
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
//
|
|
208
|
-
//
|
|
137
|
+
//Event rasised when data is received from the host before the command prompt is detected.
|
|
138
|
+
//command: is the last command run.
|
|
139
|
+
//response: is the buffer that is being loaded with each data event.
|
|
140
|
+
//sshObj: is the current host object.
|
|
141
|
+
//stream: gives stream.write() access if a response is required outside the normal command flow.
|
|
209
142
|
},
|
|
210
143
|
|
|
211
|
-
//Optional:
|
|
144
|
+
//Optional:
|
|
212
145
|
onCommandComplete: function( command, response, sshObj ) {
|
|
213
|
-
//
|
|
214
|
-
//
|
|
146
|
+
//Event raised when a standard prompt is detected after a command is run.
|
|
147
|
+
//response: is the full response from the host for the last command.
|
|
148
|
+
//sshObj: is the current host object.
|
|
215
149
|
},
|
|
216
150
|
|
|
217
|
-
//Optional:
|
|
218
|
-
//received from the host after host.idleTimeout value.
|
|
219
|
-
//This stops the connection from hanging when no prompt is detected usually because the
|
|
220
|
-
// host is requiring a response it will never get. This event
|
|
151
|
+
//Optional:
|
|
221
152
|
onCommandTimeout: function( command, response, stream, connection ) {
|
|
222
|
-
//
|
|
223
|
-
//
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
//
|
|
227
|
-
//close the connection
|
|
153
|
+
//Event is raised when a standard prompt is not detected and no data is
|
|
154
|
+
//received from the host within the host.idleTimeout value.
|
|
155
|
+
//command: is the last command run or "" when first connected.
|
|
156
|
+
//response: is the text received up to the time out.
|
|
157
|
+
//stream: gives stream.write() access if a response is required outside the normal command flow.
|
|
158
|
+
//connection: gives access to close the connection if all else fails
|
|
228
159
|
//The timer can be reset from within this event in case a stream write gets no response.
|
|
229
|
-
//See test/timeouttest.js for and example of multiple commandTimeout triggers.
|
|
230
160
|
},
|
|
231
161
|
|
|
232
|
-
//
|
|
233
|
-
//connection is closed or when any nested host connection is closed.
|
|
234
|
-
//This is where you handle the full session text for a host connection.
|
|
235
|
-
//When connecting to multiple hosts the primary host end event receives the full concatenated
|
|
236
|
-
//session text for all hosts, including its own, to process.
|
|
162
|
+
//Optional:
|
|
237
163
|
onEnd: function( sessionText, sshObj ) {
|
|
164
|
+
//is raised when the stream.on ("finish") event is triggered
|
|
238
165
|
//SessionText is the full text for this hosts session
|
|
239
166
|
//sshObj is the host object
|
|
240
167
|
},
|
|
241
168
|
|
|
242
|
-
//Optional:
|
|
169
|
+
//Optional:
|
|
243
170
|
onError: function( err, type, close = false, callback ) {
|
|
244
|
-
//
|
|
245
|
-
//
|
|
246
|
-
//
|
|
247
|
-
//
|
|
248
|
-
//
|
|
171
|
+
//Run when an error event is raised.
|
|
172
|
+
//err: is either an Error object or a string containing the error message
|
|
173
|
+
//type: is a string containing the error type
|
|
174
|
+
//close: is a Boolean value indicating if the connection should be closed or not
|
|
175
|
+
//callback: is the function to run when handling the error defined as function(err,type){}
|
|
176
|
+
//if using this remember to handle closing the connection based on the close parameter.
|
|
249
177
|
//To close the connection us this.connection.close()
|
|
250
178
|
},
|
|
251
179
|
|
|
252
|
-
//Optional:
|
|
180
|
+
//Optional:
|
|
253
181
|
callback: function( sessionText ){
|
|
254
|
-
//sessionText is the full session response
|
|
182
|
+
//sessionText: is the full session response
|
|
255
183
|
//Is overridden by SSH2shell.connect(callback)
|
|
256
184
|
}
|
|
257
185
|
};
|
|
258
186
|
```
|
|
259
187
|
* Host.server will accept current [SSH2.client.connect parameters](https://github.com/mscdex/ssh2#client-methods).
|
|
260
188
|
* Optional host properties or event handlers do not need to be included if you are not changing them.
|
|
261
|
-
* See the end of the readme for event handlers available to be added to the instance listeners.
|
|
262
189
|
* Host event handlers completely replace the default event handler definitions in the class when defined.
|
|
263
|
-
* The instance `this` keyword is available within host event handlers to give access to ssh2shell object api like
|
|
264
|
-
this.emit() and other functions.
|
|
265
190
|
* `this.sshObj` or sshObj variable passed into a function provides access to all the host config, some instance
|
|
266
|
-
variables and the current array of commands for the host. The sshObj.commands array changes with host connection.
|
|
191
|
+
variables and the current array of commands for the host. The sshObj.commands array changes with each host connection.
|
|
267
192
|
|
|
268
193
|
|
|
269
194
|
ssh2shell API
|
|
@@ -272,15 +197,15 @@ SSH2Shell extends events.EventEmitter
|
|
|
272
197
|
|
|
273
198
|
*Methods*
|
|
274
199
|
|
|
275
|
-
* .connect(callback(sessionText)) Is the main function to establish the connection and handle data events from the server
|
|
276
|
-
|
|
200
|
+
* .connect(callback(sessionText)) Is the main function to establish the connection and handle data events from the server.
|
|
201
|
+
It takes in an optional callback function for processing the full session text.
|
|
277
202
|
|
|
278
203
|
* .emit("eventName", function, parms,... ). Raises the event based on the name in the first string and takes input
|
|
279
204
|
parameters based on the handler function definition.
|
|
280
205
|
|
|
281
|
-
* .pipe(
|
|
206
|
+
* .pipe(stream) binds a writable stream to the output of the read stream but only after the connection is established.
|
|
282
207
|
|
|
283
|
-
* .unpipe(
|
|
208
|
+
* .unpipe(stream) removes a piped stream but can only be called after a connection has been made.
|
|
284
209
|
|
|
285
210
|
*Variables*
|
|
286
211
|
|
|
@@ -289,63 +214,24 @@ SSH2Shell extends events.EventEmitter
|
|
|
289
214
|
* .command is the current command being run until a new prompt is detected and the next command replaces it.
|
|
290
215
|
|
|
291
216
|
|
|
292
|
-
Test Files:
|
|
293
|
-
-----
|
|
294
|
-
```javascript
|
|
295
|
-
//single host test
|
|
296
|
-
cp .env-example .env
|
|
297
|
-
//set the env variables to match your test host/vm username and password.
|
|
298
|
-
node text/simple.js
|
|
299
|
-
|
|
300
|
-
//simple pipe example
|
|
301
|
-
node test/pipe.js
|
|
302
|
-
|
|
303
|
-
//multiple nested hosts
|
|
304
|
-
//requires the additional details added to .env file for each server
|
|
305
|
-
//my tests were done using three VM hosts
|
|
306
|
-
node test/tunneltest.js
|
|
307
|
-
|
|
308
|
-
//test the command idle time out timer and provide an example of a more complicated timeout handler
|
|
309
|
-
node test/timeouttest.js
|
|
310
|
-
|
|
311
|
-
//Test multiple sudo and su combinations for changing user
|
|
312
|
-
//Issue #10
|
|
313
|
-
//Also test Prompt detection with no password requested
|
|
314
|
-
//Issue #14
|
|
315
|
-
node test/sudosutest.js
|
|
316
|
-
|
|
317
|
-
//Test using notification commands as the last command
|
|
318
|
-
//Issue #11
|
|
319
|
-
node test/notificationstest.js
|
|
320
|
-
|
|
321
|
-
//Test keyboard-interactive authentication on the host that has it enabled
|
|
322
|
-
node test/keyboard-interactivetest.js
|
|
323
|
-
```
|
|
324
|
-
|
|
325
|
-
|
|
326
217
|
Usage:
|
|
327
218
|
======
|
|
328
219
|
Connecting to a single host:
|
|
329
220
|
----------------------------
|
|
330
221
|
|
|
331
222
|
*How to:*
|
|
332
|
-
* Use an .env file for server values loaded by dotenv from the root of the project.
|
|
333
223
|
* Connect using a key pair with pass phrase.
|
|
334
224
|
* Use sudo su with user password.
|
|
335
225
|
* Set commands.
|
|
336
226
|
* Test the response of a command and add more commands and notifications in the host.onCommandComplete event handler.
|
|
337
227
|
* Use the two notification types in the commands array.
|
|
338
228
|
* Use msg: notifications to track progress in the console as the process completes.
|
|
339
|
-
* Email the final full session text to yourself.
|
|
340
229
|
|
|
341
|
-
(will require a package json with ssh2shell, dotenv and email defined as dependencies)
|
|
342
230
|
|
|
343
231
|
*.env*
|
|
344
232
|
```
|
|
345
|
-
HOST=
|
|
346
|
-
|
|
347
|
-
USER_NAME=myuser
|
|
348
|
-
PASSWORD=mypassword
|
|
233
|
+
HOST=
|
|
234
|
+
USER_NAME=
|
|
349
235
|
PRIV_KEY_PATH=~/.ssh/id_rsa
|
|
350
236
|
PASS_PHRASE=myPassPhrase
|
|
351
237
|
```
|
|
@@ -356,17 +242,16 @@ var dotenv = require('dotenv').config(),
|
|
|
356
242
|
Email = require('email');
|
|
357
243
|
|
|
358
244
|
var host = {
|
|
359
|
-
server:
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
privateKey: require('fs').readFileSync(process.env.PRIV_KEY_PATH)
|
|
245
|
+
server: {
|
|
246
|
+
host: "192.168.0.1",
|
|
247
|
+
userName: "myuser",
|
|
248
|
+
password: "sudoPassword",
|
|
249
|
+
passPhrase: "myPassPhrase",
|
|
250
|
+
privateKey: require('fs').readFileSync("~/.ssh/id_rsa")
|
|
366
251
|
},
|
|
367
252
|
commands: [
|
|
368
253
|
"`This is a message that will be added to the full sessionText`",
|
|
369
|
-
"msg:This is a message that will be
|
|
254
|
+
"msg:This is a message that will be displayed during the process",
|
|
370
255
|
"echo $(pwd)",
|
|
371
256
|
"sudo su",
|
|
372
257
|
"msg:changing directory",
|
|
@@ -374,16 +259,14 @@ var host = {
|
|
|
374
259
|
"ls -l",
|
|
375
260
|
"msg:Confirming the current path",
|
|
376
261
|
"echo $(pwd)",
|
|
377
|
-
"msg:
|
|
262
|
+
"msg:Command dynamically added",
|
|
378
263
|
"ls -l",
|
|
379
264
|
"`All done!`"
|
|
380
265
|
],
|
|
381
266
|
|
|
382
267
|
onCommandComplete: function( command, response, sshObj ) {
|
|
383
268
|
//confirm it is the root home dir and change to root's .ssh folder
|
|
384
|
-
|
|
385
|
-
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete event, command: " + command);
|
|
386
|
-
}
|
|
269
|
+
|
|
387
270
|
if (command === "echo $(pwd)" && response.indexOf("/root") != -1 ) {
|
|
388
271
|
//unshift will add the command as the next command, use push to add command as the last command
|
|
389
272
|
sshObj.commands.unshift("msg:The command and response check worked. Added another cd command.");
|
|
@@ -394,22 +277,6 @@ var host = {
|
|
|
394
277
|
this.emit("msg", response);
|
|
395
278
|
}
|
|
396
279
|
},
|
|
397
|
-
|
|
398
|
-
onEnd: function( sessionText, sshObj ) {
|
|
399
|
-
//email the session text instead of outputting it to the console
|
|
400
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": host.onEnd event");}
|
|
401
|
-
var sessionEmail = new Email({
|
|
402
|
-
from: "me@example.com",
|
|
403
|
-
to: "me@example.com",
|
|
404
|
-
subject: "Automated SSH Session Response",
|
|
405
|
-
body: "\nThis is the full session responses for " + sshObj.server.host + ":\n\n" + sessionText
|
|
406
|
-
});
|
|
407
|
-
this.emit("msg", "Sending session response email");
|
|
408
|
-
|
|
409
|
-
// if callback is provided, errors will be passed into it
|
|
410
|
-
// else errors will be thrown
|
|
411
|
-
sessionEmail.send(function(err){ sshObj.msg.send('error', err, 'Email'); });
|
|
412
|
-
}
|
|
413
280
|
};
|
|
414
281
|
|
|
415
282
|
|
|
@@ -417,10 +284,6 @@ var host = {
|
|
|
417
284
|
var SSH2Shell = require ('ssh2shell'),
|
|
418
285
|
SSH = new SSH2Shell(host);
|
|
419
286
|
|
|
420
|
-
//Start the process
|
|
421
|
-
SSH.connect();
|
|
422
|
-
|
|
423
|
-
or
|
|
424
287
|
//use a callback
|
|
425
288
|
var callback = function (sessionText){
|
|
426
289
|
console.log (sessionText);
|
|
@@ -428,276 +291,309 @@ var callback = function (sessionText){
|
|
|
428
291
|
SSH.connect(callback);
|
|
429
292
|
```
|
|
430
293
|
|
|
431
|
-
Tunnelling nested host objects:
|
|
432
|
-
---------------------------------
|
|
433
|
-
SSH tunnelling has been incorporated into core of the class process enabling nested host objects.
|
|
434
|
-
The new `hosts: [ host1, host2]` setting can make multiple host connections possible.
|
|
435
|
-
Each host config object has its own server settings, commands, command handlers and
|
|
436
|
-
event handlers. Each host object also has its own hosts array that other host objects can be added to.
|
|
437
|
-
This provides for different host connection sequences to any depth of recursion.
|
|
438
294
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
295
|
+
Authentication:
|
|
296
|
+
---------------
|
|
297
|
+
* Each host authenticates with its own host.server parameters.
|
|
298
|
+
* When using key authentication you may require a valid pass phrase if your key was created with one.
|
|
299
|
+
* When using fingerprint validation both host.server.hashMethod property and host.server.hostVerifier function must be
|
|
300
|
+
set.
|
|
301
|
+
* When using keyboard-interactive authentication both host.server.tryKeyboard and instance.on ("keayboard-interactive",
|
|
302
|
+
function...) or host.onKeyboardInteractive() must be defined.
|
|
303
|
+
* Set the default cyphers and keys.
|
|
444
304
|
|
|
445
|
-
|
|
305
|
+
Default Cyphers:
|
|
306
|
+
---------------
|
|
307
|
+
Default Cyphers and Keys used in the initial ssh connection can be redefined by setting the ssh2.connect.algorithms through the host.server.algorithms option.
|
|
308
|
+
As with this property all ssh2.connect properties are set in the host.server object.
|
|
309
|
+
|
|
310
|
+
*Example:*
|
|
311
|
+
```javascript
|
|
446
312
|
var host = {
|
|
447
|
-
server:
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
313
|
+
server: {
|
|
314
|
+
host: "<host IP>",
|
|
315
|
+
port: "22",
|
|
316
|
+
userName: "<username>",
|
|
317
|
+
password: "<password>",
|
|
318
|
+
hashMethod: "md5", //optional "md5" or "sha1" default is "md5"
|
|
319
|
+
//other ssh2.connect options
|
|
320
|
+
algorithms: {
|
|
321
|
+
kex: [
|
|
322
|
+
'diffie-hellman-group1-sha1',
|
|
323
|
+
'ecdh-sha2-nistp256',
|
|
324
|
+
'ecdh-sha2-nistp384',
|
|
325
|
+
'ecdh-sha2-nistp521',
|
|
326
|
+
'diffie-hellman-group-exchange-sha256',
|
|
327
|
+
'diffie-hellman-group14-sha1'],
|
|
328
|
+
cipher: [
|
|
329
|
+
'aes128-ctr',
|
|
330
|
+
'aes192-ctr',
|
|
331
|
+
'aes256-ctr',
|
|
332
|
+
'aes128-gcm',
|
|
333
|
+
'aes128-gcm@openssh.com',
|
|
334
|
+
'aes256-gcm',
|
|
335
|
+
'aes256-gcm@openssh.com',
|
|
336
|
+
'aes256-cbc'
|
|
337
|
+
]
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
},
|
|
341
|
+
......
|
|
464
342
|
}
|
|
465
343
|
```
|
|
466
344
|
|
|
345
|
+
Fingerprint Validation:
|
|
346
|
+
---------------
|
|
347
|
+
At connection time the hash of the server’s public key can be compared with the hash the client had previously recorded
|
|
348
|
+
for that server. This stops "man in the middle" attacks where you are redirected to a different server as you connect
|
|
349
|
+
to the server you expected to. This hash only changes with a reinstall of SSH, a key change on the server or a load
|
|
350
|
+
balancer is now in place.
|
|
467
351
|
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
to
|
|
352
|
+
__*Note:*
|
|
353
|
+
Fingerprint check doesn't work the same way for tunnelling. The first host will validate using this method but the
|
|
354
|
+
subsequent connections would have to be handled by your commands. Only the first host uses the SSH2 connection method
|
|
355
|
+
that does the validation.__
|
|
471
356
|
|
|
357
|
+
To use fingerprint validation you first need the server hash string which can be obtained using ssh2shell as follows:
|
|
358
|
+
* Set host.verbose to true then set host.server.hashKey to any non-empty string (say "1234").
|
|
359
|
+
* Validation will be checked and fail causing the connection to terminate.
|
|
360
|
+
* A verbose message will return both the server hash and client hash values that failed comparison.
|
|
361
|
+
* This is also what will happen if your hash fails the comparison with the server in the normal verification process.
|
|
362
|
+
* Turn on verbose in the host object, run your script with hashKey unset and check the very start of the text returned
|
|
363
|
+
for the servers hash value.
|
|
364
|
+
* The servers hash value can be saved to a variable outside the host or class so you can access it without having to
|
|
365
|
+
parse response text.
|
|
366
|
+
|
|
367
|
+
*Example:*
|
|
368
|
+
```javascript
|
|
369
|
+
//Define the hostValidation function in the host.server config.
|
|
370
|
+
//hashKey needs to be defined at the top level if you want to access the server hash at run time
|
|
371
|
+
var serverHash, host;
|
|
372
|
+
//don't set expectedHash if you want to know the server hash
|
|
373
|
+
var expectedHash
|
|
374
|
+
expectedHash = "85:19:8a:fb:60:4b:94:13:5c:ea:fe:3b:99:c7:a5:4e";
|
|
375
|
+
|
|
376
|
+
host = {
|
|
377
|
+
server: {
|
|
378
|
+
//other normal connection params,
|
|
379
|
+
hashMethod: "md5", //"md5" or "sha1"
|
|
380
|
+
//hostVerifier function must be defined and return true for match of false for failure.
|
|
381
|
+
hostVerifier: function(hashedKey) {
|
|
382
|
+
var recievedHash;
|
|
383
|
+
|
|
384
|
+
expectedHash = expectedHash + "".replace(/[:]/g, "").toLowerCase();
|
|
385
|
+
recievedHash = hashedKey + "".replace(/[:]/g, "").toLowerCase();
|
|
386
|
+
if (expectedHash === "") {
|
|
387
|
+
//No expected hash so save save what was received from the host (hashedKey)
|
|
388
|
+
//serverHash needs to be defined before host object
|
|
389
|
+
serverHash = hashedKey;
|
|
390
|
+
console.log("Server hash: " + serverHash);
|
|
391
|
+
return true;
|
|
392
|
+
} else if (recievedHash === expectedHash) {
|
|
393
|
+
console.log("Hash values matched");
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
//Output the failed comparison to the console if you want to see what went wrong
|
|
397
|
+
console.log("Hash values: Server = " + recievedHash + " <> Client = " + expectedHash);
|
|
398
|
+
return false;
|
|
399
|
+
},
|
|
400
|
+
},
|
|
401
|
+
//Other settings
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
var SSH2Shell = require ('ssh2shell'),
|
|
405
|
+
SSH = new SSH2Shell(host);
|
|
406
|
+
SSH.connect();
|
|
472
407
|
```
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
408
|
+
__*Note:*
|
|
409
|
+
host.server.hashMethod only supports md5 or sha1 according to the current SSH2 documentation anything else may produce
|
|
410
|
+
undesired results.__
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
Keyboard-interactive
|
|
414
|
+
----------------------
|
|
415
|
+
Keyboard-interactive authentication is available when both host.server.tryKeyboard is set to true and the event handler
|
|
416
|
+
keyboard-interactive is defined as below. The keyboard-interactive event handler can only be used on the first connection.
|
|
417
|
+
|
|
418
|
+
Also see [test/keyboard-interactivetest.js](https://github.com/cmp-202/ssh2shell/blob/master/test/keyboard-interactivetest.js) for the full example
|
|
419
|
+
|
|
420
|
+
*Defining the event handler:*
|
|
421
|
+
```javascript
|
|
422
|
+
//this is required
|
|
423
|
+
host.server.tryKeyboard = true;
|
|
424
|
+
|
|
425
|
+
var SSH2Shell = require ('../lib/ssh2shell');
|
|
426
|
+
var SSH = new SSH2Shell(host);
|
|
427
|
+
|
|
428
|
+
//Add the keyboard-interactive handler
|
|
429
|
+
//The event function must call finish() with an array of responses in the same order as prompts received
|
|
430
|
+
// in the prompts array
|
|
431
|
+
SSH.on ('keyboard-interactive', function(name, instructions, instructionsLang, prompts, finish){
|
|
432
|
+
if (this.sshObj.debug) {this.emit('msg', this.sshObj.server.host + ": Keyboard-interactive");}
|
|
433
|
+
if (this.sshObj.verbose){
|
|
434
|
+
this.emit('msg', "name: " + name);
|
|
435
|
+
this.emit('msg', "instructions: " + instructions);
|
|
436
|
+
var str = JSON.stringify(prompts, null, 4);
|
|
437
|
+
this.emit('msg', "Prompts object: " + str);
|
|
438
|
+
}
|
|
439
|
+
//The example presumes only the password is required
|
|
440
|
+
finish([this.sshObj.server.password] );
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
SSH.connect();
|
|
478
444
|
```
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
445
|
+
|
|
446
|
+
Or
|
|
447
|
+
|
|
448
|
+
```javascript
|
|
449
|
+
host = {
|
|
450
|
+
...,
|
|
451
|
+
onKeyboardInteractive: function(name, instructions, instructionsLang, prompts, finish){
|
|
452
|
+
if (this.sshObj.debug) {this.emit('msg', this.sshObj.server.host + ": Keyboard-interactive");}
|
|
453
|
+
if (this.sshObj.verbose){
|
|
454
|
+
this.emit('msg', "name: " + name);
|
|
455
|
+
this.emit('msg', "instructions: " + instructions);
|
|
456
|
+
var str = JSON.stringify(prompts, null, 4);
|
|
457
|
+
this.emit('msg', "Prompts object: " + str);
|
|
458
|
+
}
|
|
459
|
+
//The example presumes only the password is required
|
|
460
|
+
finish([this.sshObj.server.password] );
|
|
461
|
+
},
|
|
462
|
+
...
|
|
463
|
+
}
|
|
482
464
|
```
|
|
483
465
|
|
|
484
|
-
*The nested process:*
|
|
485
466
|
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
3. Server1 is stored for use later and server2's host object is loaded as the current host.
|
|
489
|
-
4. A connection to server2 is made using its server parameters via running the ssh command on the primary.
|
|
490
|
-
5. Server2's commands are completed and server2.hosts array is checked for other hosts.
|
|
491
|
-
6. With no hosts found the connection to server2 is closed triggering an end event (calling server2.onEnd function if defined).
|
|
492
|
-
5. Server1 host object is reloaded as the current host object and server2 host object discarded.
|
|
493
|
-
6. Server1.hosts array is checked for other hosts and the next host popped off the array.
|
|
494
|
-
7. Server1's host object is stored again and server3's host object is loaded as the current host.
|
|
495
|
-
8. Server3 is connected to and it completes its process.
|
|
496
|
-
9. Server3.hosts is checked and with no hosts found the connection is closed and the end event is triggered.
|
|
497
|
-
9. Server1 is loaded for the last time.
|
|
498
|
-
10. The session text for each connection is appended to the session text for the primary host.
|
|
499
|
-
11. With no further hosts to load the connection is closed triggering an end event for the last time.
|
|
500
|
-
12. As all sessions are closed the process ends.
|
|
467
|
+
Trouble shooting:
|
|
468
|
+
-----------------
|
|
501
469
|
|
|
470
|
+
* Adding msg command `"msg:Doing something"` to your commands array at key points will help you track the sequence of
|
|
471
|
+
what has been done as the process runs. (See examples)
|
|
472
|
+
* `Error: Unable to parse private key while generating public key (expected sequence)` is caused by the pass phrase
|
|
473
|
+
being incorrect. This confused me because it doesn't indicate the pass phrase was the problem but it does indicate
|
|
474
|
+
that it could not decrypt the private key.
|
|
475
|
+
* Recheck your pass phrase for typos or missing chars.
|
|
476
|
+
* Try connecting manually to the host using the exact pass phrase used by the code to confirm it works.
|
|
477
|
+
* I did read of people having problems with the pass phrase or password having an \n added when used from an
|
|
478
|
+
external file causing it to fail. They had to add .trim() when setting it.
|
|
479
|
+
* If your password is incorrect the connection will return an error.
|
|
480
|
+
* There is an optional debug setting in the host object that will output process information when set to true and
|
|
481
|
+
passwords for failed authentication of sudo commands and tunnelling. `host.debug = true`
|
|
482
|
+
* The class now has an idle time out timer (default:5000ms) to stop unexpected command prompts from causing the process
|
|
483
|
+
hang without error. The default time out can be changed by setting the host.idleTimeOut with a value in milliseconds.
|
|
484
|
+
(1000 = 1 sec)
|
|
502
485
|
|
|
503
|
-
**_Note:_**
|
|
504
|
-
* A host object needs to be defined before it is added to another host.hosts array.
|
|
505
|
-
* Only the primary host objects connected, ready and closed messages will be used by ssh2shell.
|
|
506
|
-
* Connection events only apply to the primary host. Keyboard-interactive event handler is one of these.
|
|
507
486
|
|
|
487
|
+
Verbose and Debug:
|
|
488
|
+
------------------
|
|
489
|
+
* When host.verbose is set to true each command complete raises a msg event outputting the response text.
|
|
490
|
+
* When host.debug is set to true each process step raises a msg event to help identify what the internal processes were.
|
|
508
491
|
|
|
509
|
-
*
|
|
510
|
-
|
|
511
|
-
* Use unique host connection settings for each host
|
|
512
|
-
* Defining different commands and command event handlers for each host
|
|
513
|
-
* Sharing duplicate functions between host objects
|
|
514
|
-
* What host object attributes you can leave out of primary and secondary host objects
|
|
515
|
-
* Unique event handlers set in host objects, common event handler set on class instance
|
|
492
|
+
__*Note:*
|
|
493
|
+
Do not add debug or verbose to the onCommandProccessing event which is called every time a response is received from the host.__
|
|
516
494
|
|
|
517
|
-
|
|
518
|
-
|
|
495
|
+
Add your own verbose messages as follows:
|
|
496
|
+
`if(this.sshObj.verbose){this.emit("msg", this.sshObj.server.host + ": response: " + response);} //response might need to be changed to this._buffer`
|
|
519
497
|
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
dotenv.load();
|
|
498
|
+
Add your own debug messages as follows:
|
|
499
|
+
`if(this.sshObj.debug){this.emit("msg", this.sshObj.server.host + ": eventName");} //where eventName is the text identifying what happened`
|
|
523
500
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
port: process.env.SERVER1_PORT,
|
|
528
|
-
userName: process.env.SERVER1_USER_NAME,
|
|
529
|
-
password: process.env.SERVER1_PASSWORD,
|
|
530
|
-
passPhrase: process.env.SERVER1_PASS_PHRASE,
|
|
531
|
-
privateKey: require('fs').readFileSync(process.env.SERVER1_PRIV_KEY_PATH)
|
|
532
|
-
},
|
|
533
|
-
conParamsHost2 = {
|
|
534
|
-
host: process.env.SERVER2_HOST,
|
|
535
|
-
port: process.env.SERVER2_PORT,
|
|
536
|
-
userName: process.env.SERVER2_USER_NAME,
|
|
537
|
-
password: process.env.SERVER2_PASSWORD
|
|
538
|
-
},
|
|
539
|
-
conParamsHost3 = {
|
|
540
|
-
host: process.env.SERVER3_HOST,
|
|
541
|
-
port: process.env.SERVER3_PORT,
|
|
542
|
-
userName: process.env.SERVER3_USER_NAME,
|
|
543
|
-
password: process.env.SERVER3_PASSWORD
|
|
544
|
-
}
|
|
545
|
-
|
|
501
|
+
Notification commands:
|
|
502
|
+
----------------------
|
|
503
|
+
There are two notification commands that are added to the host.commands array but are not run as a command on the host.
|
|
546
504
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
commands: [
|
|
551
|
-
"msg:connected to host: passed. Listing dir.",
|
|
552
|
-
"ls -l"
|
|
553
|
-
],
|
|
554
|
-
debug: false,
|
|
555
|
-
onCommandComplete: function( command, response, sshObj ) {
|
|
556
|
-
//we are listing the dir so output it to the msg handler
|
|
557
|
-
if(sshObj.debug){
|
|
558
|
-
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete host1, command: " + command);
|
|
559
|
-
}
|
|
560
|
-
},
|
|
561
|
-
onEnd: function( sessionText, sshObj ) {
|
|
562
|
-
//show the full session output for all hosts.
|
|
563
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": primary host.onEnd all sessiontText");}
|
|
564
|
-
this.emit ("msg", "\nAll Hosts SessiontText ---------------------------------------\n");
|
|
565
|
-
this.emit ("msg", sshObj.server.host + ":\n" + sessionText);
|
|
566
|
-
this.emit ("msg", "\nEnd sessiontText ---------------------------------------------\n");
|
|
567
|
-
})
|
|
568
|
-
},
|
|
505
|
+
1. `"msg:This is a message"`. outputs to the console.
|
|
506
|
+
2. "\`SessionText notification\`" will take the text between "\` \`" and add it to the sessionText only.
|
|
507
|
+
* The reason for not using echo or printf commands as a normal command is that you see both the command and the message in the sessionText which is pointless when all you want is the message.
|
|
569
508
|
|
|
570
|
-
host2 = {
|
|
571
|
-
server: conParamsHost2,
|
|
572
|
-
commands: [
|
|
573
|
-
"msg:connected to host: passed",
|
|
574
|
-
"msg:Changing to root dir",
|
|
575
|
-
"cd ~/",
|
|
576
|
-
"msg:Listing dir",
|
|
577
|
-
"ls -l"
|
|
578
|
-
],
|
|
579
|
-
debug: false,
|
|
580
|
-
connectedMessage: "Connected to host2",
|
|
581
|
-
onCommandComplete: function( command, response, sshObj ) {
|
|
582
|
-
//we are listing the dir so output it to the msg handler
|
|
583
|
-
if(sshObj.debug){
|
|
584
|
-
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete host2, command: " + command);
|
|
585
|
-
}
|
|
586
|
-
if (command.indexOf("cd") != -1){
|
|
587
|
-
this.emit("msg", this.sshObj.server.host + ": Just ran a cd command:\n");
|
|
588
|
-
this.emit("msg", response);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
},
|
|
592
509
|
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
],
|
|
599
|
-
debug: false,
|
|
600
|
-
connectedMessage: "Connected to host3",
|
|
601
|
-
onCommandComplete: function( command, response, sshObj) {
|
|
602
|
-
//we are listing the dir so output it to the msg handler
|
|
603
|
-
if(sshObj.debug){
|
|
604
|
-
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete host3, command: " + command);
|
|
605
|
-
}
|
|
606
|
-
if (command.indexOf("cd") != -1){
|
|
607
|
-
this.emit("msg", this.sshObj.server.host + ": Just ran hostname command:\n");
|
|
608
|
-
this.emit("msg", response);
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
}
|
|
510
|
+
Sudo and su Commands:
|
|
511
|
+
--------------
|
|
512
|
+
It is possible to use `sudo [command]`, `sudo su`, `su [username]` and `sudo -u [username] -i`.
|
|
513
|
+
Sudo commands uses the password for the current session and is processed by ssh2shell. Su on the other hand uses the password
|
|
514
|
+
of root or an other user (`su seconduser`) and requires you detect the password prompt in `host.onCommandProcessing` and run `this.runCommand(password)`.
|
|
612
515
|
|
|
613
|
-
|
|
614
|
-
|
|
516
|
+
See: [su VS sudo su VS sudo -u -i](http://johnkpaul.tumblr.com/post/19841381351/su-vs-sudo-su-vs-sudo-u-i) for
|
|
517
|
+
clarification about the difference between the commands.
|
|
615
518
|
|
|
616
|
-
|
|
617
|
-
//host2.hosts = [ host3 ];
|
|
618
|
-
//host1.hosts = [ host2 ];
|
|
519
|
+
See: [test/sudosutest.js](https://github.com/cmp-202/ssh2shell/blob/master/test/sudosutest.js) for a working code example.
|
|
619
520
|
|
|
620
|
-
//Create the new instance
|
|
621
|
-
var SSH2Shell = require ('ssh2shell'),
|
|
622
|
-
SSH = new SSH2Shell(host1);
|
|
623
521
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
if(sshObj.debug){
|
|
628
|
-
this.emit("msg", this.sshObj.server.host + ": instance.onCommandComplete, command: " + command);
|
|
629
|
-
}
|
|
630
|
-
if (command == "ls -l"){
|
|
631
|
-
this.emit("msg", this.sshObj.server.host + ":\n" + response);
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
//Add an on end event handler used by all hosts
|
|
636
|
-
SSH.on ('end', function( sessionText, sshObj ) {
|
|
637
|
-
//show the full session output. This could be emailed or saved to a log file.
|
|
638
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": instanse.onEnd all hosts");}
|
|
639
|
-
|
|
640
|
-
this.emit ("msg", "\nSessiontText -------------------------------------------------\n");
|
|
641
|
-
this.emit ("msg", sshObj.server.host + ":\n" + sessionText);
|
|
642
|
-
this.emit ("msg", "\nEnd sessiontText ---------------------------------------------\n");
|
|
643
|
-
});
|
|
522
|
+
Prompt detection override:
|
|
523
|
+
-------------------------
|
|
524
|
+
Used to detect different prompts.
|
|
644
525
|
|
|
645
|
-
|
|
646
|
-
|
|
526
|
+
These are optional settings.
|
|
527
|
+
```
|
|
528
|
+
host.standardPrompt = ">$%#";
|
|
529
|
+
host.passwordPrompt = ":";
|
|
530
|
+
host.passphrasePrompt = ":";
|
|
531
|
+
```
|
|
647
532
|
|
|
648
|
-
|
|
533
|
+
|
|
534
|
+
Text regular expression filters:
|
|
535
|
+
-------------------------------
|
|
536
|
+
There are two regular expression filters that remove unwanted text from response data.
|
|
537
|
+
|
|
538
|
+
The first removes non-standard ascii and the second removes ANSI text formatting codes. Both of these can be modified in
|
|
539
|
+
your host object to override defaults. It is also possible to output the ANSI codes by setting disableColorFilter to true.
|
|
540
|
+
|
|
541
|
+
Defaults:
|
|
542
|
+
```javascript
|
|
543
|
+
host.asciiFilter = "[^\r\n\x20-\x7e]"
|
|
544
|
+
host.disableColorFilter = false //or true
|
|
545
|
+
host.textColorFilter = "(\[{1}[0-9;]+m{1})"
|
|
546
|
+
```
|
|
649
547
|
|
|
548
|
+
|
|
549
|
+
Responding to non-standard command prompts:
|
|
550
|
+
----------------------
|
|
551
|
+
In host.onCommandProcessing event handler the prompt can be detected and a response can be sent via `stream.write("y\n")`.
|
|
650
552
|
|
|
651
|
-
|
|
652
|
-
|
|
553
|
+
`host.onCommandProcessing` definition replaces the default handler and runs only for the current host connection
|
|
554
|
+
```javascript
|
|
555
|
+
host.onCommandProcessing = function( command, response, sshObj, stream ) {
|
|
556
|
+
//Check the command and prompt exits and respond with a 'y' but only does it once
|
|
557
|
+
if (command == "apt-get install nano" && response.indexOf("[y/N]?") != -1 && sshObj.firstRun != true) {
|
|
558
|
+
//This debug message will only run when conditions are met not on every data event so is ok here
|
|
559
|
+
sshObj.firstRun = true
|
|
560
|
+
stream.write('y\n');
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
\\sshObj.firstRun could be reset to false in host.onCommandComplete to allow for detect another non-standard prompt
|
|
564
|
+
```
|
|
653
565
|
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
* Try connecting manually to the host using the exact pass phrase used by the code to confirm it works.
|
|
661
|
-
* I did read of people having problems with the pass phrase or password having an \n added when used from an
|
|
662
|
-
external file causing it to fail. They had to add .trim() when setting it.
|
|
663
|
-
* If your password is incorrect the connection will return an error.
|
|
664
|
-
* There is an optional debug setting in the host object that will output process information when set to true and
|
|
665
|
-
passwords for failed authentication of sudo commands and tunnelling. `host.debug = true`
|
|
666
|
-
* The class now has an idle time out timer (default:5000ms) to stop unexpected command prompts from causing the process
|
|
667
|
-
hang without error. The default time out can be changed by setting the host.idleTimeOut with a value in milliseconds.
|
|
668
|
-
(1000 = 1 sec)
|
|
566
|
+
Instance definition that runs in parallel with every other commandProcessing for every host connection
|
|
567
|
+
To handle all hosts the same add an event handler to the class instance
|
|
568
|
+
Don't define an event handler in the host object with the same code, it will do it twice!
|
|
569
|
+
```javascript
|
|
570
|
+
var SSH2Shell = require ('ssh2shell');
|
|
571
|
+
var SSH = new SSH2Shell(host);
|
|
669
572
|
|
|
573
|
+
SSH.on ('commandProcessing', function onCommandProcessing( command, response, sshObj, stream ) {
|
|
670
574
|
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
575
|
+
//Check the command and prompt exits and respond with a 'y'
|
|
576
|
+
if (command == "apt-get install nano" && response.indexOf("[y/N]?") != -1 && sshObj.firstRun != true ) {
|
|
577
|
+
//This debug message will only run when conditions are met not on every data event so is ok here
|
|
578
|
+
if (sshObj.debug) {this.emit('msg', this.sshObj.server.host + ": Responding to nano install");}
|
|
579
|
+
sshObj.firstRun = true
|
|
580
|
+
stream.write('y\n');
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
```
|
|
676
584
|
|
|
677
585
|
__*Note:*
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
Add your own verbose messages as follows:
|
|
681
|
-
`if(this.sshObj.verbose){this.emit("msg", this.sshObj.server.host + ": response: " + response);}` //response might need
|
|
682
|
-
to be changed to this._buffer
|
|
683
|
-
|
|
684
|
-
Add your own debug messages as follows:
|
|
685
|
-
`if(this.sshObj.debug){this.emit("msg", this.sshObj.server.host + ": eventName");}` //where eventName is the text
|
|
686
|
-
identifying what happened
|
|
586
|
+
If no prompt is detected `commandTimeout` will be raised after the idleTimeOut period.__
|
|
687
587
|
|
|
688
588
|
|
|
689
|
-
Command Time-out
|
|
589
|
+
Command Time-out event
|
|
690
590
|
---------------
|
|
691
|
-
When
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
the
|
|
697
|
-
enabling the process to continue. It is recommended to close the connection as a default action if all else fails so you
|
|
698
|
-
are not left with a hanging script again. The default action is to add the last response text to the session text and
|
|
699
|
-
disconnect. Enabling host.debug would also provide the process path leading up to disconnection which in conjunction with
|
|
700
|
-
the session text would clarify what command and output triggered the event.
|
|
591
|
+
When onCommandTimeout event triggers after the host.idleTimeOut is exceeded.
|
|
592
|
+
This is because there is no new data and no prompt is detected to run the next command.
|
|
593
|
+
It is recommended to close the connection as a default action if all else fails so you are not left with a hanging script.
|
|
594
|
+
The default action is to add the last response text to the session text and disconnect.
|
|
595
|
+
Enabling host.debug would also provide the process path leading up to disconnection which in conjunction with
|
|
596
|
+
the session text would clarify what command and output triggered the timeout event.
|
|
701
597
|
|
|
702
598
|
**Note: If you receive garble back before the clear response you may need to save the previous response text to the
|
|
703
599
|
sessionText and clear the buffer before using stream.write() in commandTimeout.
|
|
@@ -706,7 +602,6 @@ the session text would clarify what command and output triggered the event.
|
|
|
706
602
|
|
|
707
603
|
```javascript
|
|
708
604
|
host.onCommandTimeout = function( command, response, stream, connection ) {
|
|
709
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": host.onCommandTimeout");}
|
|
710
605
|
if (command === "atp-get install node"
|
|
711
606
|
&& response.indexOf("[Y/n]?") != -1
|
|
712
607
|
&& this.sshObj.nodePrompt != true) {
|
|
@@ -723,27 +618,11 @@ host.onCommandTimeout = function( command, response, stream, connection ) {
|
|
|
723
618
|
})
|
|
724
619
|
}
|
|
725
620
|
}
|
|
621
|
+
```
|
|
726
622
|
|
|
727
623
|
or
|
|
728
624
|
|
|
729
|
-
|
|
730
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": host.onCommandTimeout");}
|
|
731
|
-
if (command === "" && response === "Connected to port 22" && this.sshObj.noFirstPrompt != true) {
|
|
732
|
-
//Setting this.sshObj.noFirstPrompt stops a response loop
|
|
733
|
-
this.sshObj.noFirstPrompt = true
|
|
734
|
-
stream.write('\n')
|
|
735
|
-
return true
|
|
736
|
-
}
|
|
737
|
-
//emit an error that passes true for the close parameter and callback the loads the last of session text
|
|
738
|
-
this.emit ("error", this.sshObj.server.host
|
|
739
|
-
+ ": Command timed out after #{this._idleTime/1000} seconds. command: "
|
|
740
|
-
+ command, "Timeout", true, function(err, type){
|
|
741
|
-
this.sshObj.sessionText += response
|
|
742
|
-
})
|
|
743
|
-
}
|
|
744
|
-
|
|
745
|
-
or
|
|
746
|
-
|
|
625
|
+
```javascript
|
|
747
626
|
//reset the default handler to do nothing so it doesn't close the connection
|
|
748
627
|
host.onCommandTimeout = function( command, response, stream, connection ) {};
|
|
749
628
|
|
|
@@ -753,323 +632,235 @@ var SSH2Shell = require ('ssh2shell'),
|
|
|
753
632
|
|
|
754
633
|
//And do it all in the instance event handler
|
|
755
634
|
SSH.on ('commandTimeout',function( command, response, stream, connection ){
|
|
756
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": instance.onCommandTimeout");}
|
|
757
635
|
//first test should only pass once to stop a response loop
|
|
758
636
|
if (command === "atp-get install node"
|
|
759
637
|
&& response.indexOf("[Y/n]?") != -1
|
|
760
638
|
&& this.sshObj.nodePrompt != true) {
|
|
761
639
|
this.sshObj.nodePrompt = true;
|
|
762
640
|
stream.write('y\n');
|
|
641
|
+
|
|
763
642
|
return true;
|
|
764
643
|
}
|
|
765
644
|
this.sshObj.sessionText += response;
|
|
645
|
+
//emit an error that closes the connection
|
|
766
646
|
this.emit("error", this.sshObj.server.host + ": Command \`" + command + "\` timed out after "
|
|
767
647
|
+ (this._idleTime / 1000) + " seconds. command: " + command, "Command Timeout", true);
|
|
768
648
|
});
|
|
769
649
|
|
|
770
650
|
SSH.on ('end', function( sessionText, sshObj ) {
|
|
771
|
-
//show the full session output. This could be emailed or saved to a log file.
|
|
772
|
-
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": instance.onEnd");}
|
|
773
651
|
this.emit("msg","\nSession text for " + sshObj.server.host + ":\n" + sessionText);
|
|
774
652
|
});
|
|
775
653
|
|
|
776
654
|
SSH.connect();
|
|
777
655
|
```
|
|
778
656
|
|
|
779
|
-
Authentication:
|
|
780
|
-
---------------
|
|
781
|
-
* Each host authenticates with its own host.server parameters.
|
|
782
|
-
* When using key authentication you may require a valid pass phrase if your key was created with one.
|
|
783
|
-
* When using fingerprint validation both host.server.hashMethod property and host.server.hostVerifier function must be
|
|
784
|
-
set.
|
|
785
|
-
* When using keyboard-interactive authentication both host.server.tryKeyboard and instance.on ("keayboard-interactive",
|
|
786
|
-
function...) or host.onKeyboardInteractive() must be defined.
|
|
787
|
-
* Set the default cyphers and keys.
|
|
788
|
-
|
|
789
|
-
Default Cyphers:
|
|
790
|
-
---------------
|
|
791
|
-
Default Cyphers and Keys used in the initial ssh connection can be redefined by setting the ssh2.connect.algorithms through the host.server.algorithms option.
|
|
792
|
-
As with this property all ssh2.connect properties are set in the host.server object.
|
|
793
|
-
|
|
794
|
-
*Example:*
|
|
795
|
-
```javascript
|
|
796
|
-
var host = {
|
|
797
|
-
server: {
|
|
798
|
-
host: "<host IP>",
|
|
799
|
-
port: "22",
|
|
800
|
-
userName: "<username>",
|
|
801
|
-
password: "<password>",
|
|
802
|
-
hashMethod: "md5", //optional "md5" or "sha1" default is "md5"
|
|
803
|
-
//other ssh2.connect options
|
|
804
|
-
algorithms: {
|
|
805
|
-
kex: [
|
|
806
|
-
'diffie-hellman-group1-sha1',
|
|
807
|
-
'ecdh-sha2-nistp256',
|
|
808
|
-
'ecdh-sha2-nistp384',
|
|
809
|
-
'ecdh-sha2-nistp521',
|
|
810
|
-
'diffie-hellman-group-exchange-sha256',
|
|
811
|
-
'diffie-hellman-group14-sha1'],
|
|
812
|
-
cipher: [
|
|
813
|
-
'aes128-ctr',
|
|
814
|
-
'aes192-ctr',
|
|
815
|
-
'aes256-ctr',
|
|
816
|
-
'aes128-gcm',
|
|
817
|
-
'aes128-gcm@openssh.com',
|
|
818
|
-
'aes256-gcm',
|
|
819
|
-
'aes256-gcm@openssh.com',
|
|
820
|
-
'aes256-cbc'
|
|
821
|
-
]
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
},
|
|
825
|
-
......
|
|
826
|
-
}
|
|
827
|
-
```
|
|
828
|
-
|
|
829
|
-
Fingerprint Validation:
|
|
830
|
-
---------------
|
|
831
|
-
At connection time the hash of the server’s public key can be compared with the hash the client had previously recorded
|
|
832
|
-
for that server. This stops "man in the middle" attacks where you are redirected to a different server as you connect
|
|
833
|
-
to the server you expected to. This hash only changes with a reinstall of SSH, a key change on the server or a load
|
|
834
|
-
balancer is now in place.
|
|
835
|
-
|
|
836
|
-
__*Note:*
|
|
837
|
-
Fingerprint check doesn't work the same way for tunnelling. The first host will validate using this method but the
|
|
838
|
-
subsequent connections would have to be handled by your commands. Only the first host uses the SSH2 connection method
|
|
839
|
-
that does the validation.__
|
|
840
|
-
|
|
841
|
-
To use fingerprint validation you first need the server hash string which can be obtained using ssh2shell as follows:
|
|
842
|
-
* Set host.verbose to true then set host.server.hashKey to any non-empty string (say "1234").
|
|
843
|
-
* Validation will be checked and fail causing the connection to terminate.
|
|
844
|
-
* A verbose message will return both the server hash and client hash values that failed comparison.
|
|
845
|
-
* This is also what will happen if your hash fails the comparison with the server in the normal verification process.
|
|
846
|
-
* Turn on verbose in the host object, run your script with hashKey unset and check the very start of the text returned
|
|
847
|
-
for the servers hash value.
|
|
848
|
-
* The servers hash value can be saved to a variable outside the host or class so you can access it without having to
|
|
849
|
-
parse response text.
|
|
850
|
-
|
|
851
|
-
*Example:*
|
|
852
|
-
```javascript
|
|
853
|
-
//Define the hostValidation function in the host.server config.
|
|
854
|
-
//hashKey needs to be defined at the top level if you want to access the server hash at run time
|
|
855
|
-
var serverHash, host;
|
|
856
|
-
//don't set expectedHash if you want to know the server hash
|
|
857
|
-
var expectedHash
|
|
858
|
-
expectedHash = "85:19:8a:fb:60:4b:94:13:5c:ea:fe:3b:99:c7:a5:4e";
|
|
859
657
|
|
|
860
|
-
host
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
var recievedHash;
|
|
867
|
-
|
|
868
|
-
expectedHash = expectedHash + "".replace(/[:]/g, "").toLowerCase();
|
|
869
|
-
recievedHash = hashedKey + "".replace(/[:]/g, "").toLowerCase();
|
|
870
|
-
if (expectedHash === "") {
|
|
871
|
-
//No expected hash so save save what was received from the host (hashedKey)
|
|
872
|
-
//serverHash needs to be defined before host object
|
|
873
|
-
serverHash = hashedKey;
|
|
874
|
-
console.log("Server hash: " + serverHash);
|
|
875
|
-
return true;
|
|
876
|
-
} else if (recievedHash === expectedHash) {
|
|
877
|
-
console.log("Hash values matched");
|
|
878
|
-
return true;
|
|
879
|
-
}
|
|
880
|
-
//Output the failed comparison to the console if you want to see what went wrong
|
|
881
|
-
console.log("Hash values: Server = " + recievedHash + " <> Client = " + expectedHash);
|
|
882
|
-
return false;
|
|
883
|
-
},
|
|
884
|
-
},
|
|
885
|
-
//Other settings
|
|
886
|
-
};
|
|
887
|
-
|
|
888
|
-
var SSH2Shell = require ('ssh2shell'),
|
|
889
|
-
SSH = new SSH2Shell(host);
|
|
890
|
-
SSH.connect();
|
|
891
|
-
```
|
|
892
|
-
__*Note:*
|
|
893
|
-
host.server.hashMethod only supports md5 or sha1 according to the current SSH2 documentation anything else may produce
|
|
894
|
-
undesired results.__
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
Keyboard-interactive
|
|
898
|
-
----------------------
|
|
899
|
-
Keyboard-interactive authentication is available when both host.server.tryKeyboard is set to true and the event handler
|
|
900
|
-
keyboard-interactive is defined as below. The keyboard-interactive event handler can only be used on the first connection.
|
|
901
|
-
|
|
902
|
-
Also see [test/keyboard-interactivetest.js](https://github.com/cmp-202/ssh2shell/blob/master/test/keyboard-interactivetest.js) for the full example
|
|
658
|
+
Tunnelling nested host objects:
|
|
659
|
+
---------------------------------
|
|
660
|
+
`hosts: [ host1, host2]` setting can make multiple host connections possible.
|
|
661
|
+
Each host config object has its own server settings, commands, command handlers and
|
|
662
|
+
event handlers. Each host object also has its own hosts array that other host objects can be added to.
|
|
663
|
+
This provides for different host connection sequences to multiple depth of connections.
|
|
903
664
|
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
host.server.
|
|
665
|
+
**SSH connections:**
|
|
666
|
+
Once the primary host connection is made all other connections are made using an ssh command from the
|
|
667
|
+
current host to the next. A number of ssh command options are set using an optional `host.server.ssh` object.
|
|
668
|
+
`host.server.ssh.options` allows setting any ssh config options.
|
|
908
669
|
|
|
909
|
-
var SSH2Shell = require ('../lib/ssh2shell');
|
|
910
|
-
var SSH = new SSH2Shell(host);
|
|
911
|
-
|
|
912
|
-
//Add the keyboard-interactive handler
|
|
913
|
-
//The event function must call finish() with an array of responses in the same order as prompts received
|
|
914
|
-
// in the prompts array
|
|
915
|
-
SSH.on ('keyboard-interactive', function(name, instructions, instructionsLang, prompts, finish){
|
|
916
|
-
if (this.sshObj.debug) {this.emit('msg', this.sshObj.server.host + ": Keyboard-interactive");}
|
|
917
|
-
if (this.sshObj.verbose){
|
|
918
|
-
this.emit('msg', "name: " + name);
|
|
919
|
-
this.emit('msg', "instructions: " + instructions);
|
|
920
|
-
var str = JSON.stringify(prompts, null, 4);
|
|
921
|
-
this.emit('msg', "Prompts object: " + str);
|
|
922
|
-
}
|
|
923
|
-
//The example presumes only the password is required
|
|
924
|
-
finish([this.sshObj.server.password] );
|
|
925
|
-
});
|
|
926
|
-
|
|
927
|
-
SSH.connect();
|
|
928
670
|
```
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
671
|
+
var host = {
|
|
672
|
+
server: { ...,
|
|
673
|
+
ssh: {
|
|
674
|
+
forceProtocolVersion: true/false,
|
|
675
|
+
forceAddressType: true/false,
|
|
676
|
+
disablePseudoTTY: true/false,
|
|
677
|
+
forcePseudoTTY: true/false,
|
|
678
|
+
verbose: true/false,
|
|
679
|
+
cipherSpec: "",
|
|
680
|
+
escape: "",
|
|
681
|
+
logFile: "",
|
|
682
|
+
configFile: "",
|
|
683
|
+
identityFile: "",
|
|
684
|
+
loginName: "",
|
|
685
|
+
macSpec: "",
|
|
686
|
+
options: {}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
947
689
|
}
|
|
948
690
|
```
|
|
949
691
|
|
|
950
|
-
Sudo and su Commands:
|
|
951
|
-
--------------
|
|
952
|
-
It is possible to use `sudo [command]`, `sudo su`, `su [username]` and `sudo -u [username] -i`. Sudo commands uses the
|
|
953
|
-
password for the user that is accessing the server and is handled by SSH2shell. Su on the other hand uses the password
|
|
954
|
-
of root or the other user (`su seconduser`) and requires you detect the password prompt in onCommandProcessing.
|
|
955
692
|
|
|
956
|
-
|
|
957
|
-
|
|
693
|
+
**Tunnelling Example:**
|
|
694
|
+
This example shows two hosts (server2, server3) that are connected to via server1.
|
|
695
|
+
The two host configs are added to server1.hosts array.
|
|
958
696
|
|
|
959
|
-
|
|
697
|
+
```
|
|
698
|
+
server1.hosts = [server2, server3]
|
|
699
|
+
server2.hosts = []
|
|
700
|
+
server3.hosts = []
|
|
701
|
+
```
|
|
702
|
+
*The following would also be valid:*
|
|
703
|
+
```
|
|
704
|
+
server1.hosts = [server2]
|
|
705
|
+
server2.hosts = [server3]
|
|
706
|
+
server3.hosts = []
|
|
707
|
+
```
|
|
960
708
|
|
|
709
|
+
*The nested process:*
|
|
961
710
|
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
711
|
+
1. The primary host (server1) is connected and all its commands completed.
|
|
712
|
+
2. Server1.hosts array is checked for other hosts.
|
|
713
|
+
3. Server1 is stored for use later and server2's host object is loaded as the current host.
|
|
714
|
+
4. A connection to the next host is made using its server parameters via running the ssh command in the current session.
|
|
715
|
+
5. That hosts commands are completed and it's hosts array is checked for other hosts.
|
|
716
|
+
6. If no hosts are found the connection is closed triggering an end event for the current host if defined.
|
|
717
|
+
5. Server1 host object is reloaded as the current host object and server2 host object discarded.
|
|
718
|
+
6. Server1.hosts array is checked for other hosts and the next host popped off the array.
|
|
719
|
+
7. Server1's host object is restored and the process repeats for an all other hosts.
|
|
720
|
+
8. Server1 is loaded for the last time and all hosts sessionText's are appended to `this.callback(sessionText)`.
|
|
721
|
+
10. As all sessions are closed, the process ends.
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
**_Note:_**
|
|
725
|
+
* A host object needs to be defined before it is added to another host.hosts array.
|
|
726
|
+
* Only the primary host objects connected, ready and closed messages will be used by ssh2shell.
|
|
727
|
+
* Connection events only apply to the first host. Keyboard-interactive event handler is one of these.
|
|
965
728
|
|
|
966
|
-
1. `"msg:This is a message intended for monitoring the process as it runs"`. The `msg:` command raises a onMsg(message)
|
|
967
|
-
event.
|
|
968
|
-
* The text after `msg:` is passed to the message property of the onMsg event.
|
|
969
|
-
2. "\`SessionText notification\`" will take the text between "\` \`" and add it to the sessionText.
|
|
970
|
-
* The reason for not using echo or printf commands as a normal command is that you see both the command and the message
|
|
971
|
-
in the sessionText which is pointless when all you want is the message.
|
|
972
729
|
|
|
730
|
+
*How to:*
|
|
731
|
+
* Define nested hosts
|
|
732
|
+
* Use unique host connection settings for each host
|
|
733
|
+
* Defining different commands and command event handlers for each host
|
|
734
|
+
* Sharing duplicate functions between host objects
|
|
735
|
+
* What host object attributes you can leave out of primary and secondary host objects
|
|
736
|
+
* Unique event handlers set in host objects, common event handler set on class instance
|
|
973
737
|
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
The following properties have been added to the host object making it possible to override prompt string values used
|
|
977
|
-
with regular expressions to for prompt detection. Being able to change these values enables you to easily manage all
|
|
978
|
-
sorts of prompt options subject to you server prompts.
|
|
738
|
+
**_Note:_**
|
|
739
|
+
* Change debug to true to see the full process for each host.
|
|
979
740
|
|
|
980
|
-
These are optional settings.
|
|
981
|
-
```
|
|
982
|
-
host.standardPrompt = ">$%#";
|
|
983
|
-
host.passwordPrompt = ":";
|
|
984
|
-
host.passphrasePrompt = ":";
|
|
985
|
-
```
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
Text regular expression filters:
|
|
989
|
-
-------------------------------
|
|
990
|
-
There are two regular expression filters that remove unwanted text from response data.
|
|
991
|
-
|
|
992
|
-
The first removes non-standard ascii and the second removes ANSI text formatting codes. Both of these can be modified in
|
|
993
|
-
your host object to override defaults. It is also possible to output the ANSI codes by setting disableColorFilter to true.
|
|
994
|
-
|
|
995
|
-
These are optional settings
|
|
996
741
|
```javascript
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
host.textColorFilter = "(\[{1}[0-9;]+m{1})"
|
|
1000
|
-
```
|
|
742
|
+
var dotenv = require('dotenv');
|
|
743
|
+
dotenv.load();
|
|
1001
744
|
|
|
745
|
+
//Host connection and authentication parameters
|
|
746
|
+
var conParamsHost1 = {
|
|
747
|
+
host: process.env.SERVER1_HOST,
|
|
748
|
+
port: process.env.SERVER1_PORT,
|
|
749
|
+
userName: process.env.SERVER1_USER_NAME,
|
|
750
|
+
password: process.env.SERVER1_PASSWORD,
|
|
751
|
+
passPhrase: process.env.SERVER1_PASS_PHRASE,
|
|
752
|
+
privateKey: require('fs').readFileSync(process.env.SERVER1_PRIV_KEY_PATH)
|
|
753
|
+
},
|
|
754
|
+
conParamsHost2 = {
|
|
755
|
+
host: process.env.SERVER2_HOST,
|
|
756
|
+
port: process.env.SERVER2_PORT,
|
|
757
|
+
userName: process.env.SERVER2_USER_NAME,
|
|
758
|
+
password: process.env.SERVER2_PASSWORD
|
|
759
|
+
},
|
|
760
|
+
conParamsHost3 = {
|
|
761
|
+
host: process.env.SERVER3_HOST,
|
|
762
|
+
port: process.env.SERVER3_PORT,
|
|
763
|
+
userName: process.env.SERVER3_USER_NAME,
|
|
764
|
+
password: process.env.SERVER3_PASSWORD
|
|
765
|
+
}
|
|
1002
766
|
|
|
1003
|
-
Responding to non-standard command prompts:
|
|
1004
|
-
----------------------
|
|
1005
|
-
When running commands there are cases that you might need to respond to specific prompt that results from the command
|
|
1006
|
-
being run. The command response check method is the same as in the example for the host.onCommandComplete event handler
|
|
1007
|
-
but in this case we use it in the host.onCommandProcessing event handler. The stream object is available in
|
|
1008
|
-
onCommandProcessing to the prompt directly using strea.write("y\n"), note "\n" might be required to complete the
|
|
1009
|
-
response.
|
|
1010
767
|
|
|
1011
|
-
Host
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
768
|
+
//Host objects:
|
|
769
|
+
var host1 = {
|
|
770
|
+
server: conParamsHost1,
|
|
771
|
+
commands: [
|
|
772
|
+
"msg:connected to host: passed. Listing dir.",
|
|
773
|
+
"ls -l"
|
|
774
|
+
],
|
|
775
|
+
debug: false,
|
|
776
|
+
onCommandComplete: function( command, response, sshObj ) {
|
|
777
|
+
//we are listing the dir so output it to the msg handler
|
|
778
|
+
if(sshObj.debug){
|
|
779
|
+
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete host1, command: " + command);
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
onEnd: function( sessionText, sshObj ) {
|
|
783
|
+
//show the full session output for all hosts.
|
|
784
|
+
if(sshObj.debug){this.emit("msg", this.sshObj.server.host + ": primary host.onEnd all sessiontText");}
|
|
785
|
+
this.emit ("msg", "\nAll Hosts SessiontText ---------------------------------------\n");
|
|
786
|
+
this.emit ("msg", sshObj.server.host + ":\n" + sessionText);
|
|
787
|
+
this.emit ("msg", "\nEnd sessiontText ---------------------------------------------\n");
|
|
788
|
+
})
|
|
789
|
+
},
|
|
1024
790
|
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
791
|
+
host2 = {
|
|
792
|
+
server: conParamsHost2,
|
|
793
|
+
commands: [
|
|
794
|
+
"msg:connected to host: passed",
|
|
795
|
+
"msg:Changing to root dir",
|
|
796
|
+
"cd ~/",
|
|
797
|
+
"msg:Listing dir",
|
|
798
|
+
"ls -l"
|
|
799
|
+
],
|
|
800
|
+
debug: false,
|
|
801
|
+
connectedMessage: "Connected to host2",
|
|
802
|
+
onCommandComplete: function( command, response, sshObj ) {
|
|
803
|
+
//we are listing the dir so output it to the msg handler
|
|
804
|
+
if(sshObj.debug){
|
|
805
|
+
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete host2, command: " + command);
|
|
806
|
+
}
|
|
807
|
+
if (command.indexOf("cd") != -1){
|
|
808
|
+
this.emit("msg", this.sshObj.server.host + ": Just ran a cd command:\n");
|
|
809
|
+
this.emit("msg", response);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
},
|
|
1031
813
|
|
|
1032
|
-
|
|
814
|
+
host3 = {
|
|
815
|
+
server: conParamsHost3,
|
|
816
|
+
commands: [
|
|
817
|
+
"msg:connected to host: passed",
|
|
818
|
+
"hostname"
|
|
819
|
+
],
|
|
820
|
+
debug: false,
|
|
821
|
+
connectedMessage: "Connected to host3",
|
|
822
|
+
onCommandComplete: function( command, response, sshObj) {
|
|
823
|
+
//we are listing the dir so output it to the msg handler
|
|
824
|
+
if(sshObj.debug){
|
|
825
|
+
this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete host3, command: " + command);
|
|
826
|
+
}
|
|
827
|
+
if (command.indexOf("cd") != -1){
|
|
828
|
+
this.emit("msg", this.sshObj.server.host + ": Just ran hostname command:\n");
|
|
829
|
+
this.emit("msg", response);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
1033
833
|
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
//This debug message will only run when conditions are met not on every data event so is ok here
|
|
1037
|
-
if (sshObj.debug) {this.emit('msg', this.sshObj.server.host + ": Responding to nano install");}
|
|
1038
|
-
sshObj.firstRun = true
|
|
1039
|
-
stream.write('y\n');
|
|
1040
|
-
}
|
|
1041
|
-
};
|
|
1042
|
-
```
|
|
834
|
+
//Set the two hosts you are tunnelling to through host1
|
|
835
|
+
host1.hosts = [ host2, host3 ];
|
|
1043
836
|
|
|
1044
|
-
|
|
1045
|
-
|
|
837
|
+
//or the alternative nested tunnelling method outlined above:
|
|
838
|
+
//host2.hosts = [ host3 ];
|
|
839
|
+
//host1.hosts = [ host2 ];
|
|
1046
840
|
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
or get the script on the fly. You can echo/printf the script content into a file as a command, ensure it is executable,
|
|
1051
|
-
run it and then delete it. The other option is to curl or wget the script from a remote location but
|
|
1052
|
-
this has some risks associated with it. I like to know what is in the script I am running.
|
|
841
|
+
//Create the new instance
|
|
842
|
+
var SSH2Shell = require ('ssh2shell'),
|
|
843
|
+
SSH = new SSH2Shell(host1);
|
|
1053
844
|
|
|
1054
|
-
|
|
845
|
+
//Add a commandComplete handler used by all hosts
|
|
846
|
+
SSH.on ('commandComplete', function onCommandComplete( command, response, sshObj ) {
|
|
847
|
+
//we are listing the dir so output it to the msg handler
|
|
848
|
+
if (command == "ls -l"){
|
|
849
|
+
this.emit("msg", this.sshObj.server.host + ":\n" + response);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
//Add an on end event handler used by all hosts
|
|
854
|
+
SSH.on ('end', function( sessionText, sshObj ) {
|
|
855
|
+
//show the full session output. This could be emailed or saved to a log file.
|
|
856
|
+
this.emit ("msg", "\nSessiontText -------------------------------------------------\n");
|
|
857
|
+
this.emit ("msg", sshObj.server.host + ":\n" + sessionText);
|
|
858
|
+
this.emit ("msg", "\nEnd sessiontText ---------------------------------------------\n");
|
|
859
|
+
});
|
|
1055
860
|
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
" #\n" +
|
|
1060
|
-
" current=$(pwd);\n" +
|
|
1061
|
-
"cd ..;\n" +
|
|
1062
|
-
"if [ -f myfile ]; then" +
|
|
1063
|
-
"sed \"/^[ \\t]*$/d\" ${current}/myfile | while read line; do\n" +
|
|
1064
|
-
"printf \"Doing some stuff\";\n" +
|
|
1065
|
-
"printf $line;\n" +
|
|
1066
|
-
"done\n" +
|
|
1067
|
-
"fi\n' > myscript.sh;" +
|
|
1068
|
-
"fi",
|
|
1069
|
-
"sudo chmod 700 myscript.sh",
|
|
1070
|
-
"./myscript.sh",
|
|
1071
|
-
"rm myscript.sh"
|
|
1072
|
-
],
|
|
861
|
+
//Start the process
|
|
862
|
+
SSH.connect();
|
|
863
|
+
|
|
1073
864
|
```
|
|
1074
865
|
|
|
1075
866
|
|
|
@@ -1087,12 +878,12 @@ There are two ways to add event handlers:
|
|
|
1087
878
|
* Instance variables and functions are available through `this` including the Emitter functions like
|
|
1088
879
|
this.emit("myEvent", properties).
|
|
1089
880
|
* Connect, ready, error and close events are not available for definition in the host object.
|
|
1090
|
-
* Defining a host event replaces the default event handler.
|
|
881
|
+
* Defining a host event handler replaces the default coded event handler.
|
|
1091
882
|
|
|
1092
883
|
2. Add an event handler, as defined below, to the class instance.
|
|
1093
884
|
* Handlers added to the class instance will be triggered every time the event is raised in parallel with any other
|
|
1094
885
|
handlers of the same name.
|
|
1095
|
-
* It will not replace the internal event handler of the class
|
|
886
|
+
* It will not replace the internal event handler of the class set by the class default or host definition.
|
|
1096
887
|
|
|
1097
888
|
An event can be raised using `this.emit('eventName', parameters)`.
|
|
1098
889
|
|
|
@@ -1192,3 +983,31 @@ ssh2shell.on ("Unpipe", function onUnpipe(source){
|
|
|
1192
983
|
//Source is the read stream to remove from outputting data
|
|
1193
984
|
});
|
|
1194
985
|
```
|
|
986
|
+
|
|
987
|
+
Bash scripts on the fly:
|
|
988
|
+
------------------------
|
|
989
|
+
If the commands you need to run would be better suited to a bash script as part of the process it is possible to generate
|
|
990
|
+
or get the script on the fly. You can echo/printf the script content into a file as a command, ensure it is executable,
|
|
991
|
+
run it and then delete it. The other option is to curl or wget the script from a remote location but
|
|
992
|
+
this has some risks associated with it. I like to know what is in the script I am running.
|
|
993
|
+
|
|
994
|
+
**Note** # and > in the following commands with conflict with the host.standardPrompt definition ">$%#" change it to "$%"
|
|
995
|
+
|
|
996
|
+
```
|
|
997
|
+
host.commands = [ "some commands here",
|
|
998
|
+
"if [ ! -f myscript.sh ]; then printf '#!/bin/bash\n" +
|
|
999
|
+
" #\n" +
|
|
1000
|
+
" current=$(pwd);\n" +
|
|
1001
|
+
"cd ..;\n" +
|
|
1002
|
+
"if [ -f myfile ]; then" +
|
|
1003
|
+
"sed \"/^[ \\t]*$/d\" ${current}/myfile | while read line; do\n" +
|
|
1004
|
+
"printf \"Doing some stuff\";\n" +
|
|
1005
|
+
"printf $line;\n" +
|
|
1006
|
+
"done\n" +
|
|
1007
|
+
"fi\n' > myscript.sh;" +
|
|
1008
|
+
"fi",
|
|
1009
|
+
"sudo chmod 700 myscript.sh",
|
|
1010
|
+
"./myscript.sh",
|
|
1011
|
+
"rm myscript.sh"
|
|
1012
|
+
],
|
|
1013
|
+
```
|