python - 'Sh' 对象没有属性
问题描述
我试图列出我网络上的所有 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'
有什么帮助吗?
解决方案
在 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 上,即使没有它也不会显示文本,因此在 Windows 上_out
可能不需要。_out
Linux-c 1
只使用一次 ping。窗户-n 1
或/n 1
. 我也曾经-W 1
在 1 秒后超时 - 所以它不会等待太长时间来响应。Windows 可能使用-w 1
或/w 1
使用模块pbs
可能您只需将所有替换sh
为pbs
import pbs
和
except pbs.ErrorReturnCode_1:
但我没有这个模块来测试它。
使用Linux 上os
需要的标准模块/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")
推荐阅读
- python - chaquopy 中的语言检查工具
- python - 在我的 Pandas 和 Openpyxl 代码中使用 Writer.Close() 函数时出错
- rabbitmq - 使用 RabbitMQ 和 Camel 一条一条地消费消息
- local-storage - _lr_id_ localstorage 项目是什么,它来自哪里?
- java - 在 android 中使用 facebook 登录后无法获取 facebook 用户个人资料
- c++ - 我已经写了一个代码直接从数组创建最大堆到一个创建的虚拟数组但是输出是错误的,有人可以指出错误
- rest - 使用 Github REST API 将数据附加到现有文件而不替换
- javascript - 我们如何在 React 类组件状态下访问本地 JSON 文件数据
- minio - 如何更改 MinIO 中的存储桶名称?
- android - Android BLE App 只能订阅 1 个 BLE 设备的特征通知