I try to use paramiko to list all TCP ports used on a compute. I found a good bash command here:
我尝试使用paramiko列出计算中使用的所有TCP端口。我在这里找到了一个很好的bash命令:
netstat -ant | sed -e '/^tcp/ !d' -e 's/^[^ ]* *[^ ]* *[^ ]* *.*[\.:]\([0-9]*\) .*$/\1/' | sort -g | uniq
This command works perfectly when I directly enter it in putty. However, when use it with paramiko, no output is shown.
当我直接在putty中输入它时,此命令可以正常工作。但是,当与paramiko一起使用时,不会显示输出。
Here is the sample code:
以下是示例代码:
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()
If I change the command as follow, the stdout do show the result, but this is not what I want. So I guess this is probably a regular expression issue with paramiko. Any idea?
如果我按如下所示更改命令,stdout会显示结果,但这不是我想要的。所以我猜这可能是paramiko的正则表达式问题。任何想法?
command = "netstat -ant | sed -e '/^tcp/ !d'"
1 个解决方案
#1
1
'\1'
is same as '\x01'
. You should escape \1
.
'\ 1'与'\ x01'相同。你应该逃避\ 1。
>>> '\1'
'\x01'
>>> print '\1'
>>> '\\1'
'\\1'
>>> print '\\1'
\1
>>> r'\1'
'\\1'
>>> print r'\1'
\1
Using raw string(r'...'
) solve your problem:
使用原始字符串(r'...')解决您的问题:
command = r"netstat -ant | sed -e '/^tcp/ !d' -e 's/^[^ ]* *[^ ]* *[^ ]* *.*[\.:]\([0-9]*\) .*$/\1/' | sort -g | uniq"
#1
1
'\1'
is same as '\x01'
. You should escape \1
.
'\ 1'与'\ x01'相同。你应该逃避\ 1。
>>> '\1'
'\x01'
>>> print '\1'
>>> '\\1'
'\\1'
>>> print '\\1'
\1
>>> r'\1'
'\\1'
>>> print r'\1'
\1
Using raw string(r'...'
) solve your problem:
使用原始字符串(r'...')解决您的问题:
command = r"netstat -ant | sed -e '/^tcp/ !d' -e 's/^[^ ]* *[^ ]* *[^ ]* *.*[\.:]\([0-9]*\) .*$/\1/' | sort -g | uniq"