[英]Send an SFTP command by using runtime.exec
我想使用Java類Runtime從sftp服務器下載文件。 我不能使用Jsch或SSHJ之類的庫,因為我需要使用-B選項來增加緩沖區大小。 到目前為止,我已經嘗試使用此代碼:
public void download(String source, String destination,String port, String user, String host ){
Runtime runtime = Runtime.getRuntime();
String cmd = "sftp -oPort=" + port + " -B 150000 "+ user + "@" + host + ":" + source + " " + destination;
String[] args = { "/bin/sh", "-c", cmd };
try {
long startTime = System.currentTimeMillis();
log.info("cmd: "+ cmd);
final Process process = runtime.exec(args);
process.waitFor();
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Time: "+elapsedTime);
BufferedReader bre = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuffer sbe = new StringBuffer();
String lineError;
while ((lineError = bre.readLine()) != null) {
sbe.append(lineError).append("\n");
}
String answerError = sbe.toString();
if(answerError.length()>0)log.error("Error:"+answerError);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我收到錯誤消息:使用主機名而不是“ xxxxxx”連接到xxxxxxx ...
我已經在膩子中直接嘗試了該命令,它的效果很好,但是當我在Java中使用它時,它根本不起作用。 我還嘗試了帶有runtime.exec()的scp命令而不是sftp進行下載,並且可以工作。
有人知道為什么它不起作用嗎? 我找不到這種方法的例子。 還是有人知道允許設置-B選項的sftp傳輸庫? 我可能已經錯過了Jsch和Sshj中的方法。
提前致謝
我在Windows上使用psftp執行此操作。 我希望您在* nix上使用sftp的結果應該相同。
static java.io.File downloadFileViaSftp(String file) {
String string = null;
try {
String c = "psftp -l user -P 22 -v -pw password hostname";
Process p = Runtime.getRuntime().exec(c);
OutputStream out = p.getOutputStream();
Writer out2 = new BufferedWriter(new OutputStreamWriter(out));
out2.write("get " + file + "\n");
out2.flush();
out2.write("close\n");
out2.flush();
out2.write("quit\n");
out2.flush();
out2.close();
InputStream in = p.getInputStream();
InputStream err = p.getErrorStream();
BufferedReader bufferedreader1 = new BufferedReader(new InputStreamReader(in), 999999);
BufferedReader bufferedreader2 = new BufferedReader(new InputStreamReader(err), 999999);
while ((string = bufferedreader2.readLine()) != null) {
System.out.println("2=" + string);
System.out.flush();
}
bufferedreader2.close();
while ((string = bufferedreader1.readLine()) != null) {
System.out.println("1=" + string);
System.out.flush();
}
bufferedreader1.close();
int x = p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return new java.io.File(file);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.