.available()读取执行脚本输出不全面问题

项目场景:

用SSH工具类连接远程主机,进行执行脚本并读取输出信息。


问题描述:

读取执行脚本的输出信息时信息丢失,读取不全面。读取输出流的代码:

 while (in.available() > 0 && !isTimeout) {
     int i = in.read(tmp, 0, bytesRead);
     isTimeout = (System.currentTimeMillis() - start) > sysConfigOption.getTIMEOUT();
     if (i < 0 || isTimeout) {
         if (isTimeout) {
            sendMsg("执行已超时\n");
         }
             break;
                            }
                                         }

原因分析:

通过上述的代码可以分析出来:在未超时以及有输出流的情况下就能走if里面的代码从而得到输出流,所以我们把重点放在.available()方法上。

    /**
     * Returns an estimate of the number of bytes that can be read (or
     * skipped over) from this input stream without blocking by the next
     * invocation of a method for this input stream. The next invocation
     * might be the same thread or another thread.  A single read or skip of this
     * many bytes will not block, but may read or skip fewer bytes.
     *
     * <p> Note that while some implementations of {@code InputStream} will return
     * the total number of bytes in the stream, many will not.  It is
     * never correct to use the return value of this method to allocate
     * a buffer intended to hold all data in this stream.
     *
     * <p> A subclass' implementation of this method may choose to throw an
     * {@link IOException} if this input stream has been closed by
     * invoking the {@link #close()} method.
     *
     * <p> The {@code available} method for class {@code InputStream} always
     * returns {@code 0}.
     *
     * <p> This method should be overridden by subclasses.
     *
     * @return     an estimate of the number of bytes that can be read (or skipped
     *             over) from this input stream without blocking or {@code 0} when
     *             it reaches the end of the input stream.
     * @exception  IOException if an I/O error occurs.
     */
    public int available() throws IOException {
        return 0;
    }

从上述available的源码,可以知道available返回可读取的字节数的估计值,而不是流的总长度。当流中间停顿的时候返回为0,这时候并没有获得流的全部长度,因此也就会出现输出流不完全。


解决方案:

这种情况下,我们可以将available换成read方法。直接上代码:

while ((bytesRead = in.read(tmp, 0, 1024)) != -1 && !isTimeout) {
   String str = new String(tmp, 0, bytesRead);
   sendMsg(str);
   sb.append(str);
   logger.putMsg(Logger.INFO, str);
   isTimeout = (System.currentTimeMillis() - start) > sysConfigOption.getTIMEOUT();
       if (isTimeout) {
            break;
                    }
                                                              }

看下.read()源码:

 /**
     * Reads up to <code>len</code> bytes of data from the input stream into
     * an array of bytes.  An attempt is made to read as many as
     * <code>len</code> bytes, but a smaller number may be read.
     * The number of bytes actually read is returned as an integer.
     *
     * <p> This method blocks until input data is available, end of file is
     * detected, or an exception is thrown.
     *
     * <p> If <code>len</code> is zero, then no bytes are read and
     * <code>0</code> is returned; otherwise, there is an attempt to read at
     * least one byte. If no byte is available because the stream is at end of
     * file, the value <code>-1</code> is returned; otherwise, at least one
     * byte is read and stored into <code>b</code>.
     *
     * <p> The first byte read is stored into element <code>b[off]</code>, the
     * next one into <code>b[off+1]</code>, and so on. The number of bytes read
     * is, at most, equal to <code>len</code>. Let <i>k</i> be the number of
     * bytes actually read; these bytes will be stored in elements
     * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
     * leaving elements <code>b[off+</code><i>k</i><code>]</code> through
     * <code>b[off+len-1]</code> unaffected.
     *
     * <p> In every case, elements <code>b[0]</code> through
     * <code>b[off]</code> and elements <code>b[off+len]</code> through
     * <code>b[b.length-1]</code> are unaffected.
     *
     * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
     * for class <code>InputStream</code> simply calls the method
     * <code>read()</code> repeatedly. If the first such call results in an
     * <code>IOException</code>, that exception is returned from the call to
     * the <code>read(b,</code> <code>off,</code> <code>len)</code> method.  If
     * any subsequent call to <code>read()</code> results in a
     * <code>IOException</code>, the exception is caught and treated as if it
     * were end of file; the bytes read up to that point are stored into
     * <code>b</code> and the number of bytes read before the exception
     * occurred is returned. The default implementation of this method blocks
     * until the requested amount of input data <code>len</code> has been read,
     * end of file is detected, or an exception is thrown. Subclasses are encouraged
     * to provide a more efficient implementation of this method.
     *
     * @param      b     the buffer into which the data is read.
     * @param      off   the start offset in array <code>b</code>
     *                   at which the data is written.
     * @param      len   the maximum number of bytes to read.
     * @return     the total number of bytes read into the buffer, or
     *             <code>-1</code> if there is no more data because the end of
     *             the stream has been reached.
     * @exception  IOException If the first byte cannot be read for any reason
     * other than end of file, or if the input stream has been closed, or if
     * some other I/O error occurs.
     * @exception  NullPointerException If <code>b</code> is <code>null</code>.
     * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
     * <code>len</code> is negative, or <code>len</code> is greater than
     * <code>b.length - off</code>
     * @see        java.io.InputStream#read()
     */
    public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        int c = read();
        if (c == -1) {
            return -1;
        }
        b[off] = (byte)c;

        int i = 1;
        try {
            for (; i < len ; i++) {
                c = read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte)c;
            }
        } catch (IOException ee) {
        }
        return i;
    }

通过read源码,可以看出read是读取流的全部长度,从长度1开始读取,若流结束或遇到异常则返回-1。
因此我们可以得出,当遇到的输出流不稳定的时候,我们应该用read读取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 SNMP (Simple Network Management Protocol) 和 PySNMP 库来实现读取内存和 CPU 利用率的脚本。 以下是一个简单的示例: ``` from pysnmp.hlapi import * def get_cpu_utilization(): errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('192.168.1.100', 161)), ContextData(), ObjectType(ObjectIdentity('UCD-SNMP-MIB', 'laLoad')), lookupNames=True, lookupValues=True ) ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) def get_memory_utilization(): errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('192.168.1.100', 161)), ContextData(), ObjectType(ObjectIdentity('UCD-SNMP-MIB', 'memTotalReal')), ObjectType(ObjectIdentity('UCD-SNMP-MIB', 'memAvailReal')), lookupNames=True, lookupValues=True ) ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: total_memory = int(varBinds[0][1]) available_memory = int(varBinds[1][1]) utilization = (total_memory - available_memory) / total_memory * 100 print('Memory utilization:', utilization, '%') if __name__ == '__main__': get_cpu_utilization() get_memory_utilization() ``` 需要注意的是,您需要先确保目标设备支持 SNMP 协议,并且已配置了公共社区字符串。此外,需要在目标设备上安装 UCD-SNMP-MIB。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值