开发者

How can I make the JSch API log in to a Unix server without a password?

I'm trying to make a Java application, that executes shell scripts on a remote Unix server, using the JSch API.

I was wondering if i开发者_StackOverflow社区t's possible to login to the server without a password. If so - how? Should I generate a pair of authentication keys on the servers, then make the application read information from the key file?

The Java application is on a Windows station.


Since it took awhile before made it work, here is a whole modified example:

JSch jsch=new JSch();
Session session=jsch.getSession("my_username", "my_host", my_port);
session.setConfig("PreferredAuthentications", "publickey");
jsch.setKnownHosts("~/.ssh/known_hosts");
jsch.addIdentity("~/.ssh/id_rsa");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect(3*1000);

Beware whether you have copied rsa or dsa key to the server and add a corresponding identity at line addIdentity - id_rsa or id_dsa.

(cat .ssh/id_rsa.pub | ssh me@servername 'cat >> .ssh/).


This is certainly doable. Have a look at the examples directory provided with jsch.

UserAuthPubKey.java is showing how to authenticate with a public key and and KeyGen.java is chowing how to create the public and private keys.


Once you have sorted out your keys there is a single line to enable connecting with a key rather than a password:

JSch jsch = new JSch();
jsch.addIdentity(".ssh/privateKey.pem");

The addIdentity method takes a single argument that points at the location of your private key file on your machine.


As said by jlliagre, it is possible.

Generate a key pair for your application, make the public key known to the server (often putting it in ~/.ssh/authorized_keys is a good way), and give both keys to the client JSch object, either as files or as byte[]. You might also want to change the PreferredAuthentications option to allow only public-key auth, to avoid asking for a password or trying something else.

Note: If you deliver your application to hosts not controlled by you, anyone which can access the application's files can use the private key to login to your server.

Thus you should make sure the account can't do anything harmful, or that the client machine (your account and any privileged one) is under your (or only known friendlies') total control. (Encrypting the private key with a passphrase does not help if the passphrase is distributed with your program. Neither does putting it in the program's jar file.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜