【发布时间】:2018-04-09 02:37:12
【问题描述】:
我正在尝试使用 Jsch 在远程服务器上执行 .csh 脚本。我能够执行诸如 cp、mv 和 ls 之类的命令。但是当我尝试执行一个在内部引用一些环境变量的脚本时,该脚本以状态 1 退出。在 script.sh 中引用了一个 INTERNAL_ENV_VARIABLE,当我使用 exec 运行时无法访问它。有什么方法可以让我从 exec 运行 .csh 脚本来处理这种依赖关系吗?
使用 shell 代替 exec 不是一种选择,因为当我们打开 shell 时有多个身份验证级别,并且会使我们正在开发的测试框架依赖于多个凭据。
我调用的命令导航到脚本目录并执行脚本。
util.executeCommand(session,"cd " + script directory+";"+"./script.csh");
控制台输出
com.jcraft.jsch.Channel$MyPipedInputStream@4bff64c2
INTERNAL_ENV_VARIABLE: Undefined variable.
exit-status: 1
执行命令的方法:executeCommand
public int executeCommand(Session session, String script) throws JSchException, IOException {
System.out.println("Execute Script " + script);
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
((ChannelExec)channelExec).setPty(true);
InputStream in = channelExec.getInputStream();
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.setCommand(script);
channelExec.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
System.out.println(channelExec.getErrStream());
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channelExec.isClosed()) {
System.out.println("exit-status: " + channelExec.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channelExec.disconnect();
return channelExec.getExitStatus();
}
创建会话的方法:createSession
public Session createSession(String user, String host, int Port, String Password) throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, Port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(Password);
session.connect(5000);
System.out.println(session.isConnected());
return session;
}
}
【问题讨论】: