ssh连接服务器

ssh连接服务器

使用的jar包
<!-- ssh连接服务器 -->
<dependency>
    <groupId>com.jcraft</groupId>
	<artifactId>jsch</artifactId>
	<version>0.1.54</version>
</dependency>
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>
demo
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

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

/**
 * @author liull
 * @date 2019/12/4 09:43
 * @description ssh连接Linux服务器
 */
public class SSHLinux {
    private static final Logger logger = Logger.getLogger(SSHLinux.class);

    private static final String ENCODING = "UTF-8";
    private static final int TIME_OUT = 2 * 60 * 100;

    /**
     * 连接服务器并执行命令
     *
     * @param host     主机ip
     * @param port     端口
     * @param username 登录名
     * @param password 登录密码
     * @param command  需要执行的命令
     * @return 执行之后的结果
     * @throws JSchException
     * @throws IOException
     */
    public static String exeCommand(String host, int port, String username, String password, String command)
            throws JSchException, IOException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        // java.util.Properties config = new java.util.Properties();
        // config.put("StrictHostKeyChecking", "no");
        session.setTimeout(TIME_OUT);
        session.setPassword(password);
        System.out.println("尝试连接服务器:host=" + host + ",username=" + username);
        session.connect();

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);//如果命令错误,则返回错误信息。

        channelExec.connect();
        String out = IOUtils.toString(in, ENCODING);

        channelExec.disconnect();
        session.disconnect();
        return out;
    }

    // 测试
    public static void main(String[] args) {
        String host = "11.111.111.1";
        int port = 22;
        String username = "root";
        String password = "******";
        String command = "/usr/local/test/test.sh";
        String res = null;
        try {
            res = exeCommand(host, port, username, password, command);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(res);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值