IP 地址字符串提取在 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")。这会返回字节,但我不推荐它,因为 __getitem__ 对字节和字符串的工作方式不同。例如"Hello"[0]不是H,它是H的字节数。