GANYMED-SSH2 Introduction
Ganymed SSH-2 for Java is a package that implements the SSH-2 protocol with pure Java. You can use it to connect to the SSH server directly in the Java program.
How to use
Add Ganymed-ssh2-build210.jar to the project Lib
Examples Show
Get the amount of space on a directory on a Linux server
Import Java. IO. BufferedReader;Import Java. IO. IOException;Import Java. IO. InputStream;Import Java. IO. InputStreamReader;Import Ch. Ethz. SSH2. Connection;Import Ch. Ethz. SSH2. Session;Import Ch. Ethz. SSH2. Streamgobbler;public class Sshutil {public static string Getdirsize (string path) {string hostname ="Linux Server IP Address";String username ="Linux users";String Password ="Linux password";String size ="";try {/ * Create A Connection instance * /Connection conn = new Connection (hostname); / * Now connect * /Conn. Connect(); / * * Authenticate. If you get a ioexception saying something like * ' Authentication method password not ' supported by the server At the this stage. * then please check the FAQ. */Boolean isauthenticated = conn. Authenticatewithpassword(Username, password);if (isauthenticated = = false) throw new IOException ("authentication failed."); / * Create a session * /Session sess = conn. Opensession();Sess. ExecCommand("Du-m--max-depth=0"+path); /* * This basic example does not handle stderr, which are sometimes * dangerous (please read th e FAQ). */InputStream stdout = new Streamgobbler (sess. Getstdout());BufferedReader br = new BufferedReader (new InputStreamReader (stdout));String line = BR. ReadLine();String ss[] = line. Split("\\s+");Size = ss[0]; /* Show exit status, if available (otherwise "null") */System. out. println("ExitCode:"+ Sess. Getexitstatus()); / * Close This session * /Sess. Close(); / * Close the connection * /Conn. Close();} catch (IOException e) {E. Printstacktrace(System. Err);System. Exit(2);} return Size;} public static void Main (string[] args) {System. out. println(Getdirsize ("/mnt/online/resource/media"));}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java uses GANYMED-SSH2 to execute Linux commands