I am trying to connect a linux
machine and executing my shell script named as "myscript.sh
". While running it, I am getting cast exception while same is working fine in Java.
I am getting below error:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class com.jcraft.jsch.ChannelExec' with class 'java.lang.Class' to class 'com.jcraft.jsch.ChannelExec' error at line: 29
Below is the code snippet:
`import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
JSch jsch = new JSch();
Session session;
try {
// Open a Session to remote SSH server and Connect.
// Set User and IP of the remote host and SSH port.
session = jsch.getSession("user", "host", 22);
// When we do SSH to a remote host for the 1st time or if key at the remote host
// changes, we will be prompted to confirm the authenticity of remote host.
// This check feature is controlled by StrictHostKeyChecking ssh parameter.
// By default StrictHostKeyChecking is set to yes as a security measure.
session.setConfig("StrictHostKeyChecking", "no");
//Set password
session.setPassword("Pwd");
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect();
// create the execution channel over the session
ChannelExec channelExec = (ChannelExec)
session.openChannel("exec");
// Set the command to execute on the channel and ex ecute the command
channelExec.setCommand("sh myscript.sh");
channelExec.connect();
// Get an InputStream from this channel and read messages, generated
// by the executing command, from the remote side.
InputStream ab = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ab));
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
// Command execution completed here.
// Retrieve the exit status of the executed command
int exitStatus = channelExec.getExitStatus();
if (exitStatus > 0) {
log.info("Remote script exec error! " + exitStatus);
}
//Disconnect the Session
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}`
The problem is here
ChannelExec channelExec = (ChannelExec)
session.openChannel("exec");
The newline tells the groovy parser that those are two statements. This is equivalent to the following Java code:
ChannelExec channelExec = (ChannelExec.class);
session.openChannel("exec");
Note that the name of a class (here ChannelExec
) becomes a Class-Literal in Groovy, whereas in Java you need to add .class
, e.g. ChannelExec.class
What you want is this:
ChannelExec channelExec = (ChannelExec) session.openChannel("exec")