当前位置: 首页 > 工具软件 > Apache SSHD > 使用案例 >

java ssh 协议_Java SSH库使用简介:Apache sshd和JSch(Java Secure Channel)

田易安
2023-12-01

1.Apache sshd

Apache sshd是一个SSH协议的100%纯Java库,支持客户端和服务器。sshd库基于Apache MINA项目(可伸缩高性能的异步IO库)。

客户端示例代码:

public void clentTest() throwsIOException

{

String cmd="ifconfig";

SshClient client=SshClient.setUpDefaultClient();

client.start();

ClientSession session=client.connect("bellring", "10.2.48.179", 22).await().getSession();

session.addPasswordIdentity("bellring");

//session.addPublicKeyIdentity(SecurityUtils.loadKeyPairIdentity("keyname", new FileInputStream("priKey.pem"), null));if(!session.auth().await().isSuccess())

System.out.println("auth failed");

ChannelExec ec=session.createExecChannel(cmd);

ec.setOut(System.out);

ec.open();

ec.waitFor(ClientChannel.CLOSED,0);

ec.close();

client.stop();

}

public void sshdClientSftpTest() throwsIOException, InterruptedException

{

Path src=Paths.get("src_sshd.txt");

Files.deleteIfExists(src);

Files.createFile(src);

Files.write(src,"adsfa\nsdfs".getBytes());

SshClient client=SshClient.setUpDefaultClient();

client.start();

ClientSession session=client.connect("bellring", "10.2.48.179", 22).await().getSession();

//session.addPasswordIdentity("bellring");session.addPublicKeyIdentity(SecurityUtils.loadKeyPairIdentity("keyname", new FileInputStream("priKey.pem"), null));

if(!session.auth().await().isSuccess())

System.out.println("auth failed");

SftpClient sftp=session.createSftpClient();for(DirEntry de:sftp.readDir("."))

System.out.println(de.filename+" "+de.attributes.type);

OutputStream os=sftp.write("test/dst_sshd.txt");

Files.copy(src, os);

os.close();//sftp.remove("delete_file.txt");

InputStream is=sftp.read("test/dst_sshd.txt");

Path dst=Paths.get("dst1_sshd.txt");

Files.deleteIfExists(dst);

Files.copy(is, dst);

is.close();

sftp.close();

client.stop();

}

服务器端示例代码:

public void serverTest() throwsIOException, InterruptedException

{

SshServer sshd=SshServer.setUpDefaultServer();

sshd.setPort(22);//*give host key generator a path, when sshd server restart, the same key will be load and used to authenticate the server

sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

sshd.setPasswordAuthenticator(newPasswordAuthenticator(){

@Overridepublic booleanauthenticate(String username, String password, ServerSession session) {

System.out.println("authen: user="+username+" password="+password);if("bellring".equals(username) && "123456".equals(password))return true;return false;

}});//use file ~/.ssh/authorized_keys

sshd.setPublickeyAuthenticator(new DefaultAuthorizedKeysAuthenticator(false));//* CommandFactory can be userd in addition to the ShellFactory,//* it can also be used instead of the ShellFactory.//* The CommandFactory is used when direct commands are sent to the SSH server,//* as this is the case when running ssh localhost shutdown or scp xxx

ScpCommandFactory scpCmdFactory=newScpCommandFactory();

scpCmdFactory.setDelegateCommandFactory(newCommandFactory() {publicCommand createCommand(String command) {

System.out.println("command = \"" + command + "\"");return new ProcessShellFactory(("cmd /c "+command).split(" ")).create();

}

});

sshd.setCommandFactory(scpCmdFactory);

sshd.start();}

2.JSch(Java Secure Channel)

jsch也是SSH2的纯Java实现。依赖于JavaTm Cryptography Extension(JCE)。JSch支持客户端。

客户端远程命令执行示例:

public void testJschClient() throwsJSchException, InterruptedException

{

JSch jsch=newJSch();//set private key for authjsch.addIdentity("yangtianxin_pc");

Session session=jsch.getSession("bellring", "10.2.48.179", 22);

session.setConfig("StrictHostKeyChecking", "no");//set auth info interactively//session.setUserInfo(new UserInfo(){.....});

//session.setPassword("bellring");session.connect();

com.jcraft.jsch.ChannelExec ec=(com.jcraft.jsch.ChannelExec)session.openChannel("exec");

ec.setCommand("ifconfig");

ec.setInputStream(null);

ec.setErrStream(System.err);

ec.setOutputStream(System.out);

ec.connect();while(!ec.isClosed())

Thread.sleep(500);

ec.disconnect();

session.disconnect();

}

sftp文件操作示例

public void testJschClientSftp() throwsJSchException, InterruptedException, SftpException, IOException

{

JSch jsch=newJSch();

//add private key for auth

//jsch.addIdentity("yangtianxin_pc");

Session session=jsch.getSession("bellring", "10.2.48.179", 22);

session.setConfig("StrictHostKeyChecking", "no");//set auth info interactively//session.setUserInfo(new UserInfo(){.....});

session.setPassword("bellring");

session.connect();

com.jcraft.jsch.ChannelSftp sftpChannel=(com.jcraft.jsch.ChannelSftp)session.openChannel("sftp");

sftpChannel.connect();

Path src=Paths.get("src.txt");

Files.deleteIfExists(src);

Files.createFile(src);

Files.write(src,"adsfasdfs".getBytes());

@SuppressWarnings("unchecked")

Vector vector=sftpChannel.ls(".");for(LsEntry entry: vector)

System.out.println(entry.getFilename()+" "+entry.getAttrs().getSize());

sftpChannel.cd("test");

sftpChannel.put("src.txt", "dst.txt");

sftpChannel.get("dst.txt", "dst1.txt");

sftpChannel.rm("dst.txt");

sftpChannel.disconnect();

session.disconnect();

System.out.println("done");

}

 类似资料: