【问题标题】:File transfer between remote servers using Jsch使用 Jsch 在远程服务器之间传输文件
【发布时间】:2016-11-17 04:17:02
【问题描述】:

我有一个要求,我需要登录到一个 unix 服务器,执行切换用户,执行一些命令,然后将这些命令创建的文件 scp 到另一个服务器。 我能够连接到服务器,执行 sudo 登录并执行命令,但是我无法将文件直接 scp 到另一个远程服务器。

我正在为此使用 Jsch jar。下面是我的代码。

public void executeChannel(Session session, String command, String pwd, List file) throws Exception{

    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");

}

command = sudo su -pentaho; cd /dir1/dir2/; ls -lrt; scp 在执行上述代码时,直到 ls -lrt 的命令都被正确执行,我可以看到输出。然而,在此之后代码挂起。 代码没有抛出异常,因此我不知道发生了什么。

任何帮助将不胜感激。

【问题讨论】:

    标签: java ssh jsch


    【解决方案1】:

    原来我没有正确打印腻子控制台的输出。我弄清楚了这个问题。解决方案是更改命令。

    从命令中删除 sudo -S -p '' 并将原始命令替换为 sudo su - user -c "my commands" 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多