当前位置: 代码迷 >> JavaScript >> JAVA-SSH2:JSch试工
  详细解决方案

JAVA-SSH2:JSch试工

热度:962   发布时间:2012-08-25 10:06:20.0
JAVA-SSH2:JSch试用

试用开源软件JSch实现通过SSH2协议,在JAVA程序内远程执行linux命令。

?

官方网站:http://www.jcraft.com/

?

?

package ssh;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JSchDemo
{
    
    public static void main(String[] args) throws Exception
    {
        String charset = "UTF-8";
        String user = "root";
        String passwd = "123456";
        String host = "40.40.40.50";
        String command = "ls -l";
        
        JSch jsch = new JSch();
        Session 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();
        
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        
        channel.connect();
        InputStream in = channel.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
        String buf = null;
        while ((buf = reader.readLine()) != null)
        {
            System.out.println(buf);
        }
        reader.close();
        channel.disconnect();
        session.disconnect();
    }
    
}
  相关解决方案