<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SSHLinux {
public static void main(String[] args) throws IOException, JSchException {
// TODO Auto-generated method stub
String host = "172.19.28.253";
int port = 22;
String user = "root";
String password = "123456";
String command = "whatweb --output-xml http://216.139.147.75:443/";
String res = exeCommand(host,port,user,password,command);
System.out.println(res);
}
public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect();
String out = IOUtils.toString(in, "UTF-8");
channelExec.disconnect();
session.disconnect();
return out;
}
}
参考资料:
1、java使用ssh连接Linux并执行命令
https://blog.csdn.net/angel_xiaa/article/details/52355625
2、Java通过SSH连接Linux服务器
https://blog.csdn.net/u014234061/article/details/51445540
3、Java实践 — SSH远程执行Shell脚本
https://blog.csdn.net/jmyue/article/details/14003783