由于項目需要,需要在項目中執(zhí)行SSH腳本,在網(wǎng)上找資料闹获,發(fā)現(xiàn)使用
有兩種方式可使用
1.使用ganymed-ssh2
<!--ssh2架包-->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
可以進行SSH的使用,包括遠程登錄河哑,執(zhí)行腳本命令等避诽,具體的Util包如下:
//定義一個連接
/**
*
* @Title: 連接Linux服務
* @Description: 通過用戶名和密碼關聯(lián)linux服務器
* @return
* @return String
* @throws
*/
public Connection connectLinux(String ip, String userName, String password) {
log.info("ConnectLinuxCommand scpGet===" + "ip:" + ip + " userName:" + userName + " commandStr:"
+ commandStr);
String returnStr = "";
boolean result = true;
RemoteConnect remoteConnect = new RemoteConnect();
remoteConnect.setIp(ip);
remoteConnect.setUserName(userName);
remoteConnect.setPassword(password);
try {
Connection conn=login(remoteConnect)
if (conn!=null) {
return conn;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @Title: login
* @Description: 用戶名密碼方式 遠程登錄linux服務器
* @return: Boolean
* @throws
*/
public Connection login(RemoteConnect remoteConnect) {
boolean flag = false;
try {
conn = new Connection(remoteConnect.getIp());
conn.connect();// 連接
flag = conn.authenticateWithPassword(remoteConnect.getUserName(), remoteConnect.getPassword());// 認證
if (flag) {
log.info("認證成功!");
return conn;
} else {
log.info("認證失斄Ы鳌沙庐!");
conn.close();
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
//此外,還可以使用證書登錄佳吞,再寫使用證書登錄的操作
/**
*
* @Title: execute
* @Description: 遠程執(zhí)行shll腳本或者命令
* @param conn 連接
* @param cmd 腳本命令
* @return: result 命令執(zhí)行完畢返回結果
* @throws
*/
public String execute(Connection conn, String cmd) {
String result = "";
try {
Session session = conn.openSession();// 打開一個會話
session.execCommand(cmd);// 執(zhí)行命令
result = processStdout(session.getStdout(), DEFAULTCHARTSET);
// 如果為得到標準輸出為空拱雏,說明腳本執(zhí)行出錯了
if (StringUtils.isBlank(result)) {
result = processStdout(session.getStderr(), DEFAULTCHARTSET);
}
conn.close();
session.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
RemoteConnect 的內容為:
import lombok.Data;
@Data
public class RemoteConnect {
private String ip;
private String userName;
private String password;
}
主要執(zhí)行的命令為創(chuàng)建防火墻規(guī)則或重啟一些指定的服務
測試命令為:
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx",
"firewall-cmd --zone=public --add-port=8850/tcp --permanent");
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx", "firewall-cmd --reload");
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx",
" firewall-cmd --zone=public --remove-port=8850/tcp --permanent ");
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx", "firewall-cmd --reload");
2.使用jsch
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
由于Hutool中已經(jīng)進行了封裝,因此直接使用Hutool操作即可底扳,但是沒有檢查為什么铸抑,必須要引入上面的jsch包之后才能用
Session session = JschUtil.createSession("192.168.xxx.xxx", YYY, "XXXX", "xxxxxxxxxxx");
JschUtil.exec(session, "firewall-cmd --zone=public --add-port=8850/tcp --permanent", null);
JschUtil.exec(session, "firewall-cmd --reload", null);
JschUtil.exec(session, " firewall-cmd --zone=public --remove-port=8850/tcp --permanent ", null);
JschUtil.exec(session, "firewall-cmd --reload", null);
至此兩種方式的使用,全部完成
可以使用免密登錄衷模,若生成的密鑰版本太高鹊汛,無法使用,可以使用
ssh-keygen -p -f id_rsa -m pem -P "" -N "" 更新密碼為可用情況
JSch jsch = new JSch();
try {
String pubKeyPath = "C:\\Users\\用戶名\\.ssh\\id_rsa";
jsch.addIdentity(pubKeyPath);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
try {
String username = "sss";
String host = "192.168.20.207";
Session session = jsch.getSession(username, host, 22);// 為了連接做準備
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// Channel channel=session.openChannel("shell");
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(" docker stats --no-stream --format "{{ json . }}" ");
//channel.setCommand(" cat /proc/stat | grep "cpu "");
//channel.setCommand("cat /proc/net/dev");
//channel.setCommand("df -lm");
// channel.setCommand("ps aux");
// channel.setInputStream(System.in);
// channel.setOutputStream(System.out);
// InputStream in=channel.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
String msg;
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
channel.disconnect();
session.disconnect();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}