1、SSH登录及执行命令
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
public class sshForLinux {
public static Vector<String> exeCommand(String host, int port, String user, String password, String shell)
throws Exception {
Vector<String> stdout = new Vector<String>();
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
if (session == null) {
throw new Exception("session is null");
}
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
try{
session.connect(30000);
}catch (Exception e) {
throw new Exception("Invalid connection to remote port or wrong username and password!!!"+host+","+user+","+password);
}
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(shell);
channel.setInputStream(null);
BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
System.out.println("The remote shell is: " + shell);
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
}
input.close();
channel.disconnect();
session.disconnect();
return stdout;
}
}
2、实例(获取某文件夹下文件最后修改时间)

来源:CSDN
作者:Cupid???
链接:https://blog.csdn.net/qq_22902421/article/details/103769721