JSCH是SSH的一个纯Java实现。说直白点,就是一个远程连接你其他Linux或java代码者Unix服务器的一个包。其实就是我们使用jsch这个jar包来方便我们编写代码来连接自己linux系统的。
SSH:是目前较可靠,专为远程登录会话和其他网络服务提供安全性的协议。
在https://mvnrepository.com/这个地址先下载jsch的jar包。
范例:http://www.jcraft.com/jsch/examples/Exec.java.html
直接列出代码:
import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
/**
* java 使用jsch远程链接linux 执行命令
* @author Weikisa
*/
public class JSchUtil {
private static JSch jsch;//定义jsch连接类
private static Session session;
private static String user = "root";//Linux系统的用户名
private static String password = "password";//密码
private static String host = "ip";//測試IP,實際使用以輸入IP地址為准
/**
* 首先连接服务器
* @throws JSchException
*/
public static void connect(String hostIP) throws JSchException {
jsch = new JSch();//将jsch实例化
session = jsch.getSession(user, hostIP, 22);//默认端口号为22端口,使用用户名user连接IP
session.setPassword(password);//设置登录密码
session.setConfig("StrictHostKeyChecking", "no");//是否使用密钥登录,一般默认为no
session.connect(60 * 1000);
}
/**
* 连接服务器后执行相应的linux命令
* @param hostIp
* @param command
* @return
* @throws JSchException
*/
public boolean execCmd(String hostIp, String command) throws JSchException {
connect(hostIp);
BufferedReader reader = null;
Channel channel = null;
try{
while(command!=null){
channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
// PrintStream myerr = new PrintStream("/tmp/err");
// ((ChannelExec)channel).setErrStream(myerr);
((ChannelExec)channel).setErrStream(System.err);
//channel.setOutputStream(System.out, true); // 这条命令等同于 System.setOut(System.out);
System.setOut(System.out);
InputStream in = channel.getInputStream();
channel.connect(); //连接
byte[] tmp = new byte[1024];
while(true){
while(in.available() > 0) {
int i = in.read(tmp,0,1024);
if(i<0) break;
System.out.println(new String(tmp,0,i));
}
if(channel.isClosed()) {
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
if(channel.getExitStatus()!=0) {
return false;
}
break;
}
try{
Thread.sleep(1000);
}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("exec ok");
return true;
}
}catch(IOException e){
e.printStackTrace();
}catch (JSchException e) {
e.printStackTrace();
} finally {// 最后流和连接的关闭
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
main方法来进行测试:
import com.jcraft.jsch.JSchException;
public class JschDemo {
public static void main(String[] args) {
JSchUtil jschUtil = new JSchUtil();
///jschUtil.connectTest("10.xxxx");
try {
jschUtil.execCmd("10.xxx","cd /usr/ && ls");
} catch (JSchException e) {
e.printStackTrace();
}
}
}