zoukankan      html  css  js  c++  java
  • java连接ssh执行shell脚本

    在liunx上写了一个shell脚本,想通过java去调用这个shell脚本,不知道怎么去调用,在网上说使用process这个进程方式,但是我执行机和我shell脚本都不在同一台电脑,老大说java中可以连接ssh,执行shell脚本,以下代码来自他们以前的项目

    public class SSH {
    	
    	static Connection conn = null;
    	static String hostname = "XXXiP地址2";
    	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开发web的几种开发模式
    Tomcat7.0安装配置
    Apache与Tomcat 区别联系
    编写 Window 服务程序
    系列文章--SharePoint 开发教程
    Google Chrome浏览器调试功能介绍
    Chrome的JS调试工具
    Google Chrome 调试JS简单教程[更新]
    ASP.NET常用标准配置web.config
    WINDOWS下kill进程的命令
  • 原文地址:https://www.cnblogs.com/chongyou/p/8253565.html
Copyright © 2011-2022 走看看