java實現(xiàn)ssh登錄linux并執(zhí)行命令的三種實現(xiàn)方式
java實現(xiàn)ssh登錄linux并執(zhí)行命令
1.方法一
使用ganymed-ssh2
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>但是這個包最新版本是2014年之后,就沒有更新了,linux 操作系統(tǒng)安裝 open-ssh 8.5及更高級版本,就一直提示連接失敗。就不再提供demo
2.方法二
jsch 暫時能使用,也是很久沒有更新了,恐怕后續(xù)也會有無法匹配系統(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的實體類
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í)行超時 "+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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決SpringBoot web項目啟動后立即關(guān)閉的問題
這篇文章主要介紹了解決SpringBoot web項目啟動后立即關(guān)閉的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Spring?Boot?集成Redisson實現(xiàn)分布式鎖詳細(xì)案例
這篇文章主要介紹了Spring?Boot?集成Redisson實現(xiàn)分布式鎖詳細(xì)案例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-08-08
Java synchronized 鎖的 8 個經(jīng)典問題小結(jié)
本文通過8個實驗探討Java中synchronized關(guān)鍵字的不同鎖機制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2026-02-02
spring?boot?實現(xiàn)一個?禁止重復(fù)請求的方法
這篇文章主要介紹了spring?boot?實現(xiàn)一個?禁止重復(fù)請求,當(dāng)重復(fù)請求該方法時,會返回"Duplicate?request",避免重復(fù)執(zhí)行相同的操作,需要的朋友可以參考下2024-03-03

