首页 > 解决方案 > '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'

有什么帮助吗?

标签: pythonnetworkingip

解决方案


在 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可能您只需将所有替换shpbs

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")

推荐阅读