Official address: http://www.cleondris.ch/en/opensource-ssh2.php
Brief introduction:
Ganymed SSH-2 for Java are a library which implements the SSH-2 protocol in pure Java (tested on J2SE 1.4.2 and 5.0). It allows one to connect to SSH servers from within Java programs. It supports SSH sessions (remote command execution and shell access), local and remote port forwarding, local stream Forwa Rding, X11 forwarding, SCP and SFTP. There are no dependencies on any JCE provider, as all crypto functionality is included.
Program:
Copy Code code as follows:
@Test
public void Testssh () {
String hostname = "192.168.0.1";
String username = "root";
String password = "password";
try {
/* Create A connection instance * *
Connection conn = new Connection (hostname);
* Now Connect * *
Conn.connect ();
System.out.println ("Connect OK");
/*
* Authenticate. If you have a ioexception saying something like
* "Authentication method password not supported by the" server "in this stage."
* then please check the FAQ.
*/
Boolean isauthenticated = Conn.authenticatewithpassword (Username,password);
if (isauthenticated = = False)
throw new IOException ("Authentication failed.");
SYSTEM.OUT.PRINTLN ("Authentication ok");
/* Create a session *
Session Sess = Conn.opensession ();
Sess.execcommand ("uname-a");
System.out.println ("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes
* Dangerous (Please read the FAQ).
*/
InputStream stdout = new Streamgobbler (Sess.getstdout ());
BufferedReader br = new BufferedReader (new InputStreamReader (stdout));
while (true) {
String line = Br.readline ();
if (line = = null)
Break
System.out.println (line);
}
/* Show exit status, if available (otherwise "null") * *
System.out.println ("ExitCode:" + sess.getexitstatus ());
/* Close the session * *
Sess.close ();
/* Close the connection * *
Conn.close ();
catch (IOException e) {
E.printstacktrace (System.err);
System.exit (2);
}
}
Run Result:
Copy Code code as follows:
Connect OK
Authentication OK
This is some information about the remote host:
Linux localhost.localdomain 2.6.22 #1 SMP Wed Aug 11:24:59 CST 2008 i686 i686 i386 Gnu/linux
exitcode:0