JSch: How to ssh into a server using ssh-keys

我与影子孤独终老i 提交于 2019-12-21 02:34:38

问题


I want to ssh into a server from behind another ssh server. The gateway server requires a username/password and I can do this. I am using a tunnel to get into the next server, but this one requires only an ssh key. I've generated the key through PuTTY, so it exists for my username but I'm not sure how to retrieve it for my Java program. Is it a configuration? i.e. setConfig("userauth.publickey", "com.jcraft.jsch.UserAuthPublicKey") then how do I use this or something else? Documentation seems to be sparse and I appreciate any help. Anything I've tried gives me an error :"Auth fail" when I connect this session

Thanks!

The tunnel method I use is: http://sourceforge.net/apps/mediawiki/jsch/index.php?title=ProxySSH so thanks to the guy who wrote it!

For context, I'd like to read/write to a server at my school from my Android phone.


回答1:


To enable public-key authentication, you have to use one of the JSch.addIdentity methods.

These take the public and private key in the OpenSSH key format - so make sure you export it from PuTTY in this format. (JSch doesn't understand PuTTY's native format, though you could write an adapter implementing the Identity interface, parsing it yourself).

The identities added to JSch are global, not per-session. This is normally not a problem, as JSch will try all authentication methods which are supported both by itself and the server in order, and public-key authentication is normally before password authentication.

All authentication methods need a user name (usually the name of the account to be logged into).

With public-key authentication, the public key must be somehow previously available to the server. For OpenSSH's sshd, the public key should be listed in ~/.ssh/authorized_keys. (If you have only one public key, simply copy it to this file, if you have multiple ones (each of which will be allowed), each should be on one line.)

So it should work out-of-the box after setting the identity.

If you want to make sure the first session uses password authentication and the second (tunneled) one uses public-key, you can use the per-session configuration, overriding the global one:

tunnelSession.setConfig("PreferredAuthentications", "password");

innerSession.setConfig("PreferredAuthentications", "publickey");

(These are comma-separated lists, here of one element each.)

About the ProxySSH example, that is by me (with some help by JSch's author, Atsuhiko Yamanaka). I should add this information to the Wiki page, maybe.



来源:https://stackoverflow.com/questions/7665002/jsch-how-to-ssh-into-a-server-using-ssh-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!