package cn.com.ultrapower.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class JSCHUtilsTest {
public static void main(String[] args) throws JSchException {
setJschLog();
String username = "用户名";
String host = "ip地址";
int port = 22;
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
String userpwd = "密码";
session.setPassword(userpwd);
session.setConfig("StrictHostKeyChecking", "no");
//http://epaul.github.io/jsch-documentation/javadoc/
session.setConfig("PreferredAuthentications", "password");//password,publickey,keyboard-interactive
//不设置StrictHostKeyChecking=no,报错:UnknownHostKey: 192.168.10.209. RSA key fingerprint is 55:7e:b7:cb:fe:4b:78:f5:25:a5:73:29:a8:e0:63:1f
session.setTimeout(5* 1000);
session.connect(5* 1000);
/**
ChannelShell channel = (ChannelShell) session.openChannel("shell");
channel.connect(5 * 1000);
if (session.isConnected()) {
System.out.println(session.getHost());
}
channel.disconnect();
session.disconnect();
*/
ChannelExec channel = (ChannelExec) session.openChannel("exec");
//默认情况下,JSch 中的“exec”通道(正确)不会为会话分配伪终端 (PTY)。因此,(可能)提供了一组不同的启动脚本。
//最好是不要设置强制分配伪终端
//((ChannelExec)channel).setPty(true);
channel.setCommand("uname -a && date && uptime && echo $0 && w && echo \"umask=\"$(bash --login -c 'umask')");
// exec.setCommand("ifconfig"); //擦的,不知道啥原因ifconfig和ip add show执行结果都是空
channel.connect();
if(session.isConnected()) {
try {
InputStream inputStream = channel.getInputStream();
String result = IOUtils.toString(inputStream);
System.out.println("result : \n"+result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
channel.disconnect();
session.disconnect();
}
}
}
private static void setJschLog () {
com.jcraft.jsch.Logger JSCH_DEBUG = new com.jcraft.jsch.Logger() {
public boolean isEnabled(int level) { return true; }
public void log(int level, String message) { System.out.println(message); }
};
JSch.setLogger(JSCH_DEBUG);
}
}
使用JSCH库通过java代码连接sshd服务
最新推荐文章于 2024-03-22 13:58:03 发布