微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

问题 sshpass 在 java 上使用 Runtime.getRuntime().exec,但在 cmd 上运行良好

如何解决问题 sshpass 在 java 上使用 Runtime.getRuntime().exec,但在 cmd 上运行良好

有人能解决这个问题吗?我使用 sshpass 在 java 上传文件。执行这个命令

Process proc = Runtime.getRuntime().exec(new String[] {"sshpass","-p","password","scp","-r",getContext().getServletContext().getRealPath ("/WEB-INF/file/"+today)+"/Name@myip:/cygdrive/d/file"});

并且错误不会使用 runtime.exec 在 java 上显示,但在运行良好的命令行上。

我的代码

try {

    Process proc = Runtime.getRuntime().exec(new String[] {"sshpass",getContext().getServletContext().getRealPath("/WEB-INF/file/"+today)+"/ Name@myip:/cygdrive/d/file"});

    // System.out.println(sshStr);
    BufferedReader read = new BufferedReader(new InputStreamReader(
    proc.getInputStream()));

    //--------------------check---------------------
    printStream(proc.getInputStream(),"OUTPUT");
    printStream(proc.getErrorStream(),"ERROR");
    //--------------------check---------------------

    try {
        proc.waitFor();
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }
    while (read.ready()) {
        System.out.println(read.readLine());
    }
} catch (IOException e) {
    System.out.println(e.getMessage());
}

解决方法

使用 Runtime.exec(String),无论您添加了哪些引号,字符串参数都会在空格处拆分。您必须改用 Runtime.exec(String[])。这导致:

Process proc = Runtime.getRuntime().exec(new String[] {
        "sshpass","-p","password","scp","-r",getContext().getServletContext().getRealPath("/WEB-INF/file/" + today) + "/ Name@myip:/cygdrive/d/file"
    });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。