IP 地址字符串提取在 Python3 中不起作用

IP address string extraction not working in Python3

当试图从 Python3 中的 'ifconfig' 命令提取 IP 地址时,我收到错误:

文件“testingCode.py”,第 28 行,在 ip = ip_string.strip().split(" ")[1:] 类型错误:需要类似字节的对象,而不是 'str'

我不确定哪里出了问题,因为代码在 Python2 中有效,但是当我切换到 Python3 时,出现此错误。我试图将 .strip() 命令切换为 .decode() 并且程序运行但不输出任何内容,因为找不到来自 ifconfig 的 IP 地址。 任何解决方案将不胜感激。

#!/usr/local/lib/python3.8

import subprocess
import os

def bash(command):
    return subprocess.check_output(['bash', '-c', command])

def nmap_scan(ip):
    print(("Scanning TCP ports on %s" % ip))
    res = bash('nmap -T4 -p1-65535 | %s grep "open"' % ip).splitlines()
    ports = []

    for port in res:
        print(port)
        ports.append(port.split("/")[0])

    port_list = ",".join(ports)
    print("\nRunning intense scan on open ports...\n")
    bash('nmap -T4 -A -sV -p%s -oN output.txt %s' % (port_list, ip))
    print("Nmap intense scan  results logged in 'output.txt'")
    exit()

ip_string = bash('ifconfig eth0 | grep "inet "')

ip = ip_string.strip().split(" ")[1]

print(("Your IP Address is: " + ip + "\n"))

octets = ".".join(ip.split(".")[:-1])
subnet = octets + ".0/24"
print(("Running netdiscover on local subnet: %s" % subnet))

ips = bash('netdiscover -P -r %s | grep "1" | cut -d " " -f2 ' % subnet).splitlines()
for i in range(0, len(ips)):
    ip = ips[i]
    print(("%s - %s" % (i + 1, ip)))

choice = eval(input("\nEnter an option 1 - %s, or 0 to exit the script:\n" % len(ips)))
nmap_scan(ips[choice - 1])

您的问题是,当您在进程中执行某些操作时,通信通常以字节为单位。因为 ip_string 的类型是字节,而不是字符串。尝试 ip = ip_string.decode("utf-8").strip().split(" ")[1]。它从字节创建一个字符串并用子字符串 " " 拆分它。如果您出于某种原因想要 ip 以字节为单位,您可以使用 ip = ip_string.decode("utf-8").strip().split(" ")[1].encode("utf-8")。这个 returns 你的字节,但我不推荐它,因为 __getitem__ 对字节和字符串的工作方式不同。例如"Hello"[0]不是H,它是H.

的字节数