首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IP地址字符串提取不适用于Python3

IP地址字符串提取不适用于Python3
EN

Stack Overflow用户
提问于 2021-02-13 15:53:16
回答 1查看 212关注 0票数 0

当试图从Python3中的“ifconfig”命令提取IP地址时,我会收到以下错误:

文件"testingCode.py",第28行,在ip = ip_string.strip().split(“")1: TypeError:需要一个类似字节的对象,而不是'str‘

我不知道是什么问题,因为代码在Python2中工作,但是当我切换到Python3时,我会得到这个错误。我试图将.strip()命令切换到.decode(),程序将运行,但没有输出任何内容,因为没有找到ifconfig中的IP地址。如有任何解决办法,将不胜感激。

代码语言:javascript
复制
#!/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])
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-13 16:15:16

您的问题在于,当您在进程中执行某件事情时,通信通常以字节为单位。因此,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的字节数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66186997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档