Problema con escribir lineas en un archivo [PYTHON] [SOLUCIONADO]

Iniciado por Panic0, 3 Octubre 2021, 03:27 AM

0 Miembros y 1 Visitante están viendo este tema.

Panic0

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
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
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)
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
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í
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.
Los ataques de pánico suelen comenzar de forma súbita, sin advertencia.