zoukankan      html  css  js  c++  java
  • java 使用jsch 远程链接linux执行命令

                一个简单的jsch链接linux并执行命令的utils。

             

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelExec;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    
    
    
    public class ShellUtils {
    	private static JSch jsch;
    	private static Session session;
    
    	
    	/**
    	 * 连接到指定的IP
    	 * 
    	 * @throws JSchException
    	 */
    	public static void connect(String user, String passwd, String host) throws JSchException {
    		jsch = new JSch();
    		session = jsch.getSession(user, host, 22);
    		session.setPassword(passwd);
    		
    		java.util.Properties config = new java.util.Properties();
    		config.put("StrictHostKeyChecking", "no");
    		session.setConfig(config);
    		
    		session.connect();
    	}
    
    	/**
    	 * 执行相关的命令
    	 * @throws JSchException 
    	 */
    	public static void execCmd(String command, String user, String passwd, String host) throws JSchException {
    		connect(user, passwd, host);
    		
    		BufferedReader reader = null;
    		Channel channel = null;
    
    		try {
    			while (command != null) {
    				channel = session.openChannel("exec");
    				((ChannelExec) channel).setCommand(command);
    				
    				channel.setInputStream(null);
    				((ChannelExec) channel).setErrStream(System.err);
    
    				channel.connect();
    				InputStream in = channel.getInputStream();
    				reader = new BufferedReader(new InputStreamReader(in));
    				String buf = null;
    				while ((buf = reader.readLine()) != null) {
    					System.out.println(buf);
    				}
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		} catch (JSchException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				reader.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			channel.disconnect();
    			session.disconnect();
    		}
    	}
       
    }
    



  • 相关阅读:
    BZOJ3832: [Poi2014]Rally(拓扑排序 堆)
    UVAlive6807 Túnel de Rata (最小生成树)
    UVAlive6800The Mountain of Gold?(负环)
    cf623A. Graph and String(二分图 构造)
    BZOJ4144: [AMPPZ2014]Petrol(最短路 最小生成树)
    cf605D. Board Game(BFS 树状数组 set)
    为什么要去创业?
    后缀数组练习题若干
    Android开发 之 我的jar包引用方法
    IBM-ETP 实训项目前一天
  • 原文地址:https://www.cnblogs.com/allenzhaox/p/3201775.html
Copyright © 2011-2022 走看看