-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathSSH.java
More file actions
350 lines (327 loc) · 9.85 KB
/
Copy pathSSH.java
File metadata and controls
350 lines (327 loc) · 9.85 KB
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
package javaforce;
import java.io.*;
import java.util.*;
import java.security.*;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.PtyCapableChannelSession;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;
/** SSH Client.
*
* @author peterq.admin
*/
public class SSH {
/** SSH Connection options. */
public static class Options {
public int type;
public String username;
public String password;
public KeyMgmt keys;
public String keyalias;
public String keypass;
public String command; //if type == EXEC
}
public static final int TYPE_SHELL = 0;
public static final int TYPE_EXEC = 1;
public static final int TYPE_SUBSYSTEM = 2;
public static boolean debug = false;
private SshClient client;
private ClientSession session;
private ClientChannel channel;
private PtyCapableChannelSession pty;
private InputStream in;
private OutputStream out;
private Object[] pipes;
public boolean connect(String host, int port, Options options) {
if (!debug) {
JFLog.setEnabled(JFLog.TRACE, false); //very verbose
JFLog.setEnabled(JFLog.DEBUG, false); //very verbose
JFLog.setEnabled(JFLog.INFO, false); //very verbose
JFLog.setEnabled(JFLog.WARN, false); //very verbose
}
try {
client = SshClient.setUpDefaultClient();
client.start();
ConnectFuture cf = client.connect(options.username, host, port);
session = cf.verify().getSession();
if (options.password != null) {
session.addPasswordIdentity(options.password);
} else {
session.addPublicKeyIdentity((KeyPair)options.keys.getKeyPair(options.keyalias, options.keypass));
}
session.auth().verify(30000);
switch (options.type) {
case TYPE_SHELL:
channel = pty = (ChannelShell)session.createShellChannel();
//https://github.com/apache/mina-sshd/blob/master/docs/port-forwarding.md
if (false) {
// Enable X11 forwarding
//session.createRemotePortForwardingTracker(SshdSocketAddress.LOCALHOST_ADDRESS, SshdSocketAddress.LOCALHOST_ADDRESS);
JFLog.log("TODO : enable x11 forwarding");
}
if (false) {
// Enable agent-forwarding
//session.createRemotePortForwardingTracker(SshdSocketAddress.LOCALHOST_ADDRESS, SshdSocketAddress.LOCALHOST_ADDRESS);
JFLog.log("TODO : enable agent forwarding");
}
break;
case TYPE_EXEC:
channel = pty = (ChannelExec)session.createExecChannel(options.command);
break;
case TYPE_SUBSYSTEM:
break;
}
pipes = createPipes();
if (pipes == null) return false;
out = (OutputStream)pipes[1];
channel.setIn((InputStream)pipes[0]);
pipes = createPipes();
if (pipes == null) return false;
in = (InputStream)pipes[0];
channel.setOut((OutputStream)pipes[1]);
channel.open();
return true;
} catch (Exception e) {
JFLog.log(e);
return false;
}
}
public void disconnect() {
try {if (channel != null) {channel.close(); channel = null;}} catch(Exception e) {}
try {if (session != null) {session.close(); session = null;}} catch(Exception e) {}
try {if (client != null) {client.close(); client = null;}} catch(Exception e) {}
try {if (out != null) {out.close(); out = null;}} catch(Exception e) {}
try {if (in != null) {in.close(); in = null;}} catch(Exception e) {}
}
public boolean isConnected() {
return client.isOpen();
}
public OutputStream getOutputStream() {
return out;
}
public InputStream getInputStream() {
return in;
}
public void setSize(int cols, int rows) {
try {
pty.sendWindowChange(cols, rows);
} catch (Exception e) {
JFLog.log(e);
}
}
/** Get output from exec command. */
public String getOutput() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Condition connected = () -> {return isConnected();};
RelayStream rs2 = new RelayStream(getInputStream(), baos, connected);
rs2.start();
try {
rs2.join();
} catch (Exception e) {
//JFLog.log(e);
}
return new String(baos.toByteArray());
}
/** Execute commands and return output.
* Commands should cause connection to terminate or function will return after timeout.
* Timeout = 1 min
* @param cmds = commands to execute
*/
public String script(String[] cmds) {
return script(cmds, 60 * 1000);
}
/** Execute commands and return output.
* Commands should cause connection to terminate or function will return after timeout.
* @param cmds = commands to execute
* @param timeout = timeout in ms (0 = disable)
*/
public String script(String[] cmds, int timeout) {
InputStream is = getInputStream();
OutputStream os = getOutputStream();
Timer timer = null;
if (timeout > 0) {
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
if (client != null) {
disconnect();
}
}
}, timeout);
}
try {
for(String cmd : cmds) {
if (debug) JFLog.log(cmd);
os.write(cmd.getBytes());
os.write("\r\n".getBytes());
}
StringBuilder sb = new StringBuilder();
byte[] data = new byte[1024];
while (isConnected()) {
int read = is.read(data);
if (debug) JFLog.log("read=" + read);
if (read == -1) break;
if (read > 0) {
sb.append(new String(data, 0, read));
}
}
while (is.available() > 0) {
int read = is.read(data);
if (debug) JFLog.log("read=" + read);
if (read == -1) break;
if (read > 0) {
sb.append(new String(data, 0, read));
}
}
disconnect();
if (timer != null) {
timer.cancel();
}
return sb.toString();
} catch (Exception e) {
JFLog.log(e);
}
if (timer != null) {
timer.cancel();
}
return null;
}
private Object[] createPipes() {
Object[] ret = new Object[2];
try {
ret[0] = new PipedInputStream();
ret[1] = new PipedOutputStream((PipedInputStream)ret[0]);
return ret;
} catch (Exception e) {
return null;
}
}
public static void usage() {
System.out.println("jfssh [user@]host[:port] [-p port]");
System.exit(1);
}
public static void error(String msg) {
System.out.println("Error:" + msg);
System.exit(2);
}
private static void output(String file, String output) {
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(output.getBytes());
fos.close();
} catch (Exception e) {
JFLog.log(e);
}
}
/** SSH cli client */
public static void main(String[] args) {
String dest = null;
int port = 22;
String outfile = null;
ArrayList<String> cmd = new ArrayList<>();
String argtype = null;
boolean script = false;
for(String arg : args) {
if (argtype != null) {
switch (argtype) {
case "-p": port = Integer.valueOf(arg); break;
case "-o": outfile = arg; break;
}
argtype = null;
continue;
}
if (arg.startsWith("-")) {
switch (arg) {
case "-p": argtype = arg; break;
case "-o": argtype = arg; break;
case "-s": script = true; break;
case "-debug": debug = true; break;
default: usage();
}
} else {
if (dest == null) {
dest = arg;
} else {
cmd.add(arg);
}
}
}
if (dest == null) usage();
String user = null;
String host = null;
int idx = dest.indexOf('@');
if (idx == -1) {
host = dest;
} else {
user = dest.substring(0, idx);
host = dest.substring(idx + 1);
}
idx = host.indexOf(':');
if (idx != -1) {
port = Integer.valueOf(host.substring(idx + 1));
host = host.substring(0, idx);
}
System.out.print("Enter Password:");
String pass = new String(System.console().readPassword());
SSH ssh = new SSH();
Options opts = new Options();
opts.username = user;
opts.password = pass;
if (cmd.size() > 0 && !script) {
StringBuilder command = new StringBuilder();
for(String str : cmd) {
if (command.length() > 0) {
command.append(" ");
}
command.append(str);
}
opts.command = command.toString();
opts.type = TYPE_EXEC;
}
if (!ssh.connect(host, port, opts)) {
error("Connection failed");
}
//connect input/output relay agents
Condition connected = () -> {
boolean conn = ssh.isConnected();
if (debug) JFLog.log("isConnected=" + conn);
return conn;
};
if (debug) {
RelayStream.debug = true;
}
switch (opts.type) {
case TYPE_SHELL:
if (script) {
String output = ssh.script(cmd.toArray(JF.StringArrayType));
System.out.println(output);
if (outfile != null) {
output(outfile, output);
}
} else {
RelayStream rs1 = new RelayStream(Console.getInputStream(), ssh.getOutputStream(), connected);
RelayStream rs2 = new RelayStream(ssh.getInputStream(), Console.getOutputStream(), connected);
rs1.start();
rs2.start();
try {
rs1.join();
rs2.join();
} catch (Exception e) {
//JFLog.log(e);
}
}
break;
case TYPE_EXEC:
String output = ssh.getOutput();
if (outfile != null) {
output(outfile, output);
}
System.out.print(output);
break;
}
ssh.disconnect();
}
}