“Sh”对象没有属性

2024-09-27 21:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图列出我的网络上的所有ip地址,我发现了这个代码,但我遇到了这个问题。这表明sh没有属性。你知道吗

我尝试过很多事情,比如导入pbs,把sh变成一个类。 我目前使用的是windows10,运行的是最新的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'

有什么帮助吗?你知道吗


Tags: indevipobject地址shoutping
1条回答
网友
1楼 · 发布于 2024-09-27 21:27:25

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

Windows10没有设备/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")

相关问题 更多 >

    热门问题