簡體   English   中英

無法從Java調用Shell腳本,其中Shell包含sshpass

[英]Unable to call a shell script from Java where Shell contains sshpass

我們有一個用例,可以將> 4GB的數據文件從sftp站點傳輸到服務器盒。 我們已決定創建一個Java服務,該服務將調用一個實習生輸入到sftp站點和路徑並將其到達目標位置的shell腳本。

我們編寫了以下代碼來從Java文件調用Shell腳本。

Process proc = null;
String command = "/mnt/hmdata/loadTest.sh";
System.out.println("passing command::" + command);
try {
    Runtime rt = Runtime.getRuntime();
    proc = rt.exec(command.trim());
    boolean status = proc.waitFor `enter code here` (45, TimeUnit.SECONDS);
    LOGGER.log(Level.INFO, "Shell Called successfully");
    if (status) {
        msg = "Shell Called successfully";

    } else {
        msg = "Error while calling Shell";
    }
} catch (IOException e) { 
    e.printStackTrace(); 
} catch (NullPointerException e) { 
    e.printStackTrace(); 
} catch (Exception ex) { 
    ex.printStackTrace(); 
} finally { 
    proc.destroy(); 
}

shell腳本就是這樣

sshpass -p '<password>' scp -r <userid>@<host>:/finint/inbound/financial/tenv/edw_osccl/* .

一旦調用Java服務,我們的服務將無法啟動外殼。 相反,在服務器命令提示符下,相同的shell運行良好。 我們正在從Unix運行我們的程序。

有人可以建議解決方案嗎?

解決。 Java代碼未更改。

   Changed Shell Script as
   echo "Hello" >> /mnt/hmdata/output.txt
   chmod 777 /mnt/hmdata/output.txt
   export PASSWD="password"

   sshpass -f /mnt/hmdata/password scp -v -r <user><host>:<path>/<file>

我認為命令應該是sh /mnt/hmdata/loadTest.sh而不是/mnt/hmdata/loadTest.sh ,這樣您才能從Java進程中使用它。 它可以表示為String[] ,如下所示:

String[] cmd = { "sh", "/mnt/hmdata/loadTest.sh"};

public Process exec(String command)是一種public Process exec(String command, String[] envp, File dir)方法public Process exec(String command, String[] envp, File dir)的便捷方法,女巫又是public Process exec(String[] cmdarray, String[] envp, File dir)一種便捷方法public Process exec(String[] cmdarray, String[] envp, File dir) ,根據Javadoc

如果您也可以共享catch塊,那就太好了,這樣我們就有了完整的try-catch塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM