我正在尝试使用 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;
}
}
util.executeCommand(session,"cd " + script directory);
util.executeCommand(session,"ls "+"script.csh"+" && exit 0 || exit 1" );
util.executeCommand(session,"./script.csh");
这些命令调用中的每一个都将独立于其他命令运行。值得注意的是,每个命令都将从相同的工作目录开始——可能是您用来登录的任何用户的主目录——并且cd
您首先调用的命令不会对您运行的其他命令产生任何影响。
如果要将一系列命令串在一起,则必须在一次调用中运行它们:
util.executeCommand(session, "cd /some/directory && ./script.csh");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句