我试图列出我的网络上的所有ip地址,我找到了这段代码,但我遇到了这个问题。它表明sh没有属性。
我尝试过很多东西,比如导入pbs和把sh变成类。我目前正在使用windows 10并运行最新的python版本。
import pbs
class Sh(object):
def getattr(self, attr):
return pbs.Command(attr)
sh = Sh()
for num in range(10,40):
ip = "192.168.0."+str(num)
try:
sh.ping(ip, "-n 1",_out="/dev/null")
print("PING ",ip , "OK")
except sh.ErrorReturnCode_1:
print("PING ", ip, "FAILED")
我应该看到我相信的ip地址列表,但是我得到了以下信息:
Traceback (most recent call last):
File "scanner.py", line 11, in <module>
sh.ping(ip, "-n 1",_out="/dev/null")
AttributeError: 'Sh' object has no attribute 'ping'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "scanner.py", line 13, in <module>
except sh.ErrorReturnCode_1:
AttributeError: 'Sh' object has no attribute 'ErrorReturnCode_1'
有什么帮助吗?
发布于 2019-08-06 17:14:20
在Linux上测试。
(Windows的ping文档)
对于模块sh,它应该是
import sh
for num in range(10, 40):
ip = "192.168.0." + str(num)
try:
sh.ping(ip, "-n 1", "-w 1") #, _out="nul") # Windows 10
#sh.ping(ip, "-c 1", "-W 1") #, _out="/dev/null") # Linux
print("PING", ip, "OK")
except sh.ErrorReturnCode_1:
print("PING", ip, "FAILED")
Windows 10没有设备/dev/null
(它存在于Linux上),但很可能它可以使用nul
跳过文本。
在Linux上,即使没有_out
,它也不会显示文本,所以在Windows上可能不需要_out
。
Linux使用-c 1
只进行一次ping。Windows -n 1
或/n 1
。我还使用-W 1
在1秒后超时-因此它不会等待太久的响应。Windows可能使用-w 1
或/w 1
。
对于模块pbs
,您可能只需将所有的sh
替换为pbs
import pbs
和
except pbs.ErrorReturnCode_1:
但我没有这个模块来测试它。
使用标准模块os
,它需要Linux上的/dev/null
。
import os
for num in range(10, 40):
ip = "192.168.0." + str(num)
exit_code = os.system("ping -n 1 -w 1 " + ip + " > nul") # Windows
#exit_code = os.system("ping -c 1 -W 1 " + ip + " > /dev/null") # Linux
if exit_code == 0:
print("PING", ip, "OK")
else:
print("PING", ip, "FAILED")
https://stackoverflow.com/questions/57385061
复制