在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
原文地址:https://www.cnblogs.com/chongyou/p/8253565.html
时间: 2024-10-11 10:16:11