Java 连接Linux 密码鉴权关闭时可用JSch

来源:互联网 发布:周冬雨怎么瘦腿的知乎 编辑:程序博客网 时间:2024/05/17 01:19

试用开源软件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();    }    }

转载自:http://acooly.iteye.com/blog/1436649

0 0