ValueError:关闭文件错误时的I / O操作

时间:2017-10-10 18:50:46

标签: python output stdout scapy arp

我需要帮助请我尝试解决这个问题,因为2天前没有成功,我在python中的新功能请在代码中进行更改并解释:

这是它的代码和arp扫描仪通过scapy它从scapy扫描中获取结果并将结果扫描(ip和macaddress)保存到txt文件在linux机器

然后运行一个名为(doublepulsar-detection-script的外部python脚本)  )通过这个命令:os.system(" python detect_doublepulsar_smb.py --file last.txt")

last.txt =这些文件包含scapy扫描结果

但扫描完成后我收到了这个错误:

  

追踪(最近一次通话):     文件" test.py",第116行,in       lena = int(raw_input("输入数字:"))   ValueError:关闭文件的I / O操作

这是完整的代码:

logging.basicConfig(format='%(asctime)s %(levelname)-5s %(message)s',  datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
logger = logging.getLogger(__name__)


def long2net(arg):
if (arg <= 0 or arg >= 0xFFFFFFFF):
    raise ValueError("illegal netmask value", hex(arg))
return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))


def to_CIDR_notation(bytes_network, bytes_netmask):
network = scapy.utils.ltoa(bytes_network)
netmask = long2net(bytes_netmask)
net = "%s/%s" % (network, netmask)
if netmask < 16:
    logger.warn("%s is too big. skipping" % net)
    return None

return net


def scan_and_print_neighbors(net, interface, timeout=1):
logger.info("arping %s on %s" % (net, interface))
try:
    ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=True)
    for s, r in ans.res:
        line = r.sprintf("%Ether.src%  %ARP.psrc%")
        try:
            hostname = socket.gethostbyaddr(r.psrc)
            line += " " + hostname[0]
        except socket.herror:
            # failed to resolve
            pass
        logger.info(line)
except socket.error as e:
    if e.errno == errno.EPERM:     # Operation not permitted
        logger.error("%s. Did you run as root?", e.strerror)
    else:
        raise

while True:

lena = int(raw_input("Enter Number : "))
print(lena)


if __name__ == "__main__":
    import sys
    import os 
    import time


    sys.stdout = open('textout.txt', 'w+')

    if lena == 1:
        for network, netmask, _, interface, address in scapy.config.conf.route.routes:
            # skip loopback network and default gw
            if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
                continue

            if netmask <= 0 or netmask == 0xFFFFFFFF:
                continue

        net = to_CIDR_notation(network, netmask)
        if interface != scapy.config.conf.iface:
            # see http://trac.secdev.org/scapy/ticket/537
            logger.warn("skipping %s because scapy currently doesn't support arping on non-primary network interfaces", net)

        if net:
            scan_and_print_neighbors(net, interface)

            sys.stdout.close()

            os.system("awk 'NR > 2 {print $2}' textout.txt > last.txt")

            os.system("python detect_doublepulsar_smb.py --file last.txt")


    elif lena == 3 :
        print("bye Bye")
        break

1 个答案:

答案 0 :(得分:1)

问题在于您关闭标准输出文件处理程序的代码,但后来input正在尝试将"Enter Number : "写入其中。

    if net:
        scan_and_print_neighbors(net, interface)

        sys.stdout.close() # <<<

要进行快速修复,请将标准stdout保存在其他变量中,然后在关闭后重定向到该变量。

if __name__ == "__main__":
    import sys
    import os 
    import time

    saved_stdout = sys.stdout
    sys.stdout = open('textout.txt', 'w+')

    ... 

    sys.stdout.close()
    sys.stdout = saved_stdout