java實(shí)現(xiàn)ssh登錄linux并執(zhí)行命令的三種實(shí)現(xiàn)方式
java實(shí)現(xiàn)ssh登錄linux并執(zhí)行命令
1.方法一
使用ganymed-ssh2
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>但是這個(gè)包最新版本是2014年之后,就沒有更新了,linux 操作系統(tǒng)安裝 open-ssh 8.5及更高級版本,就一直提示連接失敗。就不再提供demo
2.方法二
jsch 暫時(shí)能使用,也是很久沒有更新了,恐怕后續(xù)也會(huì)有無法匹配系統(tǒng)最新協(xié)議的問題。
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>public class RemoteExecuteCommand {
public static List<String> remoteExecute(Session session, String command)
{
System.out.println("CMD:" + command);
List<String> resultLines = new ArrayList<>();
ChannelExec channel = null;
try
{
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
InputStream input = channel.getInputStream();
channel.connect(50000);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
String inputLine = null;
while ((inputLine = inputReader.readLine()) != null)
{
System.out.println(inputLine);
resultLines.add(inputLine);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
System.out.println("最后關(guān)閉channel");
channel.disconnect();
}
return resultLines;
}
}
String usrName = "root";
String passWord = "******";
String remoteIP = "*****";
String remoteIP = "ifconfig";
JSch jSch = new JSch();
try
{
Session session = jSch.getSession(usrName, remoteIP);
session.setPassword(passWord);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(100000);
session.setTimeout(15000);
if (session.isConnected() == true)
{
System.out.println("Host(" + remoteIP + ") connected!");
}
ChannelExec channel = (ChannelExec) session.openChannel("exec");
remoteExecute(session, cmd);
3.方法三
使用sshd-core,一直在更新
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>2.8.0</version>
</dependency>//SshConnection 是自定義的,包含userName,pwd,hostName的實(shí)體類
public static SshResponse runCommand(SshConnection conn, String cmd, long timeout)
throws IOException {
SshClient client = SshClient.setUpDefaultClient();
try {
// Open the client
client.start();
// Connect to the server
ConnectFuture cf = client.connect(conn.getUsername(), conn.getHostname(), 22);
ClientSession session = cf.verify().getSession();
session.addPasswordIdentity(conn.getPassword());
session.auth().verify(TimeUnit.SECONDS.toMillis(timeout));
// Create the exec and channel its output/error streams
ChannelExec ce = session.createExecChannel(cmd);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
ce.setOut(out);
ce.setErr(err);
// Execute and wait
ce.open();
Set<ClientChannelEvent> events =
ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
session.close(false);
// Check if timed out
if (events.contains(ClientChannelEvent.TIMEOUT)) {
throw new RuntimeException(conn.getHostname()+" 命令 "+cmd+ "執(zhí)行超時(shí) "+timeout);
}
return new SshResponse(out.toString(), err.toString(), ce.getExitStatus());
} finally {
client.stop();
}
}
public static void main(String[] args) throws IOException {
String hostName = "*****";
String userName = "root";
String pwd = "****";
SshConnection conn = new SshConnection(userName,pwd,hostName);
// &&-表示前面命令執(zhí)行成功在執(zhí)行后面命令; ||表示前面命令執(zhí)行失敗了在執(zhí)行后面命令; ";"表示一次執(zhí)行兩條命令
String cmd = "pwd && ps -ef|grep tomcat";
SshResponse response = runCommand(conn,cmd,15);
System.out.println("==error=>"+response.getErrOutput());
System.out.println("===return==>"+response.getReturnCode());
System.out.println("===stdOut===>"+response.getStdOutput());
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java Elastic Job動(dòng)態(tài)添加任務(wù)實(shí)現(xiàn)過程解析
這篇文章主要介紹了Java Elastic Job動(dòng)態(tài)添加任務(wù)實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
interrupt()和線程終止方式_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
線程的thread.interrupt()方法是中斷線程,將會(huì)設(shè)置該線程的中斷狀態(tài)位,即設(shè)置為true,中斷的結(jié)果線程是死亡、還是等待新的任務(wù)或是繼續(xù)運(yùn)行至下一步,就取決于這個(gè)程序本身2017-05-05
SWT(JFace)體驗(yàn)之圓環(huán)狀(戒指型)
SWT(JFace)體驗(yàn)之圓環(huán)狀(戒指型)實(shí)現(xiàn)代碼。2009-06-06
Java實(shí)現(xiàn)數(shù)據(jù)脫敏(Desensitization)的操作指南
數(shù)據(jù)脫敏是指通過對敏感數(shù)據(jù)進(jìn)行部分或完全隱藏處理,保護(hù)敏感信息在存儲(chǔ)和使用過程中的安全性,常見的應(yīng)用場景包括日志記錄、接口返回、報(bào)表展示、數(shù)據(jù)分析等,本文給大家介紹了Java實(shí)現(xiàn)數(shù)據(jù)脫敏(Desensitization)的操作指南,需要的朋友可以參考下2025-02-02
springMVC?@RestControllerAdvice注解使用方式
這篇文章主要介紹了springMVC?@RestControllerAdvice注解使用方式,下面通過一個(gè)簡單的示例,演示如何使用?@RestControllerAdvice,感興趣的朋友跟隨小編一起看看吧2024-08-08
SpringBoot中的@PostConstruct注解詳細(xì)解析
這篇文章主要介紹了SpringBoot中的@PostConstruct注解詳細(xì)解析,@PostConstruct注解,主要用于在Spring容器啟動(dòng)時(shí)執(zhí)行某些操作或者任務(wù),@PostConstruct注解一般放在BEAN的方法上,一旦BEAN初始化完成之后,將會(huì)調(diào)用這個(gè)方法,需要的朋友可以參考下2024-01-01
java多線程join()方法的作用和實(shí)現(xiàn)原理解析(應(yīng)用場景)
join方法主要是用于將當(dāng)前線程掛起,等待其他線程結(jié)束后在執(zhí)行當(dāng)前線程,本文通過應(yīng)用場景分析代碼示例講解java多線程join()方法的作用和實(shí)現(xiàn)原理,感興趣的朋友一起看看吧2021-07-07

