SSHThread.java
8.59 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
package com.sitech.util.upload;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SSHThread extends Thread implements RomoteController {
private Logger logger = Logger.getLogger(SSHThread.class);
private String host;
private int port;
private String user;
private String password;
private boolean autorized = false;
private String keywords = null;
// 存放命令执行结果
private StringBuffer result = new StringBuffer();
private Session session;
private Channel channel;
private String error;
public SSHThread(String host, int port, String user, String password) {
this.host = host;
this.port = port;
this.user = user;
this.password = password;
}
/**
* 初始化SSH连接
*/
public void initial() {
JSch jsch = new JSch();
try {
session = jsch.getSession(user, host, port);
session.setPassword(this.password);
session.setConfig("StrictHostKeyChecking", "no");
// 超时时间
session.connect(30000);
this.autorized = true;
} catch (Exception e) {
error = e.getMessage();
this.autorized = false;
logger.error("Create ssh session Failed!! " + "ip=" + this.host
+ ", username=" + this.user, e);
}
}
public void run() {
super.run();
}
/**
* 关闭连接
*/
public void close() {
try {
if (channel != null && channel.isConnected()) {
try {
channel.disconnect();
} catch (Exception e) {
logger.error("Exception while close ssh channel", e);
}
}
if (session != null && session.isConnected()) {
try {
session.disconnect();
} catch (Exception e) {
logger.error("Exception while close ssh session", e);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 执行命令
*/
public void doCommand(String command) {
if (!this.isAuthorized()) {
return;
}
try {
this.result = new StringBuffer();
channel = session.openChannel("exec");
if (command != null && !command.endsWith("\n")) {
command = command + "\n";
}
((ChannelExec) channel).setCommand(command);
channel.connect();
} catch (JSchException e1) {
this.autorized = false;
logger.error("SSH session is down!! " + "ip=" + this.host
+ ", username=" + this.user, e1);
} catch (Exception e) {
logger.error("Exception while do command:" + command, e);
}
}
public String getResult() {
InputStream is = null;
InputStream extIs = null;
byte[] tmp = new byte[1024];
long timeout = 30000;
long wait = 0;
try {
if (!this.isAuthorized()) {
return "";
}
is = channel.getInputStream();
extIs = channel.getExtInputStream();
while (is != null && timeout > wait) {
while (is.available() > 0) {
int i = is.read(tmp, 0, 1024);
if (i <= 0)
break;
this.result.append(new String(tmp, 0, i));
}
while (extIs.available() > 0) {
int i = extIs.read(tmp, 0, 1024);
if (i <= 0)
break;
this.result.append(new String(tmp, 0, i));
}
if (channel.isClosed() || channel.isEOF()) {
logger.info("channel.isClosed(): " + channel.isClosed());
logger.info("channel.isEOF(): " + channel.isEOF());
logger.info("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
wait += 1000;
logger.info("wait 1000");
} catch (Exception ee) {
ee.printStackTrace();
}
}// end while
} catch (Exception e) {
logger.error("Exception while getResult()", e);
this.result = new StringBuffer();
} finally {
try {
if (is != null) {
is.close();
}
if (extIs != null) {
extIs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return this.result.toString();
}
public boolean isAuthorized() {
return this.autorized;
}
public boolean isExistDir(String dir) {
boolean success = true;
this.doCommand("cd " + dir + "\n");
try {
InputStream in = channel.getInputStream();
int nextChar;
while (true) {
while ((nextChar = in.read()) != -1) {
result.append((char) nextChar);
}
if (channel.isClosed()) {
if (channel.getExitStatus() != 0) {
success = false;
}
in.close();
break;
}
try {
Thread.sleep(500);
} catch (Exception ee) {
ee.printStackTrace();
}
}
} catch (Exception e) {
this.result = new StringBuffer();
e.printStackTrace();
}
return success;
}
public boolean isRunning(String keywords, String username) {
this.keywords = keywords;
String command = "ps -ef | grep " + this.keywords;
if (username != null && !"".equals(username)) {
command += " | grep " + username;
}
command = command + " | grep -v grep";
this.doCommand(command);
String result = this.getResult();
if (result != null && result.indexOf(this.keywords) != -1) {
return true;
} else {
return false;
}
}
public boolean isRunning(String keywords) {
this.keywords = keywords;
this.doCommand("ps -ef | grep " + this.keywords);
String result = this.getResult();
result = result.replaceAll("grep " + this.keywords, " ");
if (result != null && result.indexOf(this.keywords) != -1) {
return true;
} else {
return false;
}
}
public boolean isUsed(int port) {
this.doCommand("netstat -an | grep -v TIME_WAIT | awk '{print $4}' | grep "
+ port + "");
String result = this.getResult();
if (result != null && result.indexOf("" + port) >= 0) {
return true;
}
return false;
}
public String getResultAsStr(String cmd) {
doCommand(cmd);
return getResult();
}
public Vector<String> getResultAsVector(String command) {
Vector<String> vResult = new Vector<String>();
try {
this.doCommand(command);
String strResult = this.getResult();
if (strResult != null) {
String[] results = strResult.split("\n");
for (String line : results) {
if (line.indexOf("have mail in") >= 0) {
continue;
}
vResult.add(line);
}
}
} catch (Exception e) {
logger.error("Exception while do command:" + command, e);
}
String logInfo = "-- do command: " + command + "\n";
for (String line : vResult) {
logInfo += line + "\n";
}
logger.info(logInfo);
return vResult;
}
public int childCountOfDir(String dir) {
int count = 0;
try {
if (this.isExistDir(dir)) {
this.doCommand("cd " + dir + ";ls -l | wc -l");
String result = this.getResult();
count = Integer.valueOf(result.trim()).intValue() - 1;
} else {
count = -1;
}
} catch (Exception e) {
e.printStackTrace();
count = -1;
}
return count;
}
public boolean createDir(String dir) {
boolean isExist = false;
if (dir != null && !dir.trim().equals("") && this.isExistDir(dir)) {
isExist = true;
}
// 逐层分析目录,如果没有则创建.
if (dir != null && !dir.trim().equals("") && !this.isExistDir(dir)) {
String[] split_dir = dir.split("/");
for (int i = 0; i < split_dir.length; i++) {
String path = "";
for (int j = 0; j <= i; j++) {
if (split_dir[j] != null && !split_dir[j].equals("")) {
path += "/" + split_dir[j];
}
}
if (path != null && !path.equals("")) {
if (!this.isExistDir(path)) {
this.doCommand("mkdir " + path);
this.getResult();
System.out.println("creat path=" + path);
}
if (!this.isExistDir(path)) {
System.out.println("cat not creat path=" + path);
return false;
}
}
}
if (this.isExistDir(dir)) {
isExist = true;
}
}
return isExist;
}
public String executeCommand(String command) throws Exception {
return "";
}
public String executeCommand(List<String> commandList) throws Exception {
return "";
}
public RomoteController cloneObject() {
return null;
}
public String getIpAddr() {
return this.host;
}
public String getError() {
return error;
}
public static void main(String[] args) {
SSHThread tt = new SSHThread("172.21.0.31", 22, "bnms", "bnms1");
tt.initial();
// ss.doCommand("cd /bnmsapp2/lianlian/masteragent/bin/; ksh startagent.sh");
// String startAgentMsg = ss.getResult();
// tt.doCommand("ls");
// System.out.println(tt.getResult());
// System.out.println(tt.isAuthorized());
tt.close();
}
}