【问题标题】:paramiko stdout show nothing with regular expression?paramiko stdout 不显示正则表达式?
【发布时间】:2013-07-27 03:45:31
【问题描述】:

我尝试使用 paramiko 列出计算上使用的所有 TCP 端口。我找到了一个很好的 bash 命令here

netstat -ant | sed -e '/^tcp/ !d' -e 's/^[^ ]* *[^ ]* *[^ ]* *.*[\.:]\([0-9]*\) .*$/\1/' | sort -g | uniq

当我直接在putty中输入它时,这个命令可以完美运行。但是,与 paramiko 一起使用时,不会显示任何输出。

这里是示例代码:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='demo', password='password')
command = "netstat -ant | sed -e '/^tcp/ !d' -e 's/^[^ ]* *[^ ]* *[^ ]* *.*[\.:]\([0-9]*\) .*$/\1/' | sort -g | uniq"
stdin, stdout, stderr = ssh.exec_command(command)
print stdout.read()

如果我如下更改命令,标准输出会显示结果,但这不是我想要的。所以我想这可能是 paramiko 的正则表达式问题。有什么想法吗?

command = "netstat -ant | sed -e '/^tcp/ !d'"

【问题讨论】:

    标签: regex python-2.7 output paramiko


    【解决方案1】:

    '\1''\x01' 相同。你应该转义\1

    >>> '\1'
    '\x01'
    >>> print '\1'
    
    >>> '\\1'
    '\\1'
    >>> print '\\1'
    \1
    >>> r'\1'
    '\\1'
    >>> print r'\1'
    \1
    

    使用原始字符串(r'...') 解决您的问题:

    command = r"netstat -ant | sed -e '/^tcp/ !d' -e 's/^[^ ]* *[^ ]* *[^ ]* *.*[\.:]\([0-9]*\) .*$/\1/' | sort -g | uniq"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多