“ Sh”对象没有属性

时间:2019-08-06 23:07:31

标签: python networking ip

我试图列出网络上的所有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'

有帮助吗?

1 个答案:

答案 0 :(得分:0)

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