记得先引入依赖:
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
利用JSch工具远程操作linux,下面这个是shell类型的,还有exec和sftp的类型,后续再补充
具体代码如下:
public class SshUtil {
private static final Logger logger = LoggerFactory.getLogger(SshUtil.class);
private Vector<String> stdout;
// 会话session
Session session;
//输入IP、端口、用户名和密码,连接远程服务器
public SshUtil(final String ipAddress, final String username, final String password, int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(100000);
} catch (Exception e) {
e.printStackTrace();
}
}
public int execute(final ArrayList<String> cmds) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
for (int i = 0; i < cmds.size(); i++) {
printWriter.println(cmds.get(i));
}
printWriter.println("exit");
printWriter.flush();
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
logger.info("The remote command is: " + line);
}
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally {
printWriter.close();
try {
input.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
// 断开连接
public void close(){
if (session != null) {
session.disconnect();
}
}
// 执行命令获取执行结果
public String executeForResult(ArrayList<String> cmds) {
execute(cmds);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
}
return sb.toString();
}
public static void main(String[] args) {
ArrayList<String> cmds = new ArrayList<>();
SshUtil execute = new SshUtil("192.168.86.150","root","123456",22);
// 执行命令
cmds.add("su - dmdba");
cmds.add("cd /dm8/dmhs/bin");
cmds.add("./DmhsService start");
cmds.add("./DmhsService stop");
cmds.add("exit");
String result = execute.executeForResult(cmds);
System.out.println(result);
execute.close();
}
}