########自己执行成功的代码###########
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class java2Shell {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
##############shell.properties文件内容在代码下方#################
properties.load(java2Shell.class.getClassLoader().getResourceAsStream("shell.properties"));
String host = properties.getProperty("HOST");
String user = properties.getProperty("USER");
String pwd = properties.getProperty("PWD");
String ports = properties.getProperty("PORT");
int port = Integer.parseInt(ports);
String command = properties.getProperty("COMMAND");
String exec = exec(host,user,pwd,port,command);
System.out.println("获得执行结果:" + exec);
}
public static String exec(String host,String user,String pwd,int port,String command){
StringBuffer sb = new StringBuffer();
Session session = null;
ChannelExec openChannel = null;
JSch jSch = new JSch();
try {
session = jSch.getSession(user,pwd,port);
Properties config = new Properties();
config.put("StrictHostKeyChecking","no"); //跳过公钥的询问
session.setConfig(config);
session.setPassword(pwd);
session.connect(5000); //设置连接的超时时间
openChannel = (ChannelExec) session.openChannel("exec");
openChannel.setCommand(command); //执行命令
int exitStatus = openChannel.getExitStatus(); //退出状态为-1,直到通道关闭
System.out.println(exitStatus);
//下面是得到的内容
openChannel.connect();
InputStream in = openChannel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String buf = null;
while((buf = reader.readLine()) != null){
sb.append(buf + "\n");
System.out.println(buf);
}
} catch (JSchException | IOException e) {
sb.append(e.getMessage() + "\n");
}finally {
if(openChannel != null && !openChannel.isConnected()){
openChannel.disconnect();
}
if(session != null && session.isConnected()){
session.disconnect();
}
}
return sb.toString();
}
}
##########shell.properties文件内容###########
HOST=XXX USER=XXX PWD=XXX PORT=XXX COMMAND=cat /xx/xx.txt

本文介绍了一种使用Java通过SSH协议远程执行Shell命令的方法。通过JSch库,可以实现与远程服务器的安全连接,执行指定的Shell命令并获取执行结果。文章详细展示了如何加载配置信息,建立SSH会话,执行命令并读取输出。
7万+

被折叠的 条评论
为什么被折叠?



