標籤:shel script stack void obb array connect user host
在liunx上寫了一個shell指令碼,想通過java去調用這個shell指令碼,不知道怎麼去調用,在網上說使用process這個進程方式,但是我執行機和我shell指令碼都不在同一台電腦,老大說java中可以串連ssh,執行shell指令碼,以下代碼來自他們以前的項目
public class SSH {static Connection conn = null;static String hostname = "10.40.6.232";static String username = "root";static String password = "zhou123";static int port = 36000;public static void connect()throws IOException {try {conn = new Connection(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方式執行System.out.println( execCommandd("sh /script/test3.sh"));//使用的sh方式執行} catch (IOException e) {e.printStackTrace();}}
需要注意,在執行shell指令碼時,正常這樣就可以實現了
但是你會發現你在代碼中這樣寫,會告訴你串連失敗,正常寫法是 sh /目錄下你的shell指令碼,這個也是讓我糾結了很久,因為像正常的pwd命令他是可以正常執行,但是一旦是其他就不能執行,就必須要使用sh
java串連ssh執行shell指令碼