简介
项目中出现了一个监控小需求,采用了jcraft来实现一个远程登陆,脚本处理,记录一下简单的使用细节
maven依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
</dependencies>
LinuxShell
public class LinuxShell {
private Session session;
// 其他方法实现放别的章节分开展示
}
登陆
/**
* 远程登录
*
* @param host 主机ip
* @param port 端口号,默认22
* @param user 主机登录用户名
* @param password 主机登录密码
* @return
* @throws JSchException
*/
public void login(String host, int port, String user, String password) {
try {
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setPassword(password);
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 连接超时
session.connect(1000 * 10);
} catch (JSchException e) {
System.out.println("登录时发生错误!");
e.printStackTrace();
}
}
关闭
/**
* 关闭连接
*/
public void close() {
if (session.isConnected())
session.disconnect();
}
执行命令
/**
* 执行命令
*
* @param command
* @return
* @throws Exception
*/
public String executeShell(String command) throws Exception {
byte[] tmp = new byte[1024];
StringBuffer resultBuffer = new StringBuffer(); // 命令返回的结果
Channel channel = session.openChannel("exec");
ChannelExec exec = (ChannelExec) channel;
// 返回结果流(命令执行错误的信息通过getErrStream获取)
InputStream stdStream = exec.getInputStream();
exec.setCommand(command);
exec.connect();
try {
// 开始获得SSH命令的结果
while (true) {
while (stdStream.available() > 0) {
int i = stdStream.read(tmp, 0, 1024);
if (i < 0) break;
resultBuffer.append(new String(tmp, 0, i));
}
if (exec.isClosed()) {
// System.out.println(resultBuffer.toString());
break;
}
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
//关闭连接
channel.disconnect();
}
return resultBuffer.toString();
}
示例
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
String ip = args[0];
int port = Integer.valueOf(args[1]);
String username = args[2];
String password = args[3];
String process = args[4];
LinuxShell linux = new LinuxShell();
linux.login(ip, port, username, password);
// 简单执行一条指令
try {
String res = linux.executeShell("ls");
if (res != null) {
System.out.print(res);
}
}catch (Exception e){
e.printStackTrace();
}
linux.close();
}