1
我有一個需求,其中需要登錄到unix服務器,執行切換用戶,執行一些命令,然後將從這些命令創建的文件scp到不同的服務器。 我可以連接到服務器,執行sudo登錄並執行命令,但是我無法將文件直接傳送到另一臺遠程服務器。使用Jsch在遠程服務器之間傳輸文件
我正在使用Jsch jar。以下是我的代碼。
公共無效executeChannel(會話會話,字符串命令,字符串PWD,列表文件)拋出異常{
logger.info("************************Start of executeChannel() method*****************************");
Channel channel = session.openChannel("exec");
// below line avoids "sudo: no tty present and no askpass program" error
((ChannelExec) channel).setPty(true);
// this line ensures password prompt is not displayed after sudo user
/**
* -S The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device.
* -p The -p (prompt) option allows you to override the default password prompt and use a custom one.
*/
String filename = file.toString().replace("[", "").replace("]", "").replace(",", "");
System.out.println("sudo -S -p '' "+command+" "+filename+" server2:/dir1/dir2/dir3/");
((ChannelExec)channel).setCommand("sudo -S -p '' "+command+" "+filename+" server2:/dir1/dir2/dir3/");
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
OutputStream out=channel.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
channel.connect();
out.write((pwd+"\n").getBytes());
byte[] tmp=new byte[1024];
while(true){
logger.info("start of while(true) method, is channel connected? "+channel.isConnected());
br.readLine();
while(br.readLine() != null){
System.out.println("channel.isConnected() "+channel.isConnected());
int i = in.read(tmp, 0, 1024);
if(i<0) break;
System.out.println("printing putty console: \n"+new String(tmp,0,i));
}
if (channel.isClosed()){
System.out.println("Exit Status:- "+channel.getExitStatus());
break;
}
try{
Thread.sleep(1000);
}
catch(Exception e) {
e.printStackTrace();
}
}
out.flush();
br.close();
System.out.println("DONE");
}
命令=須藤蘇-pentaho; cd/dir1/dir2 /; ls -lrt; scp 在執行上面的代碼時,直到ls -lrt執行正確,我可以看到輸出。但是在此之後代碼會掛起。 代碼沒有拋出任何異常,因此我對發生了什麼感到不知所措。
任何幫助將不勝感激。