当前位置: 代码网 > it编程>编程语言>Java > java实现ssh登录linux并执行命令的三种实现方式

java实现ssh登录linux并执行命令的三种实现方式

2024年12月01日 Java 我要评论
java实现ssh登录linux并执行命令1.方法一使用ganymed-ssh2 <dependency> <groupid>ch.ethz

java实现ssh登录linux并执行命令

1.方法一

使用ganymed-ssh2

        <dependency>
            <groupid>ch.ethz.ganymed</groupid>
            <artifactid>ganymed-ssh2</artifactid>
            <version>262</version>
        </dependency>

但是这个包最新版本是2014年之后,就没有更新了,linux 操作系统安装 open-ssh 8.5及更高级版本,就一直提示连接失败。就不再提供demo

2.方法二

jsch 暂时能使用,也是很久没有更新了,恐怕后续也会有无法匹配系统最新协议的问题。

     <dependency>
            <groupid>com.jcraft</groupid>
            <artifactid>jsch</artifactid>
            <version>0.1.55</version>
        </dependency>
public class remoteexecutecommand {

    public static list<string> remoteexecute(session session, string command)
    {
        system.out.println("cmd:" + command);
        list<string> resultlines = new arraylist<>();
        channelexec channel = null;

        try
        {
            channel = (channelexec) session.openchannel("exec");
            channel.setcommand(command);
            inputstream input = channel.getinputstream();
            channel.connect(50000);
            bufferedreader inputreader = new bufferedreader(new inputstreamreader(input));
            string inputline = null;
            while ((inputline = inputreader.readline()) != null)
            {
                system.out.println(inputline);
                resultlines.add(inputline);
            }

        } catch (exception e)
        {
            e.printstacktrace();
        } finally
        {
            system.out.println("最后关闭channel");
            channel.disconnect();
        }

        return resultlines;
    }
}


        string usrname = "root";
        string password = "******";
		string remoteip = "*****";
		string remoteip = "ifconfig";
        jsch jsch = new jsch();
        try
        {
            session session = jsch.getsession(usrname, remoteip);
            session.setpassword(password);
            session.setconfig("stricthostkeychecking", "no");
            session.connect(100000);
            session.settimeout(15000);
            if (session.isconnected() == true)
            {
                system.out.println("host(" + remoteip + ") connected!");
            }

            channelexec channel = (channelexec) session.openchannel("exec");

            remoteexecute(session, cmd);

3.方法三

使用sshd-core,一直在更新

<dependency>
    <groupid>org.apache.sshd</groupid>
    <artifactid>sshd-core</artifactid>
    <version>2.8.0</version>
</dependency>
//sshconnection 是自定义的,包含username,pwd,hostname的实体类
 public static sshresponse runcommand(sshconnection conn, string cmd, long timeout)
            throws  ioexception {
        sshclient client = sshclient.setupdefaultclient();

        try {
            // open the client
            client.start();
            // connect to the server
            connectfuture cf = client.connect(conn.getusername(), conn.gethostname(), 22);
            clientsession session = cf.verify().getsession();
            session.addpasswordidentity(conn.getpassword());
            session.auth().verify(timeunit.seconds.tomillis(timeout));

            // create the exec and channel its output/error streams
            channelexec ce = session.createexecchannel(cmd);
            bytearrayoutputstream out = new bytearrayoutputstream();
            bytearrayoutputstream err = new bytearrayoutputstream();
            ce.setout(out);
            ce.seterr(err);
//       execute and wait
            ce.open();
            set<clientchannelevent> events =
                    ce.waitfor(enumset.of(clientchannelevent.closed), timeunit.seconds.tomillis(timeout));
            session.close(false);

//       check if timed out
            if (events.contains(clientchannelevent.timeout)) {
                throw new runtimeexception(conn.gethostname()+" 命令 "+cmd+ "执行超时 "+timeout);
            }
            return new sshresponse(out.tostring(), err.tostring(), ce.getexitstatus());

        } finally {
            client.stop();
        }
    }
    
      public static void main(string[] args) throws ioexception {
        string hostname = "*****";
        string username = "root";
        string pwd = "****";
        sshconnection  conn  = new sshconnection(username,pwd,hostname);
//    &&-表示前面命令执行成功在执行后面命令; ||表示前面命令执行失败了在执行后面命令; ";"表示一次执行两条命令
        string cmd = "pwd && ps  -ef|grep tomcat";
        sshresponse response = runcommand(conn,cmd,15);
        system.out.println("==error=>"+response.geterroutput());
        system.out.println("===return==>"+response.getreturncode());
        system.out.println("===stdout===>"+response.getstdoutput());
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com