ssh工具 (Java)
生活随笔
收集整理的這篇文章主要介紹了
ssh工具 (Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
執行shell命令、下載文件...
package com.sunsheen.blockchain.admin.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import org.apache.http.util.Asserts;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.sunsheen.blockchain.admin.common.ServersConstant;
public class SSHUtil {
/**
* 連接服務器
* @param host
* @param user
* @param pwd
* @return
* @throws JSchException
*/
public static synchronized Session connect(String host,String user,String pwd) throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
session.setPassword(pwd);
session.connect();
return session;
}
/**
* 執行命令集
* @param session
* @param cmds
* @return
* @throws IOException
* @throws JSchException
*/
public static String execCommandByShell(Session session,String[] cmds)
throws IOException, JSchException {
String result = "";
// 2.嘗試解決 遠程ssh只能執行一句命令的情況
ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
InputStream inputStream = channelShell.getInputStream();// 從遠端到達的數據都能從這個流讀取到
channelShell.setPty(true);
channelShell.connect();
OutputStream outputStream = channelShell.getOutputStream();// 寫入該流的數據
// 都將發送到遠程端
// 使用PrintWriter 就是為了使用println 這個方法
// 好處就是不需要每次手動給字符加
PrintWriter printWriter = new PrintWriter(outputStream);
for (String cmd:cmds) {
printWriter.println(cmd);
}
printWriter.println("exit");// 為了結束本次交互
printWriter.flush();// 把緩沖區的數據強行輸出
return result;
}
/**
* 單個文件上傳
* @param file 上傳的文件
* @param remoteFolder 服務器上存放當前文件的文件夾
* @param uploadFileName 上傳文件的名字
*/
public static void postFile(InputStream fileStream,String remoteFolder,String uploadFileName) throws Exception{
//上傳文件的個數應該跟對應文件夾相同
if((null==fileStream || null==remoteFolder))
return;
String username = ServersConstant.USERNAME;
String password = ServersConstant.PASSWORD;
String address = ServersConstant.ADDRES;
int port = ServersConstant.PORT;
ChannelSftp sftp = null;
Channel channel = null;
Session sshSession = null;
try {
//創建連接
JSch jsch = new JSch();
sshSession = jsch.getSession(username, address, port);
sshSession.setPassword(password);
//獲取session
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
//得到sftp
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
sftp.cd(remoteFolder);//進入對應存放日志文件的目錄
sftp.put(fileStream, uploadFileName);//寫入文件
} finally {
//關閉sftp信道
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
//關閉channel管道
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
//關閉session
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
}
}
/**
* 轉換指令到服務器執行
* @param command 要執行的指令
*/
public static void transferCommand(String... commands){
String romoteAddr = ServersConstant.ADDRES;
String username = ServersConstant.USERNAME;
String password = ServersConstant.PASSWORD;
try {
Connection connection = new Connection(romoteAddr);// 創建一個連接實例
connection.connect();// Now connect
boolean isAuthenticated = connection.authenticateWithPassword(username, password);//認證
Asserts.check(isAuthenticated, "用戶名或密碼錯誤!");
ch.ethz.ssh2.Session sess = connection.openSession();// 創建一個會話
sess.requestPTY("bash");
sess.startShell();
InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
//向服務器上輸入命令
PrintWriter out = new PrintWriter(sess.getStdin());
for(String command : commands){
out.println(command);
}
out.close();
sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,100);
//關閉連接
sess.close();
connection.close();
stderrReader.close();
stdoutReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 下載指定文件到本地指定文件夾oo
* @param serversFolder 服務器文件所在目錄 /opt/log
* @param fileName 需要下載的文件名 monitor.log
* @param localFolder 本地存放文件的文件夾 d:\logs
*/
public static void download(String serversFolder,String fileName,String localFolder) {
String username = ServersConstant.USERNAME;
String password = ServersConstant.PASSWORD;
String address = ServersConstant.ADDRES;
int port = ServersConstant.PORT;
ChannelSftp sftp = null;
Channel channel = null;
Session sshSession = null;
try {
// 創建連接
JSch jsch = new JSch();
sshSession = jsch.getSession(username, address, port);
sshSession.setPassword(password);
// 獲取session
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
// 得到sftp
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
// 進入服務器文件夾
sftp.cd(serversFolder);
//創建本地文件夾
File downloadFile = new File(localFolder);
if(!downloadFile.exists())
downloadFile.mkdirs();
// 下載
String serversFile = serversFolder +"/"+ fileName;
sftp.get(serversFile,localFolder);
System.out.println(fileName+"已下載到:"+localFolder);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉sftp信道
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
// 關閉channel管道
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
// 關閉session
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
}
}
}
總結
以上是生活随笔為你收集整理的ssh工具 (Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML 表格垂直对齐方式
- 下一篇: STM32 VBAT引脚悬空 可以么?