1.解決什麼問題:代碼在118服務器上,shell腳本在119服務器上。118代碼調用shell腳本。
2.其它問題:如果代碼和腳本在同一服務器上,簡單多了。
移步:https://blog.csdn.net/vcfriend/article/details/81226632
思路:因爲shell腳本在119上,所以要連接119服務器纔行。用到了了jcraft依賴,去maven庫搜索一下,加進來。
main方法教你如何調用
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* java 登錄linux系統,並讀取執行shell命令結果
* @author zyb
* 2020-07-06
*/
public class LinuxShell {
private static Logger log = LoggerFactory.getLogger(LinuxShell.class);
private static Session session;
/**
* 遠程登錄
* @param host 主機ip
* @param port 端口號,默認22
* @param user 主機登錄用戶名
* @param password 主機登錄密碼
* @return
* @throws JSchException
*/
public static 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) {
log.info("登錄時發生錯誤!");
e.printStackTrace();
}
}
/**
* 執行shell腳本
* @param command shell命令腳本
* @return
* @throws Exception
*/
public static 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();
}
/**
* 關閉連接
*/
public static void close() {
if (session.isConnected())
session.disconnect();
}
/**
* 測試
* @param args
*/
public static void main(String[] args) {
String ip="192.168.1.119";
String username="用戶名";
String password="密碼";
LinuxShell linux = new LinuxShell();
linux.login(ip, 22, username,password);
//要執行的腳本命令
String command = "sh /dir/test/aaa_do.sh ";
try {
String result = linux.executeShell(command);
System.out.println(result);
linux.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}