elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado:


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  Problema con escribir lineas en un archivo [PYTHON] [SOLUCIONADO]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema con escribir lineas en un archivo [PYTHON] [SOLUCIONADO]  (Leído 2,048 veces)
Panic0

Desconectado Desconectado

Mensajes: 218



Ver Perfil
Problema con escribir lineas en un archivo [PYTHON] [SOLUCIONADO]
« en: 3 Octubre 2021, 03:27 am »

Hola a todos, estoy creando unos scripts que sirven para generar y probar ips publicas.

Hasta ahora todo bien, tengo estos tres archivos py


ip_tester.py
Código:
import os
import subprocess
import pathlib
import random
import time
from colorama import Fore

path = pathlib.Path()

ips_file_path         = path / "ips_file" / "ips.txt"

ips_file_working_path = path / "ips_file" / "ips_working.txt"

clear_screen = lambda :(os.system("clear"))

one_second  = 1


def ping(host) -> bool:

    command = ['ping', '-c', '1', host]
    response = subprocess.call(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

    if response == 0:
        return True
    else:
        return False



def ip_tester() -> None:
    print("Testing ip's")
    print("-be patient!-")
    ips_file = open(ips_file_path,"r")  
    try:
        ips_file_working = open(ips_file_working_path,"a")

    except FileNotFoundError:
        ips_file_working = open(ips_file_working_path,"w")
    
    ips = ips_file.readlines()
    len_ips = len(ips)
    ip_counter = 0

    for ip in ips:
        ip_counter = ip_counter + 1
        random_ip_chooser = random.choice(ips)
        for x in random_ip_chooser:
            random_ip_chooser = random_ip_chooser.replace("\n","")

        ip_checker = ping(random_ip_chooser)
        if ip_checker == 1:
            print(f"[IP:{ip_counter}] {random_ip_chooser}" ,"STATE",Fore.GREEN + ":UP!")
            print('\033[39m')
            ips_file_working.writelines(random_ip_chooser + "\n")

        elif ip_checker == 0:
            print(f"[IP:{ip_counter}] {random_ip_chooser}","STATE", Fore.RED + ":DOWN")
            print('\033[39m')


ips_generator.py
Código:
import random
import pathlib
import os

path = pathlib.Path()

ips_file_path         = path / "ips_file" / "ips.txt"
ips_file_working_path = path / "ips_file" / "ips_working.txt"

clear_screen = lambda :(os.system("clear"))

def success():
    print("Success!")
    input("<ENTER>")


def file_ips() -> None:
    try:
        ip_file = open(ips_file_path,"r")
        ips_lines = ip_file.readlines()
        line_counter = 0
        for ip_line in ips_lines:
             line_counter = line_counter + 1
        if line_counter <= 1:
            pass
        else:
            print("The file already has ips generated, do you want to empty it?")
            op = input("s/n: ").lower()
            
            if op == "s":
                ip_file = open(ips_file_path,"w")
                success()
            else:
                pass

        ip_file = open(ips_file_path,"a")
    
        print("How many ips you want to generate?")
        ip_range = int(input("Range: "))
        for ip in range(0,ip_range + 1):
            random_ip = f"{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(0,255)}"
            print(random_ip)
            ip_file.writelines(random_ip + "\n")

        print(f"GENERATED IPS {ip}")
        success()

    except FileNotFoundError:
        print("The file does not exist, do you want to create it?")
        os = input("s/n: ").lower()
        if os == "s":
            ip_file = open(ips_file_path,"w")
            success()
            clear_screen()
            print("Select the option 1 again!")

        else:
            print("Start the script again!")
            clear_screen()

def ips_working_file() -> None:
    try:
        ip_file = open(ips_file_working_path,"r")
        ips_lines = ip_file.readlines()
        line_counter = 0
        for ip_line in ips_lines:
             line_counter = line_counter + 1
        if line_counter <= 1:
            pass

    except FileNotFoundError:
        print("The file does not exist, do you want to create it?")
        os = input("s/n: ").lower()
        if os == "s":
            ip_file = open(ips_file_working_path,"w")
            success()
            clear_screen()





pic.py
(Este seria el main)
Código:
from subprocess import check_output
from ip_tester import *
from ips_generator import *


if __name__ == "__main__":
    clear_screen()
    check_path = pathlib.Path("ip_public_browser/ips_file/").exists()

    print(check_path)
    if check_path == False:
        try:
            os.mkdir("ips_file")
        except FileExistsError:
            pass
    else:
        pass
    while True:
        print("     ██████╗░██╗░░░██╗██████╗░██╗░░░░░██╗░█████╗░  ██╗██████╗░")
        print("     ██╔══██╗██║░░░██║██╔══██╗██║░░░░░██║██╔══██╗  ██║██╔══██╗")
        print("     ██████╔╝██║░░░██║██████╦╝██║░░░░░██║██║░░╚═╝  ██║██████╔╝")
        print("     ██╔═══╝░██║░░░██║██╔══██╗██║░░░░░██║██║░░██╗  ██║██╔═══╝░")
        print("     ██║░░░░░╚██████╔╝██████╦╝███████╗██║╚█████╔╝  ██║██║░░░░░")
        print("     ╚═╝░░░░░░╚═════╝░╚═════╝░╚══════╝╚═╝░╚════╝    ╚═╝╚═╝░░░░░ ", "\n")

        print("     ░█████╗░██████╗░███████╗░█████╗░████████╗░█████╗░██████╗░")
        print("     ██╔══██╗██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗")
        print("     ██║░░╚═╝██████╔╝█████╗░░███████║░░░██║░░░██║░░██║██████╔╝")
        print("     ██║░░██╗██╔══██╗██╔══╝░░██╔══██║░░░██║░░░██║░░██║██╔══██╗")
        print("     ╚█████╔╝██║░░██║███████╗██║░░██║░░░██║░░░╚█████╔╝██║░░██║")
        print("     ░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝░░░╚═╝░░░░╚════╝░╚═╝░░╚═╝")
        print()
        print("1: Ip Files")
        print("2: Ip tester")
        print("e: Exit")
        op = input("Option: ").upper()
        if op == "1":
            while True:
                clear_screen()
                print("What type of file do you want to generate?" ,"\n","\n")
                print("1 : Ips for testing")
                print("2 : To save ips")
                print("b : Back", "\n")
                op = str(input("Option: ")).lower()
                
                if op == "1":
                    file_ips()
                elif op == "2":
                    ips_working_file()
                elif op == "b":
                    clear_screen()
                    break

        elif op == "2":
            clear_screen()
            ip_tester()

        elif op == "e":
            print("Thanks for use!")
            break
            


El problema esta en el primer archivo "ip_tester.py"
especificamnte en esta parte
Código:
if ip_checker == 1:
            print(f"[IP:{ip_counter}] {random_ip_chooser}" ,"STATE",Fore.GREEN + ":UP!")
            print('\033[39m')
            ips_file_working.writelines(random_ip_chooser + "\n")


El script debería escribir en el archivo, la ip probada funcionando... Pero por algún motivo no lo hace.

Me ayudan?


Gracias!!!


Pd: Este script esta creado para linux, no lo probé en windows

Edit:
Lo logre solucionar
simplemente agregue dentro del for, la apretura del archivo así
Código:
for ip in ips:
        ip_counter = ip_counter + 1
        random_ip_chooser = random.choice(ips)
        for x in random_ip_chooser:
            random_ip_chooser = random_ip_chooser.replace("\n","")

        ip_checker = ping(random_ip_chooser)

        ips_file_working = open(ips_file_working_path,"a")

Aun así, no se cual es la diferencia de abrirlo antes del for, pero bueno, funciono que es lo importante.


« Última modificación: 3 Octubre 2021, 17:35 pm por Panic0 » En línea

Los ataques de pánico suelen comenzar de forma súbita, sin advertencia.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines