91av视频/亚洲h视频/操亚洲美女/外国一级黄色毛片 - 国产三级三级三级三级

資源簡介

使用jcraft jar包登錄linux系統,并讀取執行shell命令結果,含jcraft jar包和java實例代碼。

資源截圖

代碼片段和文件信息

package?linux;

import?java.io.InputStream;

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

/**
?*?java?登錄linux系統,并讀取執行shell命令結果
?*?@author?wanghonggang
?*?2018-10-30
?*/
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?userString?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();
}
}

/**
?*?執行shell腳本
?*?@param?command?shell命令腳本
?*?@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? 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();
}

/**
?*?關閉連接
?*/
public?void?close()?{
if?(session.isConnected())
session.disconnect();
}

/**
?*?測試
?*?@param?args
?*/
public?static?void?main(String[]?args)?{

String?ip=“192.168.1.168“;
String?username=“whg“;
String?password=“whg“;

LinuxShell?linux?=?new?LinuxShell();

linux.login(ip?22?usernamepassword);
String?command?=?“df?-h“;
try?{
String?result?=?linux.executeShell(command);
System.out.println(result);
linux.close();
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
}

?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件??????280515??2018-10-30?10:42??jsch-0.1.54.jar
?????文件????????2788??2018-10-30?13:54??LinuxShell.java

評論

共有 條評論