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

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

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值