1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.argeo.slc.jsch;
17
18 import java.io.BufferedReader;
19 import java.io.BufferedWriter;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.io.OutputStreamWriter;
23
24 import org.apache.commons.io.IOUtils;
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.argeo.slc.SlcException;
28 import org.springframework.core.io.Resource;
29 import org.springframework.util.StringUtils;
30
31 import com.jcraft.jsch.Channel;
32 import com.jcraft.jsch.Session;
33
34 public class SshShell extends AbstractJschTask {
35 private final static Log log = LogFactory.getLog(SshShell.class);
36 private Resource input;
37
38 @Override
39 void run(Session session) {
40 try {
41 final Channel channel = session.openChannel("shell");
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 final BufferedWriter writer = new BufferedWriter(
69 new OutputStreamWriter(channel.getOutputStream()));
70
71
72 channel.connect(3 * 1000);
73
74
75
76
77
78
79
80
81 Thread writerThread = new Thread("Shell writer " + getSshTarget()) {
82
83 @Override
84 public void run() {
85
86 if (log.isDebugEnabled())
87 log.debug("Start writing to shell");
88
89 BufferedReader reader = null;
90 try {
91 reader = new BufferedReader(new InputStreamReader(input
92 .getInputStream()));
93 String line = null;
94 while ((line = reader.readLine()) != null) {
95 if (!StringUtils.hasText(line))
96 continue;
97 writer.write(line);
98 writer.newLine();
99 }
100 writer.append("exit");
101 writer.newLine();
102 writer.flush();
103
104 } catch (IOException e) {
105 throw new SlcException("Cannot write to shell on "
106 + getSshTarget(), e);
107 } finally {
108 IOUtils.closeQuietly(reader);
109 }
110 }
111 };
112 writerThread.start();
113
114 BufferedReader execIn = null;
115 try {
116 execIn = new BufferedReader(new InputStreamReader(channel
117 .getInputStream()));
118 String line = null;
119 while ((line = execIn.readLine()) != null) {
120 if (!line.trim().equals(""))
121 log.info(line);
122 }
123 } catch (Exception e) {
124 throw new SlcException("Cannot read from shell on "
125 + getSshTarget(), e);
126 } finally {
127 IOUtils.closeQuietly(execIn);
128 }
129
130 } catch (Exception e) {
131 throw new SlcException("Cannot use SSH shell on " + getSshTarget(),
132 e);
133 }
134 }
135
136 public void setInput(Resource input) {
137 this.input = input;
138 }
139
140 }