我有一个输入文件测试.txt如下:
host:dc2000
host:192.168.178.2
我想使用以下方法获取所有这些机器的地址:
grep "host:" /root/test.txt
依此类推,我通过python获得命令输出:
import subprocess
file_input='/root/test.txt'
hosts=subprocess.Popen(['grep','"host:"',file_input], stdout= subprocess.PIPE)
print hosts.stdout.read()
但结果是空字符串。
我不知道我遇到了什么问题。你能建议我如何解决吗?
试试:
import subprocess
hosts = subprocess.check_output("grep 'host:' /root/test.txt", shell=True)
print hosts
您的代码应该可以工作,您确定用户具有读取文件的访问权限吗?
另外,您确定文件中有"host:"
吗?您可能是这个意思:
hosts_process = subprocess.Popen(['grep','host:',file_input], stdout= subprocess.PIPE)
hosts_out, hosts_err = hosts_process.communicate()
另一种解决方案,尝试 Plumbum 包(https://plumbum.readthedocs.io/):
from plumbum.cmd import grep
print(grep("host:", "/root/test.txt"))
print(grep("-n", "host:", "/root/test.txt")) #'-n' option