【问题标题】:How to work around jsch.addIdentity() in Junit test?如何在 Junit 测试中解决 jsch.addIdentity() 问题?
【发布时间】:2016-06-28 19:03:26
【问题描述】:

我使用 apache mina sshd 来设置一个模拟 ssh 服务器用于 Junit 测试。由于 apache mina 的文档非常不清楚,我无法弄清楚如何处理测试中的身份验证问题。

我想测试的代码,基本上是使用Jsch将文件从本地传输到远程。

public static void scpTo(String rfilePath, String lfilePath, String user, String host, String keyPath, int port) {
    FileInputStream fis=null;
    try {
        while(true) {
            String rfile = rfilePath;
            String lfile = lfilePath;

            JSch jsch = new JSch();
            jsch.addIdentity(keyPath);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");

            Session session = jsch.getSession(user, host, port);
            session.setConfig(config);

            session.connect();

            // exec 'scp -t rfile' remotely
            String command = "scp " + " -t " + rfile;
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            // get I/O streams for remote scp
            OutputStream out = channel.getOutputStream();
            InputStream in = channel.getInputStream();

            channel.connect();

            if (checkAck(in) != 0) {
                System.exit(0);
            }

            File _lfile = new File(lfile);
            if(!_lfile.exists()) {
                System.err.println("Local file not existing");
            }

            //check file existing
            File _rfile = new File(rfile);
            if (_rfile.exists()) {
                System.out.println("Remote file already existed");
                break;
            }

            // send "C0644 filesize filename", where filename should not include '/'
            long filesize = _lfile.length();
            command = "C0644 " + filesize + " ";
            if (lfile.lastIndexOf('/') > 0) {
                command += lfile.substring(lfile.lastIndexOf('/') + 1);
            } else {
                command += lfile;
            }
            command += "\n";
            out.write(command.getBytes());
            out.flush();
            if (checkAck(in) != 0) {
                System.exit(0);
            }

            // send a content of lfile
            fis = new FileInputStream(lfile);
            byte[] buf = new byte[1024];
            while (true) {
                int len = fis.read(buf, 0, buf.length);
                if (len <= 0) break;
                out.write(buf, 0, len); //out.flush();
            }
            fis.close();
            fis = null;
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            if (checkAck(in) != 0) {
                System.exit(0);
            }
            out.close();

            channel.disconnect();
            session.disconnect();

            //System.exit(0);

            Thread.sleep(2000);
        }
    } catch (Exception e) {
        System.out.println(e);
        try {
            if (fis != null) fis.close();
        } catch (Exception ee) {
        }
    }
}

以及用于测试的setUp。如果我想使用资源文件夹中的给定密钥文件对所有用户和主机对进行身份验证,我应该为 setUp 做什么?对于当前的setUp,会出现Auth fail错误。

@Before
public void setup() {
    user = "siyangli";
    host = "localhost";
    //pick a port not occupied for tesing
    port = 22998;
    sshd = SshServer.setUpDefaultServer();
    sshd.setPort(port);
    keyPath = "/Users/siyangli/.ssh/id_rsa";
    //it will change the key file??? do not know why, how to work around the authentication key??
    sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/Users/siyangli/.ssh/id_rsa"}));
    //sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(keyPath));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
        public boolean authenticate(String username, String password, ServerSession session) {
            return true;
        }
    });
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return true;
        }
    });
    CommandFactory myCommandFactory = new CommandFactory() {
        public Command createCommand(String command) {
            System.out.println("Command: " + command);
            return null;
        }
    };
    sshd.setCommandFactory(new ScpCommandFactory(myCommandFactory));
    List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
    userAuthFactories.add(new UserAuthPassword.Factory());
    sshd.setUserAuthFactories(userAuthFactories);
    List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>();
    namedFactoryList.add(new SftpSubsystem.Factory()); sshd.setSubsystemFactories(namedFactoryList);
    try {
        sshd.start();
    } catch (IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Finished setup !!! ");
}

【问题讨论】:

  • 提示:您的方法 scpTo 正在做很多事情。我强烈建议您查看 Robert Martin 的“清洁代码”……或者花一些时间观看 youtube.com/playlist?list=PLD0011D00849E1B79……您的代码可以从中受益匪浅……

标签: junit jsch apache-mina


【解决方案1】:

您需要更改此行: userAuthFactories.add(new UserAuthPassword.Factory()); 到 userAuthFactories.add(new UserAuthPublicKey.Factory());

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2020-08-19
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2018-03-13
    相关资源
    最近更新 更多