【问题标题】:Not able to execute a .csh script using jsch library - Exit 1无法使用 jsch 库执行 .csh 脚本 - 退出 1
【发布时间】: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; 
      }
}

【问题讨论】:

标签: java linux shell ssh jsch


【解决方案1】:
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");

【讨论】:

  • 非常感谢。这就解释了为什么 ls 命令不起作用。但是脚本仍然没有被执行。我将编辑问题以反映这一点。非常感谢您的回复。
猜你喜欢
  • 2011-10-01
  • 1970-01-01
  • 2010-11-29
  • 2014-05-30
  • 1970-01-01
  • 2017-08-26
  • 2021-09-09
  • 1970-01-01
  • 2019-06-23
相关资源
最近更新 更多