【问题标题】:Problem sshpass using Runtime.getRuntime().exec on java, but on cmd tunning fine问题 sshpass 在 java 上使用 Runtime.getRuntime().exec,但在 cmd 上调优
【发布时间】:2021-02-26 02:44:19
【问题描述】:

有人可以解决这个问题吗?我使用 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"});

在 java 上使用 runtime.exec 并没有显示错误,但在命令行上运行良好。

我的代码

try {

    Process proc = Runtime.getRuntime().exec(new String[] {"sshpass","-p", "password","scp","-r",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());
}

【问题讨论】:

    标签: java ssh cygwin sshpass


    【解决方案1】:

    使用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"
        });
    
    

    【讨论】:

    • 你的代码仍然对我不起作用@pieter12345
    • 我看到您已按照我的建议更新了您的问题。您的路径或任何其他论点仍然可能是错误的。我可以建议尝试从 cmdline 运行它,然后将其放入我提供的代码框架中,以查看它是否也可以通过 Java 运行。我不知道你的命令是否真的正确,我假设你已经测试过了。
    • 顺便说一句,您的代码在不使用“Name@myip:”的情况下工作,可能是因为使用了 java exec 无法读取的符号“@”或“:”。你知道如何解决这个问题吗?
    • @NisaAhmad 直接从 cmdline 运行命令时,它有效吗?您能否在问题中也包含该命令?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多