java遠(yuǎn)程連接Linux執(zhí)行命令的3種方式完整代碼
更新時(shí)間:2024年06月07日 09:32:33 作者:凡客丶
在一些Java應(yīng)用程序中需要執(zhí)行一些Linux系統(tǒng)命令,例如服務(wù)器資源查看、文件操作等,這篇文章主要給大家介紹了關(guān)于java遠(yuǎn)程連接Linux執(zhí)行命令的3種方式,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
1. 使用JDK自帶的RunTime類(lèi)和Process類(lèi)實(shí)現(xiàn)
public static void main(String[] args){ Process proc = RunTime.getRunTime().exec("cd /home/tom; ls;") // 標(biāo)準(zhǔn)輸入流(必須寫(xiě)在 waitFor 之前) String inStr = consumeInputStream(proc.getInputStream()); // 標(biāo)準(zhǔn)錯(cuò)誤流(必須寫(xiě)在 waitFor 之前) String errStr = consumeInputStream(proc.getErrorStream()); int retCode = proc.waitFor(); if(retCode == 0){ System.out.println("程序正常執(zhí)行結(jié)束"); } } /** * 消費(fèi)inputstream,并返回 */ public static String consumeInputStream(InputStream is){ BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s ; StringBuilder sb = new StringBuilder(); while((s=br.readLine())!=null){ System.out.println(s); sb.append(s); } return sb.toString(); }
2. ganymed-ssh2 實(shí)現(xiàn)
pom
<!--ganymed-ssh2包--> <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210</version> </dependency>
import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; public static void main(String[] args){ String host = "210.38.162.181"; int port = 22; String username = "root"; String password = "root"; // 創(chuàng)建連接 Connection conn = new Connection(host, port); // 啟動(dòng)連接 conn.connection(); // 驗(yàn)證用戶(hù)密碼 conn.authenticateWithPassword(username, password); Session session = conn.openSession(); session.execCommand("cd /home/winnie; ls;"); // 消費(fèi)所有輸入流 String inStr = consumeInputStream(session.getStdout()); String errStr = consumeInputStream(session.getStderr()); session.close; conn.close(); } /** * 消費(fèi)inputstream,并返回 */ public static String consumeInputStream(InputStream is){ BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s ; StringBuilder sb = new StringBuilder(); while((s=br.readLine())!=null){ System.out.println(s); sb.append(s); } return sb.toString(); }
3. jsch實(shí)現(xiàn)
pom
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public static void main(String[] args){ String host = "210.38.162.181"; int port = 22; String username = "root"; String password = "root"; // 創(chuàng)建JSch JSch jSch = new JSch(); // 獲取session Session session = jSch.getSession(username, host, port); session.setPassword(password); Properties prop = new Properties(); prop.put("StrictHostKeyChecking", "no"); session.setProperties(prop); // 啟動(dòng)連接 session.connect(); ChannelExec exec = (ChannelExec)session.openChannel("exec"); exec.setCommand("cd /home/winnie; ls;"); exec.setInputStream(null); exec.setErrStream(System.err); exec.connect(); // 消費(fèi)所有輸入流,必須在exec之后 String inStr = consumeInputStream(exec.getInputStream()); String errStr = consumeInputStream(exec.getErrStream()); exec.disconnect(); session.disconnect(); } /** * 消費(fèi)inputstream,并返回 */ public static String consumeInputStream(InputStream is){ BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s ; StringBuilder sb = new StringBuilder(); while((s=br.readLine())!=null){ System.out.println(s); sb.append(s); } return sb.toString(); }
4. 完整代碼:
執(zhí)行shell命令
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210</version> </dependency>
import cn.hutool.core.io.IoUtil; import com.jcraft.jsch.ChannelShell; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Vector; /** * shell腳本調(diào)用類(lèi) * * @author Micky */ public class SshUtil { private static final Logger logger = LoggerFactory.getLogger(SshUtil.class); private Vector<String> stdout; // 會(huì)話session Session session; //輸入IP、端口、用戶(hù)名和密碼,連接遠(yuǎn)程服務(wù)器 public SshUtil(final String ipAddress, final String username, final String password, int port) { try { JSch jsch = new JSch(); session = jsch.getSession(username, ipAddress, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(100000); } catch (Exception e) { e.printStackTrace(); } } public int execute(final String command) { int returnCode = 0; ChannelShell channel = null; PrintWriter printWriter = null; BufferedReader input = null; stdout = new Vector<String>(); try { channel = (ChannelShell) session.openChannel("shell"); channel.connect(); input = new BufferedReader(new InputStreamReader(channel.getInputStream())); printWriter = new PrintWriter(channel.getOutputStream()); printWriter.println(command); printWriter.println("exit"); printWriter.flush(); logger.info("The remote command is: "); String line; while ((line = input.readLine()) != null) { stdout.add(line); System.out.println(line); } } catch (Exception e) { e.printStackTrace(); return -1; }finally { IoUtil.close(printWriter); IoUtil.close(input); if (channel != null) { channel.disconnect(); } } return returnCode; } // 斷開(kāi)連接 public void close(){ if (session != null) { session.disconnect(); } } // 執(zhí)行命令獲取執(zhí)行結(jié)果 public String executeForResult(String command) { execute(command); StringBuilder sb = new StringBuilder(); for (String str : stdout) { sb.append(str); } return sb.toString(); } public static void main(String[] args) { String cmd = "ls /opt/"; SshUtil execute = new SshUtil("XXX","abc","XXX",22); // 執(zhí)行命令 String result = execute.executeForResult(cmd); System.out.println(result); execute.close(); } }
下載和上傳文件
/** * 下載和上傳文件 */ public class ScpClientUtil { private String ip; private int port; private String username; private String password; static private ScpClientUtil instance; static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String passward) { if (instance == null) { instance = new ScpClientUtil(ip, port, username, passward); } return instance; } public ScpClientUtil(String ip, int port, String username, String passward) { this.ip = ip; this.port = port; this.username = username; this.password = passward; } public void getFile(String remoteFile, String localTargetDirectory) { Connection conn = new Connection(ip, port); try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (!isAuthenticated) { System.err.println("authentication failed"); } SCPClient client = new SCPClient(conn); client.get(remoteFile, localTargetDirectory); } catch (IOException ex) { ex.printStackTrace(); }finally{ conn.close(); } } public void putFile(String localFile, String remoteTargetDirectory) { putFile(localFile, null, remoteTargetDirectory); } public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) { putFile(localFile, remoteFileName, remoteTargetDirectory,null); } public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) { Connection conn = new Connection(ip, port); try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (!isAuthenticated) { System.err.println("authentication failed"); } SCPClient client = new SCPClient(conn); if ((mode == null) || (mode.length() == 0)) { mode = "0600"; } if (remoteFileName == null) { client.put(localFile, remoteTargetDirectory); } else { client.put(localFile, remoteFileName, remoteTargetDirectory, mode); } } catch (IOException ex) { ex.printStackTrace(); }finally{ conn.close(); } } public static void main(String[] args) { ScpClientUtil scpClient = ScpClientUtil.getInstance("XXX", 22, "XXX", "XXX"); // 從遠(yuǎn)程服務(wù)器/opt下的index.html下載到本地項(xiàng)目根路徑下 scpClient.getFile("/opt/index.html","./"); // 把本地項(xiàng)目下根路徑下的index.html上傳到遠(yuǎn)程服務(wù)器/opt目錄下 scpClient.putFile("./index.html","/opt"); } }
總結(jié)
到此這篇關(guān)于java遠(yuǎn)程連接Linux執(zhí)行命令的3種方式的文章就介紹到這了,更多相關(guān)java遠(yuǎn)程連接Linux執(zhí)行命令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot在idea下debug調(diào)試熱部署問(wèn)題
這篇文章主要介紹了springboot在idea下debug調(diào)試熱部署問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Map按單個(gè)或多個(gè)Value排序當(dāng)Value相同時(shí)按Key排序
Map可以先按照value進(jìn)行排序,然后按照key進(jìn)行排序。 或者先按照key進(jìn)行排序,然后按照value進(jìn)行排序,這樣操作都行,這篇文章主要介紹了Map按單個(gè)或多個(gè)Value排序,當(dāng)Value相同時(shí)按Key排序,需要的朋友可以參考下2023-02-02Java 靜態(tài)數(shù)據(jù)初始化的示例代碼
這篇文章主要介紹了Java 靜態(tài)數(shù)據(jù)初始化的示例代碼,幫助大家更好的理解和學(xué)習(xí)Java,感興趣的朋友可以了解下2020-09-09Mybatis中通用Mapper的InsertList()用法
文章介紹了通用Mapper中的insertList()方法在批量新增時(shí)的使用方式,包括自增ID和自定義ID的情況,對(duì)于自增ID,使用tk.mybatis.mapper.additional.insert.InsertListMapper包下的insertList()方法;對(duì)于自定義ID,需要重寫(xiě)insertList()方法2025-02-02一個(gè)簡(jiǎn)單的Spring容器初始化流程詳解
這篇文章主要給大家介紹了一個(gè)簡(jiǎn)單的Spring容器初始化流程的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01