1 package org
.argeo
.slc
.jsch
;
3 import java
.io
.BufferedReader
;
4 import java
.io
.InputStream
;
5 import java
.io
.InputStreamReader
;
6 import java
.util
.ArrayList
;
9 import org
.apache
.commons
.io
.IOUtils
;
10 import org
.apache
.commons
.logging
.Log
;
11 import org
.apache
.commons
.logging
.LogFactory
;
12 import org
.argeo
.slc
.SlcException
;
14 import com
.jcraft
.jsch
.Channel
;
15 import com
.jcraft
.jsch
.ChannelExec
;
16 import com
.jcraft
.jsch
.Session
;
18 public class RemoteExec
extends AbstractJschTask
{
19 private final static Log log
= LogFactory
.getLog(RemoteExec
.class);
21 private Boolean failOnBadExitStatus
= true;
23 private List
<String
> commands
= new ArrayList
<String
>();
24 private String command
;
26 public void run(Session session
) {
27 if (command
!= null) {
28 if (commands
.size() != 0)
29 throw new SlcException(
30 "Specify either a single command or a list of commands.");
31 remoteExec(session
, command
);
33 if (commands
.size() == 0)
34 throw new SlcException(
35 "Neither a single command or a list of commands has been specified.");
37 for (String cmd
: commands
) {
38 remoteExec(session
, cmd
);
43 protected void remoteExec(Session session
, String command
) {
44 BufferedReader execIn
= null;
46 Channel channel
= session
.openChannel("exec");
47 ((ChannelExec
) channel
).setCommand(command
);
50 // channel.setXForwarding(true);
52 // channel.setInputStream(System.in);
53 channel
.setInputStream(null);
55 ((ChannelExec
) channel
).setErrStream(System
.err
);
57 InputStream in
= channel
.getInputStream();
59 if (log
.isDebugEnabled())
60 log
.debug("Run '" + command
+ "' on " + getSshTarget() + "...");
64 // byte[] tmp = new byte[1024];
66 execIn
= new BufferedReader(new InputStreamReader(in
));
68 while ((line
= execIn
.readLine()) != null) {
69 if (!line
.trim().equals(""))
73 if (channel
.isClosed()) {
74 int exitStatus
= channel
.getExitStatus();
75 if (exitStatus
== 0) {
76 if (log
.isTraceEnabled())
77 log
.trace("Remote execution exit status: "
80 String msg
= "Remote execution failed with "
81 + " exit status: " + exitStatus
;
82 if (failOnBadExitStatus
)
83 throw new SlcException(msg
);
92 } catch (Exception ee
) {
96 } catch (Exception e
) {
97 throw new SlcException("Cannot execute remotely '" + command
98 + "' on " + getSshTarget(), e
);
100 IOUtils
.closeQuietly(execIn
);
104 public void setCommand(String command
) {
105 this.command
= command
;
108 public void setCommands(List
<String
> commands
) {
109 this.commands
= commands
;
112 public void setFailOnBadExitStatus(Boolean failOnBadExitStatus
) {
113 this.failOnBadExitStatus
= failOnBadExitStatus
;