簡介
項目中出現了一個監控小需求,採用了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();
}