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

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [PYTHON] Invitación a los usuarios para unirse a un pequeño proyecto
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [PYTHON] Invitación a los usuarios para unirse a un pequeño proyecto  (Leído 2,285 veces)
astinx

Desconectado Desconectado

Mensajes: 111



Ver Perfil
[PYTHON] Invitación a los usuarios para unirse a un pequeño proyecto
« en: 7 Agosto 2012, 23:50 pm »

Hola, estoy realizando un pequeño proyecto por cuenta propia. El mismo consiste en lo siguiente:-"Desarrollar un script en python que lea de un JSON un archivo config, el cual contiene información de configuración, para configurar automaticamente una distro de debian"

¿Por qué?
Bueno, hasta hace poco era un fanatico de las distros y la eficiencia, ya hace 3 años que soy usuario de Linux (o GNU/Linux, sinceramente no le doy importancia a la diferencia, no se ofendan por favor). Comenze con Ubuntu, pero cuando me di cuenta de que con tantas actualizaciones terminaba bajando basura y que al fin y al cabo (creo yo) es una de las distros mas "borrachas" de Linux, termine migrando a algo mas generico y mas core, Debian. He provado casi todos los entornos de escritorio y tratar de sacarle al maximo la eficiencia a Debian, sin embargo, me ha pasado mas de una vez que he dicho:-"A la $%&! Instalare todo desde cero con solo lo basico y necesario!".

Sin embargo, una cosa que me molesta, es que uno tiene que configurar varias cosas por cuenta propia cuando instala por primera vez Debian (si es que se quiere tener un sistema ordenado), packages, bajar el sudo, la filestructure de uno, los repositorios, aplicaciones, etcétera.

Por eso me decidi a hacer un script que tomara toda mi info de "customizacion" y la ejecutara. Helo aqui un ejemplo de mi archivo config:

Código
  1. #Users name (the same of the /home/<user_name> folder this must exist!)
  2. {"user_name" : "astinx",
  3.  
  4. #The file structure of your environment
  5. "filestructure" :  "dev/tools/eclipse
  6. dev/tools/smalltalk
  7. dev/tools/ada
  8. dev/tools/pl1
  9. dev/tools/blender
  10. dev/tools/php
  11. dev/tools/python
  12. dev/tools/c
  13. dev/tools/ruby
  14. dev/tools/actionscript
  15. dev/tools/js
  16.  
  17. dev/frameworks/java/grails
  18. dev/frameworks/java/play
  19. dev/frameworks/java/spring
  20. dev/frameworks/java/struct
  21. dev/frameworks/java/gwt
  22.  
  23. dev/flash/flex
  24.  
  25. dev/frameworks/python/django
  26.  
  27. dev/frameworks/php/codeigniter
  28. dev/frameworks/php/symphony
  29.  
  30. dev/frameworks/myframeworks
  31.  
  32. dev/references/hibernate
  33. dev/references/spring
  34. dev/references/blazeds
  35.  
  36. dev/workspaces/eclipseworksheet
  37. dev/workspaces/phpworksheet
  38.  
  39. dev/servers
  40.  
  41. dev/scripts/python
  42. dev/scripts/bash
  43. dev/scripts/ruby
  44.  
  45. repos/git
  46. repos/svn
  47.  
  48. books
  49.  
  50. college/mypapers
  51.  
  52. media/video
  53. media/music
  54. media/images
  55.  
  56. job",
  57. #Repositories that you wanna make a checkout
  58. "repositories_checkout" : "svn://...",
  59. #Packages that you wanna install
  60. "packages" : "geany
  61.  virtualbox-ose
  62.  pgadmin3",
  63. #External devices like ntfs partitions that you wanna have every time mounted  
  64. "external_devices" : "/dev/sda3 => externalntfs",
  65. #.deb files that you wanna install (they must be at the same level of this file and init_script.py file)
  66. "backup_debs" : "google-chrome.deb",
  67. #.tar, .giz or .zip that you wanna extract in some of the filestructure folder.
  68. #The sintax is <file_name> => <destination_folder> with <extension>
  69. "backup_files" : "eclipse_environment.zip => /dev/tools/eclipse with .zip
  70.  webdevelop.tar => /dev/tools/php with .tar",
  71.  
  72. #Anothers scripts that you wanna run when this script finishs
  73. #The sintax is <script_name> with <bash|python|anything what make it run>
  74. "anothers" : "java_install_script.sh with bash
  75.  hi.py with python"}
  76.  

PD: Perdonen mi "ingles" xD

Esos parametros que inclui en el JSON son algunos de los que pense que podrian resultar utiles, pense:-"¿Que se me hace molesto cuando recien acabo de formatear la maquina?". Hacer la filestructure, descargar los packages, modificar los init.d para que siempre me monten los dispositivos externos (tengo una particion con Windows CHAN!... para jugar videojuegos y tengo un NTFS que uso como boveda), descomprimir mis programas en los respectivos directorios, instalar los .deb, tirar algun que otro script de backup, etcétera.

Mi script de backup lo hice en Python (algunos pensaran:-"¿Por que no en Bash?", simple, ODIO Bash, programar en Bash, no es programar xD)

Helo aqui:
Código
  1. #!/usr/local/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. #       init_script.py
  5. #      
  6. #       Copyright 2012 astinx <astinx@astinxmachina>
  7. #      
  8. #       This program is free software; you can redistribute it and/or modify
  9. #       it under the terms of the GNU General Public License as published by
  10. #       the Free Software Foundation; either version 2 of the License, or
  11. #       (at your option) any later version.
  12. #      
  13. #       This program is distributed in the hope that it will be useful,
  14. #       but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. #       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. #       GNU General Public License for more details.
  17. #      
  18. #       You should have received a copy of the GNU General Public License
  19. #       along with this program; if not, write to the Free Software
  20. #       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  21. #       MA 02110-1301, USA.
  22.  
  23. import datetime
  24. import sys
  25. import os
  26. import subprocess
  27. import json
  28. import re
  29.  
  30. # This is the only thing that you can touch of this script, the config file absolute path.
  31. config_path = "/home/astinx/dev/scripting/bash/config"
  32. comment_regex = "(\A#.*\n*)"
  33. whiteline_regex = "(\A\s*\Z)"
  34.  
  35. # First, we clean the config file, this is, erase all the comments
  36. config_file = file(config_path,"r")
  37. # A temporary file to put the parsed config file, without comments
  38. config_temp = file(config_path+"_temp","w")
  39. for line in config_file:
  40. if (not (re.match(comment_regex+"|"+whiteline_regex,line))):
  41. config_temp.write(line)
  42.  
  43. config_file.close()
  44. config_temp.close()
  45.  
  46. # Now we clean the \n like dev/asd\ndev/qwe", to  dec/asd,dev/qwe",
  47. config_json = file(config_path+"_json","w")
  48. config_temp = file(config_path+"_temp","r")
  49. for line in config_temp:
  50. # If is something like '"packages" : "geany'
  51. if (re.match(".*\n\Z",line) and (not(re.match('.*\",\n\Z',line))) and (not(re.match("({)|(.*})",line)))):
  52. line = line.replace("\n",", ")
  53. line = line.replace("\t","")
  54. config_json.write(line)
  55. else:
  56. line = line.replace("\t","")
  57. config_json.write(line)
  58. config_json.close()
  59. config_temp.close()
  60.  
  61.  
  62. # Well the config file is cleaned, now we can open it as a JSON object
  63.  
  64. config_path = "/home/astinx/dev/scripting/bash/config"
  65. config_path = config_path + "_json"
  66. jsonfile = file(config_path,"r")
  67. json_string = jsonfile.read()
  68. jsonfile.close()
  69. json_obj = json.loads(json_string)
  70. config_dictionary = dict(json_obj)
  71.  
  72. # Now we get the environment variables from the JSON
  73. user_name = config_dictionary.get("user_name")
  74. filestructure = config_dictionary.get("filestructure")
  75. repositories_checkout = config_dictionary.get("repositories_checkout")
  76. packages = config_dictionary.get("packages")
  77. external_devices = config_dictionary.get("external_devices")
  78. backup_debs = config_dictionary.get("backup_debs")
  79. backup_files = config_dictionary.get("backup_files")
  80. anothers = config_dictionary.get("anothers")
  81.  
  82. #We build the filestructure
  83.  
  84. for directory in filestructure.split(','):
  85. print "Building "+directory+" ...\n"
  86. try:
  87. os.system("mkdir -p "+directory)
  88. except OSError, e:
  89. print "No se pudo crear el directorio ["+str(e)+"]"
  90. except ValueError, e:
  91. print "Uno de los directorios ingresados es ilegible ["+str(e)+"]"
  92.  

Apenas lo único que llevo hecho es esta parte, que seria el "parser de la aplicación", es que al parecer la librería de JSON, se mama un poco si encuentra algo del estilo <clave>:<valor>, donde valor incluye saltos de linea. Por eso tuve que introducir un poco de código, para limpiar el JSON antes de traérmelo.

Me gustaría que me dieran sus opiniones acerca de que otro campo podría incluir en el JSON de config, de manera que este script de customizacion sea lo mejor posible, si quieren aportar con código también son bienvenidos,  acá les dejo el repo donde tengo colgado el código:
http://code.google.com/p/pcustom

Cualquier cosa si quieres ser miembros para comitear codigo me envian un mensaje privado.

Saludos y gracias por su tiempo, sus criticas seran bienvenidas!


« Última modificación: 8 Agosto 2012, 00:02 am por EleKtro H@cker » En línea

La programación hoy en día es una carrera entre los ingenieros de software intentando construir mejores y más eficientes programas a prueba de idiotas y el Universo intentando producir mejores y más grandes idiotas. De momento, el Universo está ganando
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Sugerencias para pequeño proyecto...?
Multimedia
^Sephiroth^ 2 1,776 Último mensaje 13 Junio 2005, 22:04 pm
por ^Sephiroth^
Pequeño conversor by swik [Python]
Scripting
.:Swik:. 3 4,864 Último mensaje 18 Abril 2010, 11:32 am
por xassiz_
Mi pequeño proyecto con arduino y dos ldr. « 1 2 »
Electrónica
braulio-- 16 14,689 Último mensaje 9 Julio 2010, 11:07 am
por braulio--
Mi pequeño proyecto
Desarrollo Web
FightingTheWorld 2 3,961 Último mensaje 19 Mayo 2011, 15:59 pm
por [u]nsigned
[Python]Generar archivo cifrado solo leido para usuarios logeados
Scripting
MatiasHA 0 1,811 Último mensaje 11 Diciembre 2012, 09:21 am
por MatiasHA
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines