forked from pquiring/javaforce
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellProcess.java
More file actions
executable file
·376 lines (339 loc) · 9.08 KB
/
Copy pathShellProcess.java
File metadata and controls
executable file
·376 lines (339 loc) · 9.08 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/**
* Provides services to run shell processes with input/output and sudo password
* authentication.
*
* Created : Feb 18, 2012
*
* Note : The responses will not work if the process spawns a child process that
* expects input.
*
*/
package javaforce;
import java.lang.reflect.*;
import java.util.*;
import java.io.*;
public class ShellProcess {
private Process p;
private InputStream is, es;
private OutputStream os;
private StringBuffer output;
private boolean active;
private ArrayList<Response> script = new ArrayList<Response>();
private ArrayList<Variable> envAdd = new ArrayList<Variable>();
private ArrayList<Variable> envRemove = new ArrayList<Variable>();
private ShellProcessListener listener = null;
private File path;
private int errorLevel;
private boolean keepOutput = true;
public static boolean log = false;
public static boolean logPrompt = false;
public String command;
private static class Response {
public String prompt;
public String reply;
public boolean repeat, used, regex, term;
};
private static class Variable {
public Variable(String name, String value) {
this.name = name;
this.value = value;
}
public String name, value;
}
/**
* Registers a response to a prompt. If repeat is true the response can be
* used many times.
*/
public void addResponse(String prompt, String reply, boolean repeat) {
Response res = new Response();
res.prompt = prompt.trim();
res.reply = reply;
res.repeat = repeat;
res.regex = false;
res.term = false;
script.add(res);
}
/**
* Terminates the program if prompt is detected.
*/
public void addTerminate(String prompt) {
Response res = new Response();
res.prompt = prompt.trim();
res.reply = "";
res.repeat = false;
res.regex = false;
res.term = true;
script.add(res);
}
/**
* Registers a response to a prompt in the form of a regex. If repeat is true
* the response can be used many times.
*/
public void addRegexResponse(String prompt_regex, String reply, boolean repeat) {
Response res = new Response();
res.prompt = prompt_regex.trim();
res.reply = reply;
res.repeat = repeat;
res.regex = true;
res.term = false;
script.add(res);
}
/**
* Terminates the program if prompt_regex is detected.
*/
public void addRegexTerminate(String prompt_regex) {
Response res = new Response();
res.prompt = prompt_regex.trim();
res.reply = "";
res.repeat = false;
res.regex = true;
res.term = true;
script.add(res);
}
/**
* The listener will receive all output.
*/
public void addListener(ShellProcessListener listener) {
this.listener = listener;
}
public ShellProcessListener getListener() {
return listener;
}
public void addEnvironmentVariable(String name, String value) {
envAdd.add(new Variable(name, value));
}
public void removeEnvironmentVariable(String name) {
envRemove.add(new Variable(name, null));
}
/**
* Sets init working folder.
*/
public void setFolder(File path) {
this.path = path;
}
/**
* Discards all output. Note that responses are disabled when this is enabled.
* This is intended for long processes that are monitored with a
* ShellProcessListener
*/
public void keepOutput(boolean state) {
keepOutput = state;
}
/**
* See run(String cmd[], boolean redirStderr)
*/
public String run(List<String> cmd, boolean redirStderr) {
return run(cmd.toArray(new String[0]), redirStderr);
}
/**
* Runs a process, sending responses to stdin and returning all stdout. The
* responses should cause the process to terminate.
* If cmd[0] is 'sudo' then jsudo-ask is used if a password is required to run the command.
* If redirStderr is true then stderr will be redir to stdout.
*/
public String run(String cmd[], boolean redirStderr) {
if (cmd[0].equals("sudo")) {
//if running sudo add -A option to use jsudo-ask to request password
String newcmd[] = new String[cmd.length + 1];
newcmd[0] = "sudo";
newcmd[1] = "-A";
System.arraycopy(cmd, 1, newcmd, 2, cmd.length - 1);
cmd = newcmd;
}
ProcessBuilder pb = new ProcessBuilder(cmd);
if (redirStderr) {
pb.redirectErrorStream(true);
}
if (path != null) {
pb.directory(path);
}
Map<String, String> env = pb.environment();
if (cmd[0].equals("sudo")) {
env.put("SUDO_ASKPASS", "/usr/bin/jsudo-ask");
}
for (int a = 0; a < envAdd.size(); a++) {
Variable v = envAdd.get(a);
env.put(v.name, v.value);
}
for (int a = 0; a < envRemove.size(); a++) {
Variable v = envRemove.get(a);
env.remove(v.name);
}
command = "";
for (int a = 0; a < cmd.length; a++) {
command += cmd[a] + " "; //test
}
output = new StringBuffer();
active = true;
if (log) {
String msg = "Exec :";
for (int a = 0; a < cmd.length; a++) {
msg += " ";
msg += cmd[a];
}
JFLog.log(msg);
}
try {
//start the process
p = pb.start();
is = p.getInputStream();
os = p.getOutputStream();
es = p.getErrorStream();
//start worker thread
Worker wi = new Worker(is, true);
wi.start();
Worker we = null;
if (!redirStderr) {
we = new Worker(es, false);
we.start();
}
//wait for process to terminate
p.waitFor();
active = false;
//wait for worker threads to exit
wi.join();
if (!redirStderr) {
we.join();
}
} catch (Exception e) {
JFLog.log(e);
errorLevel = -1;
return null;
}
if (log) {
JFLog.log("Exec:Complete");
}
errorLevel = p.exitValue();
return output.toString();
}
/**
* Forcefully terminates the process.
*/
public void destroy() {
if (p != null) {
p.destroy();
}
}
private void _destroy() {
destroy();
}
/**
* Returns error level from last process run.
*/
public int getErrorLevel() {
return errorLevel;
}
private class Worker extends Thread {
private InputStream wis;
private boolean processScript;
public Worker(InputStream wis, boolean processScript) {
this.processScript = processScript;
this.wis = wis;
}
public void run() {
byte buf[] = new byte[1024];
int read;
String str;
String prompt;
int in, ir;
Response res;
int pidx = 0;
try {
while ((active) || (wis.available() > 0)) { //InputStream may have more data after process is inactive!!!
read = wis.read(buf);
if (read == -1) {
break;
}
if (read == 0) {
continue;
}
str = new String(buf, 0, read);
if (log) {
JFLog.log(str);
}
if (listener != null) {
try {
listener.shellProcessOutput(str);
} catch (Exception e1) {
}
}
if (!keepOutput) {
continue;
}
if (!processScript) {
continue;
}
output.append(str);
//check for possible response
prompt = output.substring(pidx).trim();
if (prompt.length() == 0) {
continue;
}
in = prompt.lastIndexOf("\n");
ir = prompt.lastIndexOf("\r");
if ((in != -1) && (in > ir)) {
prompt = prompt.substring(in + 1).trim();
}
if ((ir != -1) && (ir > in)) {
prompt = prompt.substring(ir + 1).trim();
}
if (logPrompt) {
JFLog.log("prompt=" + prompt);
}
for (int a = 0; a < script.size(); a++) {
res = script.get(a);
if (res.used) {
continue;
}
boolean matches = false;
if (res.regex) {
matches = prompt.matches(res.prompt);
} else {
matches = prompt.equals(res.prompt);
}
if (matches) {
pidx = output.length(); //avoid reusing a part of this prompt
if (res.term) {
_destroy();
return;
}
if (log) {
JFLog.log(res.reply);
}
os.write(res.reply.getBytes());
os.flush();
if (!res.repeat) {
res.used = true;
}
break;
}
}
}
} catch (Exception e) {
// if (log) JFLog.log(e);
}
if (log) {
JFLog.log("ShellProcess:Worker thread exiting");
}
}
}
public OutputStream getOutputStream() {
return os;
}
/** Returns pid on Unix systems. */
public int getpid() {
if (JF.isWindows()) return -1;
try {
Class cls = p.getClass();
Field f = cls.getField("pid");
return f.getInt(p);
} catch (Exception e) {
JFLog.log(e);
return -1;
}
}
public boolean isAlive() {
if (p == null) return false;
return p.isAlive();
}
}