java linux ssh工具類


1. maven 配置
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

2.代碼

import java.io.IOException;
import java.io.InputStream;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;


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


public class SSHUtils {
final static String user = "root";// 用戶名
final static String pwd = "131420.com";// 密碼
final static String ip = "47.107.168.139";// 服務器地址
final static int port = 22;// 端口號
final static int timeout = 60000000;

public static void main(String[] args) throws Exception {
//查看文件個數

String commond = "free";

String ls = SSHUtils.execCommandByJSch(ip, port,user, pwd,commond);

System.out.println(ls);
}


private static final String ENCODING = "UTF-8";
//private static final int timeout = 60 * 60 * 1000;
private static final int defaultPort = 22;


public static Session getJSchSession(String ip, int port, String user, String pwd, int timeout) throws JSchException {
JSch jsch = new JSch();

Session session = jsch.getSession(user, ip, port);
session.setPassword(pwd);
session.setConfig("StrictHostKeyChecking", "no"); // 第一次訪問服務器時不用輸入yes
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.setTimeout(timeout);
session.connect();

return session;
}

public static String execCommandByJSch(String ip, String user, String pwd, String command) throws IOException, JSchException {
return execCommandByJSch(ip, defaultPort, user, pwd, timeout, command, ENCODING);
}

public static String execCommandByJSch(String ip, int port, String user, String pwd, String command) throws IOException, JSchException {
return execCommandByJSch(ip, port, user, pwd, timeout, command, ENCODING);
}

public static String execCommandByJSch(String ip, int port, String user, String pwd, int timeout, String command, String resultEncoding) throws IOException, JSchException {
Session session = getJSchSession(ip, port, user, pwd, timeout);
String result = execCommandByJSch(session, command, resultEncoding);
session.disconnect();

return result;
}

public static String execCommandByJSch(Session session, String command) throws IOException, JSchException {
return execCommandByJSch(session, command, ENCODING);
}

public static String execCommandByJSch(Session session, String command, String resultEncoding) throws IOException, JSchException {
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect();

String result = IOUtils.toString(in, resultEncoding);

channelExec.disconnect();

return result;
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM