使用 JSch 从 SSH 服务器读取命令输出时获取不需要的字符

Getting unwanted characters when reading command output from SSH server using JSch

我正在连接到远程服务器 SSH 服务器并尝试获取特定路径中的文件列表我能够获取路径中的文件列表但它们的格式不可读任何人都可以帮助解决这个问题

String host="xxxxx.yyyy.com";
String user="user";
String password="password";
String command1="dzdo su - lucy";
try{    
    java.util.Properties config = new java.util.Properties(); 
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(password);
    session.setConfig(config);
    session.connect();
    System.out.println("Connected");

    Channel channel=session.openChannel("shell");
    OutputStream ops = channel.getOutputStream();
    PrintStream ps = new PrintStream(ops, true);

    channel.connect();
    ps.println(command1);
    ps.println("ls -ltr");
    InputStream in=channel.getInputStream();
    byte[] tmp=new byte[1024];
    while(true){
        while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
        }
        if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
        }
        try{Thread.sleep(1000);}catch(Exception ee){}
    }
    channel.disconnect();
    session.disconnect();
    System.out.println("DONE");

这是控制台输出

drwxrws---. 2 gleaiid gleai 4096 Jan 21  2016 [0m[01;34mold[0m
-rwxrws---. 1 jhon gleai  100 Jul 20  2017 [30;43mNVISAP_814_Test.txt[0m
-rwxrws---. 1 jhon  gleai  134 Jul 20  2017 [30;43mUS_NISC14_4164556_Test.txt[0m
-rwxrws---. 1 jhon  gleai    0 Jul 20  2017 [30;43mNVISAP_R00814_Test.trg[0m

这些 ANSI escape codes 通常由终端客户端解释为漂亮的 [color] 打印输出。

如果服务器配置正确,您只会在使用交互式终端时获得这些。换句话说,如果您为会话请求了 pseudo terminal(如果您要使会话自动化,则不应该这样做)。

如果您使用 "shell" 通道,JSch 会自动请求伪终端,因为它应该用于实现交互式终端。

  • 如果自动执行远程命令,最好使用 "exec" 通道,如 JSch Exec.java example.

  • 所示
  • 或者,您可以通过调用 setPty. But I do not recommend using "shell" channel. Though if you need to, for whatever reason, you should call setPty(false) in any case, as that will prevent many other similar troubles. I actually already recommended that to you in .

  • 来阻止 JSch 请求伪终端

其他人注意:虽然我明白为什么 OP 使用 ls 命令,但一般来说,应该使用 SFTP API to retrieve a directory listing,而不是执行 ls 并解析其输出。解析 ls 输出是一种非常不可靠的方法。


相关问题:

  • Removing shell stuff (like prompts) from command output in JSch

创建频道后,可以设置伪终端类型为“dumb”

ChannelShell channel = (ChannelShell) session.openChannel("shell");
channel.setPtyType("dumb");