Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中捕获Scapy函数输出_Python_Scapy - Fatal编程技术网

在Python中捕获Scapy函数输出

在Python中捕获Scapy函数输出,python,scapy,Python,Scapy,我试图在python脚本中捕获scapy函数traceroute到字符串的输出。我知道我需要像处理子程序一样将此函数传输到stdout.call,但不确定如何使用scapy执行此操作,是否有人能够提供任何帮助?我是Python新手 相关代码如下 #!/usr/bin/env python from scapy.all import traceroute traceroute('www.google.com') 可以通过使用类似文件的对象(例如StringIO)修补sys.stdout: 无论

我试图在python脚本中捕获scapy函数traceroute到字符串的输出。我知道我需要像处理子程序一样将此函数传输到stdout.call,但不确定如何使用scapy执行此操作,是否有人能够提供任何帮助?我是Python新手

相关代码如下

#!/usr/bin/env python
from scapy.all import traceroute

traceroute('www.google.com')

可以通过使用类似文件的对象(例如StringIO)修补sys.stdout:

无论如何,请注意,您需要的信息可能已经存在于traceroute方法返回的对象中:


注意:您可以在下面的答案中找到有关修补标准输出的更多信息。

您也可以这样调用traceroute:

trace, _ = traceroute("www.example.org", verbose=0)
# trace.get_trace() returns a rather impractical format, so we need
# to convert it. First, we only want the first trace available
hosts = trace.get_trace().values()[0]

# hosts will be in the format { 1: ("1.2.3.4",     False), 
#                               2: ("10.20.30.40", False) ... }
# We convert it to ["1.2.3.4", "10.20.30.40", ...] here:
ips = [hosts[i][0] for i in range(1, len(hosts) + 1)]

之后,ips变量将包含作为跟踪一部分的主机列表。

哦,太好了,这看起来是完美的解决方案,您能为我解释一下第二行吗?我不确定您从哪里获得的类“a”当然应该是跟踪。编辑它并添加一些评论
print result.summary()                                      
print unanswered.summary()
trace, _ = traceroute("www.example.org", verbose=0)
# trace.get_trace() returns a rather impractical format, so we need
# to convert it. First, we only want the first trace available
hosts = trace.get_trace().values()[0]

# hosts will be in the format { 1: ("1.2.3.4",     False), 
#                               2: ("10.20.30.40", False) ... }
# We convert it to ["1.2.3.4", "10.20.30.40", ...] here:
ips = [hosts[i][0] for i in range(1, len(hosts) + 1)]