http://wiki.jsch.org Here's a minimalistic example of Public Key Authentcation. It is
adapted from JSCH examples, but I have stripped out the GUI etc.
import com.jcraft.jsch.*;
public class UserAuthPubKey{
public static void main(String[] arg){
String pubkeyfile="/home/cr/users/anand/.ssh/id_dsa";
String passphrase="";
String host="gs00", user="root";
try{
JSch jsch=new JSch();
jsch.addIdentity(pubkeyfile);
// jsch.addIdentity(pubkeyfile, passphrase);
jsch.setKnownHosts("/home/cr/users/anand/.ssh/known_hosts");
Session session=jsch.getSession(user, host, 22);
session.connect();
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
}
catch(Exception e){
System.out.println(e); e.printStackTrace();
}
} //end of main
} //end of class
A quick and dirty example of using JSCH library to transfer files to/from a server.
import com.jcraft.jsch.*; import java.io.*; import java.io.IOException;
/** * * @author anand */ public class sftpex { public static void main(String[] args) { // TODO code application logic here
String username = "testuser"; String host = "testserver.example.com"; String pass = "testpass"; String khfile = "/home/testuser/.ssh/known_hosts"; String identityfile = "/home/testuser/.ssh/id_rsa";
JSch jsch = null; Session session = null; Channel channel = null; ChannelSftp c = null; try { jsch = new JSch(); session = jsch.getSession(username, host, 22); session.setPassword(pass); jsch.setKnownHosts(khfile); jsch.addIdentity(identityfile); session.connect();
channel = session.openChannel("sftp"); channel.connect(); c = (ChannelSftp) channel;
} catch (Exception e) { e.printStackTrace(); }
try { System.out.println("Starting File Upload:"); String fsrc = "/tmp/abc.txt", fdest = "/tmp/cde.txt"; c.put(fsrc, fdest); c.get(fdest, "/tmp/testfile.bin"); } catch (Exception e) { e.printStackTrace(); } c.disconnect(); session.disconnect();
} }
|