Java Process,waitFor给我一个255 exitCode调用一个sh文件

时间:2016-05-16 08:47:29

标签: java bash shell

我有一个应该从服务器重启客户端的进程。

从我的java webapp到达本地服务器上的控制器

@RequestMapping(value = "/client/restart", method = RequestMethod.GET)
    public int restartClient(@RequestParam(value = "idClient") int idClient) {
        Client client = clientService.findById(idClient);
        int numeroClient = client.getNumeroClient();
        String command = "/home/pi/park/script/resetClient.sh";
        int exitCode = 1;
        try {
            Process p = new ProcessBuilder(command, "" + numeroClient).start();

            p.waitFor();
            logger.debug("wait for esce con: "+p.waitFor());
            exitCode = p.exitValue();

        } catch (InterruptedException | IOException e) {

            logger.error("I/O", e);
        }

        return exitCode;

    }

这应该返回操作的exitCode。如果我直接从shell调用resetClient.sh及其参数,则客户端会正确重启。

resetClient.sh这很简单:

#!/bin/sh

CLIENT=$1

ssh client$CLIENT 'sudo /etc/init.d/myscript restart'

我在服务器和客户端之间通过ssh无密码访问。 我的记录器返回p.waitFor() = 255 我已尝试使用命令绝对路径或相对路径,但它是相同的 如果我从服务器shell运行.sh命令,我得到正确的0

1 个答案:

答案 0 :(得分:0)

ssh的手册页说:

ssh exits with the exit status of the remote command or with 255 if an error occurred.

看来ssh失败了,但是你的帖子中没有足够的信息来说明原因 它可能与许可有关,可能是由于没有附加 tty ,这有很多合理的原因。

您确实需要捕获命令的输出以了解更多信息。

检查p.getErrorStream()p.getInputStream() 可能会打印一条错误消息,告诉您问题所在。