• Java远程操作Linux服务器命令


    Java可以通过SSH协议远程连接Linux服务器,然后使用JSch库或者Apache Commons Net库来执行远程Linux命令。以下是一个使用JSch库的示例代码:

    1. import com.jcraft.jsch.*;
    2. public class RemoteCommandExecutor {
    3. private String host;
    4. private String user;
    5. private String password;
    6. public RemoteCommandExecutor(String host, String user, String password) {
    7. this.host = host;
    8. this.user = user;
    9. this.password = password;
    10. }
    11. public void executeCommand(String command) throws JSchException {
    12. JSch jsch = new JSch();
    13. Session session = jsch.getSession(user, host, 22); // 默认SSH端口号为22
    14. session.setConfig("StrictHostKeyChecking", "no"); // 不进行公钥验证
    15. session.setPassword(password);
    16. session.connect();
    17. ChannelExec channel = (ChannelExec) session.openChannel("exec");
    18. channel.setCommand(command);
    19. channel.setInputStream(null);
    20. channel.setErrStream(System.err);
    21. channel.connect();
    22. channel.disconnect();
    23. session.disconnect();
    24. }
    25. public static void main(String[] args) throws JSchException {
    26. RemoteCommandExecutor executor = new RemoteCommandExecutor("192.168.0.1", "username", "password");
    27. executor.executeCommand("ls -l");
    28. }
    29. }

    该示例通过构造方法传入服务器地址、用户名和密码,然后在executeCommand方法中执行传入的命令。在执行命令之前,需要建立一个SSH会话,并且打开一个执行命令的通道,最后关闭通道和会话。

    注意事项:

    1. 需要在项目中引入JSch库和其依赖的JZlib库。
    2. 如果需要传递参数,需要将参数用单引号或双引号括起来。
    3. 执行命令时,需要保证Linux服务器上已经安装需要执行的命令及其依赖的程序或库文件。
  • 相关阅读:
    centos7部署ds
    Vue3 封装 Element Plus Menu 无限级菜单组件
    出纳商铺如何实施数字员工提高投资回报率
    SMTP协议浅析
    MyBatisPlus(六)字段映射 @TableField
    Tableau3——文本表,树形图,词云图
    【带RL负载的全波桥式整流器】功能齐全的单相非控整流器(Simulink)
    为什么建议你做自动化邮件营销?
    Android dumpsys 常用命令
    突破大O(N的平方)的排序
  • 原文地址:https://blog.csdn.net/m0_37649480/article/details/134428885