jsch为什么不执行scp命令?

问题描述 投票:0回答:1

我正在尝试使用scp将文件从本地传输到远程。本地是Windows(OpenSSH作为服务运行),远程是FreeBSD(已设置rsa键)。为此,我正在使用Jsch库。

try {
        if (ses == null) ses = fsaTo.getSession();
        channel = ses.openChannel("exec");
        String cmd = "scp "+ UserHostIdentity.getTransferUser(fsaFrom.getSystem()) + "@" 
                + UserHostIdentity.getTransferHost(fsaFrom.getSystem()) + ":"
                + from + " " 
                + to;
        ((ChannelExec)channel).setCommand(cmd);
        ((ChannelExec)channel).setErrStream(System.err);
        channel.connect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

命令cmd我对其进行了手动测试,并成功运行。这是我启动会话的方式:

JSch jsch = new JSch();
    try {
        sshSession = jsch.getSession(UserHostIdentity.getTransferUser(fs), UserHostIdentity.getTransferHost(fs),22);
        UserInfo lui = UserHostIdentity.getTransferUserInfo(fs);
        sshSession.setUserInfo(lui);
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.connect();
    } catch (JSchException e) {
        logger.error("Could not access fileserver.");
        throw new RuntimeException(e);
    }

问题是在调用channel.connect()之后没有任何反应,没有错误,没有反应。在相同的上下文中,以下代码执行"sha256 -q " + filePath并返回正确的结果:

public String doCommand(String cmd) {
    if (sshSession == null) {
        initiateConnection();
    }

    Channel channel;
    String result = "";
    try {
        channel = sshSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream input = channel.getInputStream();
        channel.connect(); 
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;

        while((line = bufferedReader.readLine()) != null){
            result = line;
        }
        bufferedReader.close();
        inputReader.close();
        channel.disconnect();
    } catch (JSchException e) {
        logger.error("Problem with communication to Fileserver.");
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("Problem with command stream.");
        throw new RuntimeException(e);
    }
    return result;
}

我的问题是,为什么它不能与scp命令一起使用。

java scp jsch
1个回答
0
投票

最好的开始可能是使用详细参数运行scp:

scp -v src dest

或者如果这样不能帮助您查看是否可以安装strace(如果尚未安装)并运行:

strace scp -v src dest

这应该向您提示可能出了什么问题(尽管您说已设置了主机密钥,但是您是否对其进行了测试?),例如:

  • 主机密钥验证可能失败
  • 您可能需要输入私钥的密码短语
  • 可能存在一些安全性不兼容

而且您忘了继续阅读InputStream,也许在channel.connect()行周围做这样的事情:

InputStream in = channel.getInputStream();
channel.connect();
in.transferTo(System.out);

或者像sha256命令一样继续读取InputStream(来自scp的stdout),直到该过程完成(这样就可以在我的机器上工作了。)>]

© www.soinside.com 2019 - 2024. All rights reserved.