Wrote a shell script on the Liunx, want to call this shell script through Java, do not know how to call, in the Internet said to use process this way, but my executive machine and my shell script is not the same computer, the boss said Java can connect SSH, Execute the shell script with the following code from their previous project
public class SSH {static Connection conn = null;static String hostname = "10.40.6.232"; static string username = "root"; STA Tic String password = "zhou123"; static int port = 36000;public static void Connect () throws IOException {try {conn = new Co Nnection (Hostname,port); Conn.connect (); Conn.authenticatewithpassword (username, password);} catch (Exception e) {System.out.println ("?????"); System.out.println ("" + e);}} @SuppressWarnings ("resource") public static string execcommand (String command) throws IOException {connect (); Session session = Conn.opensession (); Session.execcommand (command); Streamgobbler stdout = new Streamgobbler (Session.getstdout ()); BufferedReader br = new BufferedReader (New InputStreamReader ((stdout), "UTF-8"); String line = "", while (line = Br.readline ())! = null) {System.out.println (line);} Session.close (); return line;} @SuppressWarnings ("resource") public static arraylist<string> execcommandd (String command) throws IOException { Connect (); Session session = Conn.opensesSion (); session.execcommand (command); arraylist<string> Array_result = new arraylist<string> (); Streamgobbler stdout = new Streamgobbler (Session.getstdout ()); BufferedReader br = new BufferedReader (New InputStreamReader ((stdout), "UTF-8"); String Line;while (line = Br.readline ())! = null) {Array_result.add (line);} Session.close (); return array_result;} public static void Main (string[] args) {try {//System.out.println (EXECCOMMANDD ("Uname-s-r-v")); System.out.println (EXECCOMMANDD ("pwd"));//sh-mode execution System.out.println (execcommandd ("sh/script/test3.sh"));// Use SH mode to execute} catch (IOException e) {e.printstacktrace ();}}
It is important to note that when you execute a shell script, it is normal to implement the
But you will find that you write in the code, will tell you that the connection failed, normal writing is the SH/directory of your shell script, this is also let me struggle for a long time, because like the normal pwd command he can execute normally, but once the other cannot execute, you must use SH
Java connection SSH Execution shell script