簡體   English   中英

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

[英]IP address string extraction not working in Python3

當嘗試從 Python3 中的“ifconfig”命令中提取 IP 地址時,我收到錯誤消息:

文件“testingCode.py”,第 28 行,ip = ip_string.strip().split("")[1:] TypeError: a bytes-like object is required, not 'str'

我不確定出了什么問題,因為代碼在 Python2 中有效,但是當我切換到 Python3 時,我得到了這個錯誤。 我試圖將 .strip() 命令切換到 .decode() 並且程序運行但沒有 output 任何內容,因為找不到來自 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] 它從字節創建一個字符串,並使用 substring " "將其拆分。 如果您出於某種原因想要ip以字節為單位,您可以使用ip = ip_string.decode("utf-8").strip().split(" ")[1].encode("utf-8") 這會返回字節,但我不推薦它,因為__getitem__對字節的作用與對字符串的作用不同。 例如"Hello"[0]不是H ,它是H的字節數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM