简体   繁体   中英

IP address string extraction not working in Python3

When attempting to extract the IP address from an 'ifconfig' command in Python3, I recieve the error:

File "testingCode.py", line 28, in ip = ip_string.strip().split(" ")[1:] TypeError: a bytes-like object is required, not 'str'

I'm not sure what is wrong because the code works in Python2, however when I switch to Python3, I get this error. I attempted to switch the.strip() command to.decode() and the program runs but doesn't output anything as the IP address from ifconfig is'nt found. Any solutions would be greatly appreciated.

#!/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])

Your problem is a the fact that, when you execute something in a process, the communication is usually in bytes. Because of that the type of ip_string is bytes, not string. Try ip = ip_string.decode("utf-8").strip().split(" ")[1] . It creates a string from the bytes and splits that with the substring " " . If you for some reason wnat to have ip in bytes you can use ip = ip_string.decode("utf-8").strip().split(" ")[1].encode("utf-8") . This returns you the bytes, but I doesn't recomend it, because __getitem__ works different with bytes as with strings. For example "Hello"[0] is not H , its the byte number of H .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM