已复制
全屏展示
复制代码

Java远程执行linux命令总结

· 1 min read

注意事项

  • 执行的命令不要用 ; & 拼接多条命令
  • 执行的命令参数如果有空格,需要注意测试,空格对命令行解析有一定的误差。

pom依赖

<dependency>
  <groupId>org.apache.sshd</groupId>
  <artifactId>sshd-core</artifactId>
  <version>2.1.0</version>
</dependency>

Java源码

package org.example;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;

import java.io.ByteArrayOutputStream;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

class Main {
    public static void main(String[] args) throws Exception {
        String command = "ls /";
        runx("yzy", "9090", "localhost", 22, 3000, command);
    }

    public static void runx(String username, String password,
                            String host, int port, long defaultTimeoutSeconds, String command) throws Exception {

        SshClient client = SshClient.setUpDefaultClient();

        try {
            // Open the client
            client.start();

            // Connect to the server
            ConnectFuture cf = client.connect(username, host, 22);
            ClientSession session = cf.verify().getSession();
            
            // 密码模式
            session.addPasswordIdentity(password);
            
            // 密钥模式
            String resourceKey = "/Users/yzy/.ssh/id_rsa";
            FileInputStream is = new FileInputStream(resourceKey);
            KeyPair keyPair = SecurityUtils.loadKeyPairIdentity(resourceKey, is, null);
            session.addPublicKeyIdentity(keyPair);
            
            
            session.auth().verify(TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));

            ChannelExec ce = session.createExecChannel(command);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayOutputStream err = new ByteArrayOutputStream();
            ce.setOut(out);
            ce.setErr(err);

            // Execute and wait
            ce.open();
            Set<ClientChannelEvent> events =
                    ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));
            session.close(false);

            // Check if timed out
            if (events.contains(ClientChannelEvent.TIMEOUT)) {
                System.out.println("timeout...");
            }

            System.out.println("out:" + out.toString());
            System.out.println("err:" + err.toString());
            System.out.println("code:" + ce.getExitStatus());

        } finally {
            client.stop();
        }
    }
}
🔗

文章推荐