如何使用python子进程Popen调用通过SSH进入远程服务器来执行awk命令?

时间:2018-10-11 05:24:42

标签: python awk ssh subprocess popen

我在/a/logs/file.log位置的远程服务器198.168.111.222上有一个日志文件,其中每一行的格式如下所示-

1538966781.794|7f5059db5940| 31aaa010| core-0: load 0% perf 1%/0.90 count 3600000
1538966791.798|7f5059db5940| 31aaa010| core-0: load 0% perf 2%/0.90 count 4600000
1538966801.803|7f5059db5940| 31aaa010| core-0: load 0% perf 3%/0.90 count 5600000 
1538966811.809|7f5059db5940| 31aaa010| core-0: load 0% perf 4%/0.90 count 6600000

每行都以Unix时间戳开头。我对获取所有包含字符串“ perf”并且位于给定的startTime和endTime参数之间的行感兴趣。对于上面的示例,它应该返回-

1538966791.798|7f5059db5940| 31aaa010| core-0: load 0% perf 2%/0.90 count 4600000
1538966801.803|7f5059db5940| 31aaa010| core-0: load 0% perf 3%/0.90 count 5600000 

这是我尝试过的-

import subprocess
ip = '198.168.111.222'
startTime = '1538966781.794'
endTime = '1538966811.809'
linetype = 'perf'

cmd = '''ssh -oHostKeyAlgorithms=+ssh-dss root@'''+ ip + ''' \'awk '$0 ~ "''' + 
linetype + '''" && $0 > "''' + startTime + '''" && $0 < "''' + endTime + '''"' 
/a/logs/file.log\''''

print(cmd)
loglines = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output = loglines.stdout.read().decode('utf-8').strip()
print(output) 

我得到的输出是-

ssh -oHostKeyAlgorithms=+ssh-dss root@198.168.111.222 'awk '$0 ~ "perf" && $0 > 
"1538966781.794" && $0 < "1538966811.809"' /a/logs/file.log'
awk: fatal: cannot open file `/Users/ira' for reading (No such file or directory)

我尝试了','',“”和'''的不同组合,但是没有运气。请指导。谢谢!

0 个答案:

没有答案