使用JSCH连接Linux服务器(1)-执行linux命令
Linux  /  houtizong 发布于 3年前   228
package com.aliyun.utility.jsch;import java.io.InputStream;import java.util.Properties;import com.jcraft.jsch.ChannelExec;import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;public class JSCHUtil {private static JSCHUtil instance;public static JSCHUtil getInstance() {if (instance == null) {instance = new JSCHUtil();}return instance;}private JSCHUtil() {}private Session getSession(String host, int port, String ueseName)throws Exception {JSch jsch = new JSch();Session session = jsch.getSession(ueseName, host, port);return session;}public Session connect(String host, int port, String ueseName,String password) throws Exception {Session session = getSession(host, port, ueseName);session.setPassword(password);Properties config = new Properties();config.setProperty("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();return session;}public String execCmd(Session session, String command) throws Exception {if (session == null) {throw new RuntimeException("Session is null!");}ChannelExec exec = (ChannelExec) session.openChannel("exec");InputStream in = exec.getInputStream();byte[] b = new byte[1024];exec.setCommand(command);exec.connect();StringBuffer buffer = new StringBuffer();while (in.read(b) > 0) {buffer.append(new String(b));}exec.disconnect();return buffer.toString();}public void clear(Session session) {if (session != null && session.isConnected()) {session.disconnect();session = null;}}public static void main(String[] args) throws Exception {Session session = JSCHUtil.getInstance().connect("10.9.9.135", 22,"yy", "yy");String cmd = "cd /" + ";" + "ls -al |grep home";String result = JSCHUtil.getInstance().execCmd(session, cmd);// 多条命令之间以;分隔System.out.println(result);System.exit(0);}}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接