Codificando videos para Nokia 5800

22 11 2009

Nokia 5800

Hace poco compré un Nokia 5800, este equipo tienen una buena resolución 640×360 ( en múltiplos de 8 ) y los vídeos se ven muy bien.

Estuve peleando con el avidemux y ffpmeg para poder convertir vídeos que funcionen. Supuestamente soporta H.264/MPEG-4, pero hay algo que no funciona bien, incluso hay vídeos que se ven bien en un N96 pero no en este. Con el avidemux logré hacerlo pero sólo se escuchaba el audio y era necesario avanzar y retroceder el vídeo hasta que muestre una imagen.

Hasta que finalmente di con Handbrake (http://handbrake.fr/), disponible en los repositorios packman (handbrake-gtk), con este software logré codificar vídeos que funcionen sin problema.
La configuración que utilicé es la siguiente:

Format: MP4
Video >
Video Codec: MPEG-4 (ffmpeg)
Bitrate: 700
Audio >
Codec: AAC
Sample rate: 44.1

En las dimensiones (Picture Settings), el Alignment en 8.
En cuanto al tamaño, depende del vídeo origen, como máximo recomiendo 640×360.

Nokia5800





Verificación de certificados con openssl

25 09 2009

Para validar un certificado junto con su cadena de certificación:

openssl verify -CAfile cert1.cer ... certN.cer finalcert.cer

Leer el contenido de un PKCS7

openssl asn1parse -in token.pk7 -i -dump

Pasar de CER a PEM

openssl x509 -ni certificado.cer -outform PEM -out certificado.pem

Validar un token PKCS7 con un certificado (PEM)

openssl smime -verify -noverify -inform PEM -signer certificado.pem -in token.pk7





bloquear ip por 60 segundos con iptables

15 04 2009

Algo que encontré en la lista:

I assume you’re looking for the “recent” module for iptables.
# Blocking ssh attacks
/usr/sbin/iptables -A INPUT -p tcp –syn –dport 22 -m recent –name sshattack –set
/usr/sbin/iptables -A INPUT -p tcp –dport 22 –syn -m recent –name sshattack –update –seconds 60 –hitcount 6 -j LOG –log-prefix ‘SSH attack: ‘
/usr/sbin/iptables -A INPUT -p tcp –dport 22 –syn -m recent –name sshattack –update –seconds 60 –hitcount 6 -j REJECT

This will block all further syns from an IP address starting on the
sixth port 22 connection within 60 seconds. It takes 60 seconds of
absolute quiet from that same ip address (or a reboot) to make the
block go away. Kills a LOT of brute force ssh attacks. I’ve also
used this both against web statistics spammers and email DOSers with
good results.

http://lists.opensuse.org/opensuse-security/2005-12/msg00069.html





network manager y python

8 04 2009
  • Usando dbus para interactuar con Network Manager desde python
  • Escuchando eventos desde dbus
  • Obtención de IP propia y de un host x
  • Simple envío de mail
  • gobject: loops y timers
  • libnotify (usando pynotify)
  • Actualización de IP dinámica en CDMON


#!/usr/bin/python
import httplib
import smtplib
import socket
import fcntl
import struct
import os
import time
import datetime
import dbus
import sys
import pynotify
import gobject
import dbus.mainloop.glib
import logging
import logging.handlers
import urllib2
import threading
#
LOG_FILENAME="-----------.log"
IFNAME = "eth0"
URL_TEST = "http://www.google.com"
FROM_ADDR = 'From: ----------'
TO_ADDR = 'To: ------------'
DYNA_HOST = "dinamico.cdmon.org"
PWD="------------------"
USR="-----------"
URL="/onlineService.php?n="+USR+"&p="+PWD+"&enctype=MD5"
MY_HOSTNAME="-----------"
TIMEOUT=5000
#
NM_STATE_UNKNOWN = 0
NM_STATE_ASLEEP = 1
NM_STATE_CONNECTING = 2
NM_STATE_CONNECTED = 3
NM_STATE_DISCONNECTED = 4
.
class Callable:
....def __init__(self, anycallable):
........self.__call__ = anycallable
#
class Message:
#
....def error(msg):
........if pynotify.init("NetControl"):
............n = pynotify.Notification("CDMON", msg, "error")
............n.set_urgency(pynotify.URGENCY_CRITICAL)
............n.set_timeout(5000)
............n.show()
#
....def info(msg):
........if pynotify.init("NetControl"):
............n = pynotify.Notification("CDMON", msg)
............n.set_urgency(pynotify.URGENCY_LOW)
............n.set_timeout(5000)
............n.show()
....error = Callable(error)
....info = Callable(info)
#
class Manager:
....bus = None
....nm = None
....logger = None
#
....def __init__(self):
........self.bus = dbus.SystemBus()
........self.logger = logging.getLogger('NetControl')
........self.logger.setLevel(logging.DEBUG)
........handler = logging.handlers.RotatingFileHandler(
............ LOG_FILENAME, maxBytes=1048576, backupCount=2)
........formatter = logging.Formatter("%(asctime)s - %(funcName)s - %(levelname)s - %(message)s")
........handler.setFormatter(formatter)
........self.logger.addHandler(handler)
#
....def connect(self):
........for i in range(1,3):
............try:
................self.logger.debug("Connect to Network Manager. Attemp %s",i)
................self.nm = self.bus.get_object('org.freedesktop.NetworkManager','/org/freedesktop/NetworkManager')
................break
............except Exception, e1:
................self.logger.error("Failed to connect to Network Manager (%s)",str(e1))
................time.sleep(10)
#
........if self.nm is None:
............Message.error("Unable to connect to the Network Manager")
............self.logger.error("Unable to connect to Network Manager. Exit.")
............sys.exit(2)
#
....def is_active(self):
........return self.nm.state() == NM_STATE_CONNECTED
#
....def wake_up(self):
........if self.nm.state() NM_STATE_ASLEEP:
............self.logger.debug("Put to sleep")
............self.nm.sleep()
............time.sleep(2)
........self.logger.debug("Wake up")
........self.nm.wake()
#
....def is_alive(self):
........try:
............self.logger.debug("Check if there is a real connection")
............urllib2.urlopen(URL_TEST)
............self.logger.debug("Connected.")
............return True
........except Exception, e1:
............self.logger.debug("No connection.")
............self.logger.error(str(e1))
............return False
#
....def check_cdmon(self):
........try:
............'''GET INET ADDRESS'''
............self.logger.debug("Get local IP")
............s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
............myip = socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', IFNAME[:15]))[20:24])
#
............'''GET HOST ADDRESS'''
............self.logger.debug("Get CDMON record")
............result = socket.getaddrinfo(MY_HOSTNAME, None, 0, socket.SOCK_STREAM)
............hostip = [x[4][0] for x in result][0]
............if (myip != hostip):
................self.update_cdmon(myip)
............else:
................self.logger.debug("No need to update.")
........except Exception, e1:
............Message.error(str(e1))
............self.logger.error(str(e1))
............return True
#
....def update_cdmon(self,myip):
........try:
............self.logger.debug("Updating IP (%s)",myip)
............conn = httplib.HTTPSConnection(DYNA_HOST)
............conn.putrequest('GET', URL)
............conn.endheaders()
............response = conn.getresponse()
............resp = response.read()
#
............if resp.count("errorlogin") > 0:
................Message.error("Login failed!")
................self.logger.error("Login failed!")
................self.send_mail("Login failed! " + myip)
............elif resp.count("novaversio") > 0:
................Message.error("Request url changed!")
................self.logger.error("Request url changed!")
................self.send_mail("Request URL has changed. Update this tool! " + myip)
............elif resp.count("guardatok") > 0:
................rs = resp.split("&")
................for part in rs:
....................if part.count("newip"):
........................newip = part[6:]
........................Message.info("New IP: "+newip)
........................self.send_mail("New IP: "+newip)
....................elif resp.count("badip") > 0:
........................Message.error("Bad IP!")
........................self.logger.error("Bad IP!")
........except httplib.HTTPException:
............Message.error("HTTPException")
............self.logger.error("HTTPException")
........except httplib.NotConnected:
............Message.error("NotConnected")
............self.logger.error("NotConnected")
........except httplib.InvalidURL:
............Message.error("InvalidURL")
............self.logger.error("InvalidURL")
........except httplib.UnknownProtocol:
............Message.error("UnknownProtocol")
............self.logger.error("UnknownProtocol")
........except httplib.UnknownTransferEncoding:
............Message.error("UnknownTransferEncoding")
............self.logger.error("UnknownTransferEncoding")
........except httplib.UnimplementedFileMode:
............Message.error("UnimplementedFileMode")
............self.logger.error("UnimplementedFileMode")
........except httplib.IncompleteRead:
............Message.error("IncompleteRead")
............self.logger.error("IncompleteRead")
........except httplib.ImproperConnectionState:
............Message.error("ImproperConnectionState")
............self.logger.error("ImproperConnectionState")
........except httplib.CannotSendRequest:
............Message.error("IncompleteRead")
............self.logger.error("IncompleteRead")
........except httplib.CannotSendHeader:
............Message.error("CannotSendHeader")
............self.logger.error("CannotSendHeader")
........except httplib.ResponseNotReady:
............Message.error("ResponseNotReady")
............self.logger.error("ResponseNotReady")
........except httplib.BadStatusLine:
............Message.error("BadStatusLine")
............self.logger.error("BadStatusLine")
#
....def send_mail(self,msg):
........server = smtplib.SMTP("localhost")
........smsg = TO_ADDR + "\n"
........smsg += "Subject: CDMON\n\n" + msg
........server.sendmail(FROM_ADDR,TO_ADDR, smsg)
........server.quit()
#
....def on_nm_update(self, arg1):
........if arg1 == NM_STATE_UNKNOWN:
............self.logger.debug("Interface state is UNKNOWN")
........elif arg1 == NM_STATE_ASLEEP:
............self.logger.debug("Interface state is SLEEP")
........elif arg1 == NM_STATE_CONNECTING:
............self.logger.debug("Interface state is CONNECTING")
........elif arg1 == NM_STATE_DISCONNECTED:
............self.logger.debug("Interface state is DISCONNECTED")
........elif arg1 == NM_STATE_CONNECTED:
............self.logger.debug("Interface state is CONNECTED")
............time.sleep(5)
............if self.check_alive():
................self.check_cdmon()
............else:
................self.logger.error("No connection")
................Message.error("No connection")
#
....def check_alive(self):
........for i in range(1,3):
............if self.is_alive():
................break
............self.wake_up()
............time.sleep(10)
........return self.is_alive()
#
....def listen(self):
........self.logger.debug("Listening")
........self.bus.add_signal_receiver(self.on_nm_update,
............dbus_interface="org.freedesktop.NetworkManager",
............signal_name="StateChanged")
#
....def do_self_check(self):
........self.logger.debug("Self checking")
........if self.check_alive():
............self.check_cdmon()
........else:
............self.logger.error("No connection")
............Message.error("No connection")
........self.start_timer()
#
....def start_timer(self):
........self.logger.debug("Start timer")
........gobject.timeout_add(TIMEOUT, self.do_self_check)
#
#MAIN
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
#
man = Manager()
man.connect()
#
for i in range(1,3):
....for b in range(1,3):
........if man.is_active():
............break
........time.sleep(5)
#
....if man.is_active():
.... break
#
....man.wake_up()
....time.sleep(10)
#
if not man.is_active():
....Message.error("Connection is not active")
....sys.exit(2)
#
if not man.check_alive():
....Message.error("No connection")
#
man.listen()
man.check_cdmon()
#
man.start_timer()
gobject.MainLoop().run()

Para conservar la indentación los espacios iniciales fueron reemplazados por ‘.’
Saltos de línea reemplazados por #





notificaciones en el escritorio

6 04 2009

Distintas formas de mostrar una notificación en el escritorio:

usando python y pynotify

#import os
import sys
#os.environ['DISPLAY']=':0'
try:
import pynotify
except:
print "pynotify not installed"
else:
if pynotify.init("pyMessage"):
n = pynotify.Notification(sys.argv[1], sys.argv[2], "info")
n.set_urgency(pynotify.URGENCY_CRITICAL)
n.set_timeout(20000)
n.show()
else:
print "there was a problem initializing the pynotify module"

conectando python con dbus

import dbus
#import os
import sys
#os.environ['DISPLAY']=':0'
print "Inicializando el bus de tipo session"
bus = dbus.SessionBus()
print "Obteniendo el objeto Notifications"
notify_object = bus.get_object('org.freedesktop.Notifications','/org/freedesktop/Notifications')
print "Obteniendo una interface de tipo Notificatios del objecto"
notify_interface = dbus.Interface(notify_object,'org.freedesktop.Notifications')
print "Lanzando la notificacion"
noti_id = notify_interface.Notify("Messenger", 0, "info", sys.argv[1],sys.argv[2], '',{},20000)
print "Tenemos la notificacion con el ID: ",noti_id

notify-send con un script en bash

#!/bin/bash
#export DISPLAY=:0
/usr/bin/notify-send --urgency=critical --expire-time=20000 --icon=info $1 $2

El DISPLAY=:0 me permite enviar una notificación a esa pantalla desde un terminal remoto.





split cue

6 04 2009

shntool (3.0.8)
cuebreakpoints sample.cue | shnsplit -o flac sample.ape





convertir bin/cue/img/nrg/mdf a iso

3 01 2009

bin
Necesario: bchunk

bchunk image.bin image.cue image

img (CloneCD)
Necesario: ccd2iso

ccd2iso image.img image.iso

mdf (Alcohol)
Necesario: mdf2iso

mdf2iso image.mdf image.iso

nrg (Nero)
Necesario: mdf2iso

nrg2iso image.nrg image.iso

Todas la herramientas estan disponibles en los repositorios estandard de openSUSE.
zypper se 2iso muestra más herramientas disponibles.





Compilar un módulo de YaST

10 12 2008

ycpc -c /usr/share/YaST2/modules/<<modulo>>.ycp





Aplicar un parche

10 12 2008

patch -p0 < patch-file-name-here





Instalando módulos en apache

6 12 2008
a2ensite
Will create the correct symlinks in sites-enabled to allow the site configured in sitefilename to be served
a2dissite
Will remove the symlinks from sites-enabled so that the site configured in sitefilename will not be served
a2enmod
e.g. a2enmod php4 will create the correct symlinks in mods-enabled to allow the module to be used. In this example it will link both php4.conf and php4.load for the user
a2dismod
Will remove the symlinks from mods-enabled so that the module cannot be used

Tomado de: http://www.debian-administration.org/articles/207