ssh连接服务器
使用的jar包
<!-- ssh连接服务器 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
demo
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* @author liull
* @date 2019/12/4 09:43
* @description ssh连接Linux服务器
*/
public class SSHLinux {
private static final Logger logger = Logger.getLogger(SSHLinux.class);
private static final String ENCODING = "UTF-8";
private static final int TIME_OUT = 2 * 60 * 100;
/**
* 连接服务器并执行命令
*
* @param host 主机ip
* @param port 端口
* @param username 登录名
* @param password 登录密码
* @param command 需要执行的命令
* @return 执行之后的结果
* @throws JSchException
* @throws IOException
*/
public static String exeCommand(String host, int port, String username, String password, String command)
throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
session.setTimeout(TIME_OUT);
session.setPassword(password);
System.out.println("尝试连接服务器:host=" + host + ",username=" + username);
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, ENCODING);
channelExec.disconnect();
session.disconnect();
return out;
}
// 测试
public static void main(String[] args) {
String host = "11.111.111.1";
int port = 22;
String username = "root";
String password = "******";
String command = "/usr/local/test/test.sh";
String res = null;
try {
res = exeCommand(host, port, username, password, command);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(res);
}
}