<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>En borrador permanente &#187; Twisted</title>
	<atom:link href="http://www.juanjoconti.com.ar/categoria/aprendiendo-python/twisted/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.juanjoconti.com.ar</link>
	<description>el blog de Juanjo Conti - abstracto, lúdico y digital</description>
	<lastBuildDate>Tue, 07 Feb 2012 16:20:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Videos de las charlas en Junín</title>
		<link>http://www.juanjoconti.com.ar/2010/12/01/videos-de-las-charlas-en-junin/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=videos-de-las-charlas-en-junin</link>
		<comments>http://www.juanjoconti.com.ar/2010/12/01/videos-de-las-charlas-en-junin/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 23:07:49 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Prolog]]></category>
		<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Eventos]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[twisted]]></category>
		<category><![CDATA[videos]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=2972</guid>
		<description><![CDATA[Los amigos del LugJU han publicado los videos de todas las charlas realizadas en su último evento de Software Libre. Se pasaron! Este es el video de mi charla Desarrollando aplicaciones de red con Twisted: Y también están el resto &#8230; <a href="http://www.juanjoconti.com.ar/2010/12/01/videos-de-las-charlas-en-junin/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Los amigos del LugJU han publicado los videos de todas las charlas realizadas en su último evento de Software Libre. Se pasaron!</p>
<p>Este es el video de mi charla <a href="http://www.juanjoconti.com.ar/2010/11/06/charla-desarrollando-aplicaciones-de-red-con-twisted/" target="_blank">Desarrollando aplicaciones de red con Twisted</a>:</p>
<p><center><br />
<embed src="http://blip.tv/play/AYKQ%2BksC" type="application/x-shockwave-flash" width="480" height="414" allowscriptaccess="always" allowfullscreen="true"></embed><br />
</center><br />
Y también están <a href="http://unnoba.blip.tv/posts?view=archive&amp;nsfw=dc" target="_blank">el resto de las charlas</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2010/12/01/videos-de-las-charlas-en-junin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Charla: Desarrollando aplicaciones de red con Twisted</title>
		<link>http://www.juanjoconti.com.ar/2010/11/06/charla-desarrollando-aplicaciones-de-red-con-twisted/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=charla-desarrollando-aplicaciones-de-red-con-twisted</link>
		<comments>http://www.juanjoconti.com.ar/2010/11/06/charla-desarrollando-aplicaciones-de-red-con-twisted/#comments</comments>
		<pubDate>Sat, 06 Nov 2010 13:49:33 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Eventos]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[PyAr]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[twisted]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=2914</guid>
		<description><![CDATA[Hoy di en Junín una charla introductoria Twisted. Cuando los organizadores me contactaron hace un para de meses para invitarme a venir, me preguntaron sobre qué podía hablar. Mi primera idea era una charla titulada algo así como Python para &#8230; <a href="http://www.juanjoconti.com.ar/2010/11/06/charla-desarrollando-aplicaciones-de-red-con-twisted/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hoy di en <a href="http://jornadassl.agora.unnoba.edu.ar/" target="_blank">Junín</a> una charla introductoria <a href="http://twistedmatrix.com/" target="_blank">Twisted</a>.</p>
<p>Cuando los organizadores me contactaron hace un para de meses para invitarme a venir, me preguntaron sobre qué podía hablar. Mi primera idea era una charla titulada algo así como <strong>Python para diversión, trabajo y estudio</strong>. Mandé un guión con los temas que incluiría, en en el track trabajo mensioné Twisted, el framework que venía usando hacía un tiempo ya. La respuesta que recibí fue.</p>
<p>&#8220;Dale, date una charla de Twisted&#8221;</p>
<p> <img src='http://www.juanjoconti.com.ar/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Si bien venía usándolo hacía casi dos años, mi forma de aprenderlo no fue la más pedagógica, sino que fue la forma dura. Empecé a desarrollar y fui conociendo lo puntudo de sus aristas a medida que iba necesitando agregar nuevas funcionalidades.</p>
<p>Preparar la charla mi vino muy bien para organizar lo que sabía y aprender algunas que había venido evitando. Hoy <a href="http://twitpic.com/34efyo" target="_blank">di la charla en Junín</a> y creo que salió bastante bien.</p>
<p>Introducción a Twisted, un framework escrito en Python que permite<br />
crear aplicaciones de red (clientes y servidores) asincrónicas.<br />
Veremos sus conceptos principales y ejemplos que permitirán al<br />
auditorio volver a su casa con las herramientas básicas para empezar a programar utilizándolo.</p>
<p>Dejo el material de la charla:</p>
<p><a href="http://www.juanjoconti.com.ar/files/charlas/aplicaciones_de_red.pdf" target="_blank">Slides</a><br />
<a href="http://www.juanjoconti.com.ar/files/charlas/ejemplos_intro_twisted.zip" target="_blank">Ejemplos</a></p>
<p>Y una propaganda que fue mi última slide. PyAr, el grupo de usuarios de Python de Argentina está dando charlas abiertas (de 2hs c/u) en La Tribu todos los sábados. El próximo sábado tenemos justamenet una clase de Twisted!</p>
<p><a href="http://python.org.ar/pyar/CharlasAbiertas2010#Twisted" target="_blank">http://python.org.ar/pyar/CharlasAbiertas2010#Twisted</a></p>
<p>Sábado 13 de Noviembre &#8211; Charlas Abiertas de Python en La Tribu (Lambaré 873, Capital Federal)</p>
<p><strong>Twisted</strong></p>
<blockquote><p>Vamos a ver porque el modelo de twisted es necesario, como se programa en modo asyncronico usando deferreds y conocer el api de red de twisted para hacer servicios.</p></blockquote>
<p>Disertante: Lucio Torre<br />
13 a 15 horas</p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2010/11/06/charla-desarrollando-aplicaciones-de-red-con-twisted/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Twitter updates desde Twisted</title>
		<link>http://www.juanjoconti.com.ar/2010/09/26/twitter-updates-desde-twisted/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=twitter-updates-desde-twisted</link>
		<comments>http://www.juanjoconti.com.ar/2010/09/26/twitter-updates-desde-twisted/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 18:00:47 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[twisted]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=2724</guid>
		<description><![CDATA[Este artículo es una re-edición del publicado el 24/08/2010 ya que cuando lo publiqué, Twitter estaba terminando su proceso apagar el sistema de autenticación básica para pasar al más complejo sistema de la danza oAuth; lo cual convirtió al artículo &#8230; <a href="http://www.juanjoconti.com.ar/2010/09/26/twitter-updates-desde-twisted/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Este artículo es una re-edición del publicado el 24/08/2010 ya que cuando lo publiqué, Twitter estaba terminando su proceso apagar el sistema de autenticación básica para pasar al <a href="http://dev.twitter.com/pages/auth_overview" target="_blank">más complejo sistema de la danza oAuth;</a> lo cual convirtió al artículo en inservible. El artículo anterior no está más disponible. Gracias a <a href="http://www.pupeno.com" target="_blank">Pupeno</a> por revisar esta versión.<br />
</em></p>
<p>¿Tenés un servidor escrito en <a href="http://twistedmatrix.com" target="_blank">Twisted</a>? ¿Tenés eventos críticos o importantes que mandás por mail o a celulares? ¿Qué tal publicarlos en <a href="http://www.twitter.com" target="_blank">Twitter</a>?</p>
<p>La versión original de este artículo utilizaba la biblioteca <a href="http://github.com/dustin/twitty-twister" target="_blank">Twitty Twister</a>, la única pensada para usar Twitter desde Twisted. Lamentablemente no funciona bien con el nuevo sistema de autenticación de Twitter por lo que voy a usar <a href="http://github.com/joshthecoder/tweepy" target="_blank">Tweepy</a>, una librería con la cual hacer la danza de oAuth es muy sencillo.</p>
<p>1) <a href="https://twitter.com/signup" target="_blank">Registrar</a> un usuario dónde publicar las notificaciones.<br />
2) Con ese usuario, <a href="http://dev.twitter.com/apps/new" target="_blank">registrar una aplicación</a>. Es muy importante usar el mismo usuario para ahorrarnos algunos pasos en la danza oAuth.<br />
3) De la página de la aplicación creada, tomar la siguiente información: consumer key, consumer secret (desde la home de la aplicación), access token y access token secret (de la página My Access Token).<br />
4) Código:</p>
<p>Con los datos del punto 3, creamos el módulo <strong>twitterupdates.py</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> tweepy
&nbsp;
TWITTER_KEY = <span style="color: #483d8b;">'xxxxxxxxxxxxxxxx'</span>
TWITTER_SECRET = <span style="color: #483d8b;">'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'</span>
MY_KEY = <span style="color: #483d8b;">'xxxxxxxxxxxxxxxxxxxxxxxx'</span>
MY_SECRET = <span style="color: #483d8b;">'xxxxxxxxxxxxxxxxxxxxxxxxxx'</span>
&nbsp;
auth = tweepy.<span style="color: black;">OAuthHandler</span><span style="color: black;">&#40;</span>TWITTER_KEY, TWITTER_SECRET<span style="color: black;">&#41;</span>
auth.<span style="color: black;">set_access_token</span><span style="color: black;">&#40;</span>MY_KEY, MY_SECRET<span style="color: black;">&#41;</span>
twitter = tweepy.<span style="color: black;">API</span><span style="color: black;">&#40;</span>auth<span style="color: black;">&#41;</span></pre></div></div>

<p>y desde nuestra aplicación Twisted lo importamos:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> twitterupdates <span style="color: #ff7700;font-weight:bold;">import</span> twitter</pre></div></div>

<p>Postear una actualización en Twitter o cualquier otra petición a un servidor externo tiene una naturaleza bloqueante y en un framework de concurrencia colaborativa, como es Twisted, no podemos darnos ese lujo. Para solucionar esto, utilizamos <a href="http://twistedmatrix.com/documents/10.1.0/api/twisted.internet.threads.deferToThread.html" target="_blank">deferToThread</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">deferToThread<span style="color: black;">&#40;</span>twitter.<span style="color: black;">update_status</span>, <span style="color: #483d8b;">&quot;Mensaje a postear en Twitter&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Esta llamada retorna un objeto <a href="http://twistedmatrix.com/documents/current/core/howto/defer.html" target="_blank">Deferred</a> al cual se le pueden añadir callbacks o errbacks. La llamada bloqueante es corrida en un hilo aparte.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2010/09/26/twitter-updates-desde-twisted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cambiando el formato de los logs en Twisted</title>
		<link>http://www.juanjoconti.com.ar/2010/09/14/cambiando-el-formato-de-los-logs-en-twisted/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=cambiando-el-formato-de-los-logs-en-twisted</link>
		<comments>http://www.juanjoconti.com.ar/2010/09/14/cambiando-el-formato-de-los-logs-en-twisted/#comments</comments>
		<pubDate>Tue, 14 Sep 2010 14:25:05 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[twisted]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=2809</guid>
		<description><![CDATA[En Twisted se puede tener un log de todo lo que pasa en un programa de forma bastante fácil: from twisted.python import log from twisted.python.logfile import DailyLogFile &#160; log.startLogging&#40;DailyLogFile&#40;'log.txt', LOGDIR&#41;&#41; Todos los prints que anden dando vuelta ahora son entradas &#8230; <a href="http://www.juanjoconti.com.ar/2010/09/14/cambiando-el-formato-de-los-logs-en-twisted/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>En Twisted <a href="http://twistedmatrix.com/documents/current/core/howto/logging.html" target="_blank">se puede tener un log</a> de todo lo que pasa en un programa de forma bastante fácil:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">python</span> <span style="color: #ff7700;font-weight:bold;">import</span> log
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">python</span>.<span style="color: black;">logfile</span> <span style="color: #ff7700;font-weight:bold;">import</span> DailyLogFile
&nbsp;
log.<span style="color: black;">startLogging</span><span style="color: black;">&#40;</span>DailyLogFile<span style="color: black;">&#40;</span><span style="color: #483d8b;">'log.txt'</span>, LOGDIR<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Todos los <strong>prints</strong> que anden dando vuelta ahora son entradas en el log y de yapa estoy usando DailyLogFile en lugar de un archivo común y corriente para que al final del día rote a un nuevo archivo en disco. Hay varias opciones, esta es la que me sirve a mí.</p>
<p>Por defecto los logs se ven algo así:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:00-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>__main__.TModBusFactory<span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo cliente: 190.136.29.16:<span style="color: #000000;">12101</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:00-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>__main__.TModBusFactory<span style="color: #7a0874; font-weight: bold;">&#93;</span> Total: <span style="color: #000000;">1</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:01-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">0</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> G24 dice:  :0090SFE00
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:01-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">0</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> SITIO SFE
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:01-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">0</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo sitio registrado en MBProxy SFE
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span>-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>__main__.TModBusFactory<span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo cliente: 190.136.29.16:<span style="color: #000000;">30519</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span>-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>__main__.TModBusFactory<span style="color: #7a0874; font-weight: bold;">&#93;</span> Total: <span style="color: #000000;">2</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span>-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">1</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> G24 dice:  :0090SFE00
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span>-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">1</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> SITIO SFE
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span>-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">1</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> SFE ya estaba conectado. Borrando anterior.
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">51</span>-0500 <span style="color: #7a0874; font-weight: bold;">&#91;</span>TModBus,<span style="color: #000000;">1</span>,190.136.29.16<span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo sitio registrado en MBProxy SFE</pre></div></div>

<p>¿Cómo podemos cambiar el formato de salida? Algunos tips.</p>
<p>Para cambiar el formato de la fecha y hora:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">log.<span style="color: black;">FileLogObserver</span>.<span style="color: black;">timeFormat</span> = <span style="color: #483d8b;">'%Y-%m-%d %H:%M:%S'</span></pre></div></div>

<p>Para cambiar lo que aparece entre corchetes: utilizar log.msg y el keyword system:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">log.<span style="color: black;">msg</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Nuevo cliente: %s:%d&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">peer</span>.<span style="color: black;">host</span>, <span style="color: #008000;">self</span>.<span style="color: black;">peer</span>.<span style="color: black;">port</span><span style="color: black;">&#41;</span>, system=<span style="color: #483d8b;">' - '</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Con estos dos cambios se puede tener un log como este:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:00 <span style="color: #7a0874; font-weight: bold;">&#91;</span> - <span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo cliente: 190.136.29.16:<span style="color: #000000;">12101</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:00 <span style="color: #7a0874; font-weight: bold;">&#91;</span> - <span style="color: #7a0874; font-weight: bold;">&#93;</span> Total: <span style="color: #000000;">1</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:01 <span style="color: #7a0874; font-weight: bold;">&#91;</span>SFE<span style="color: #7a0874; font-weight: bold;">&#93;</span> G24 dice:  :0090SFE00
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:01 <span style="color: #7a0874; font-weight: bold;">&#91;</span>SFE<span style="color: #7a0874; font-weight: bold;">&#93;</span> SITIO SFE
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">41</span>:01 <span style="color: #7a0874; font-weight: bold;">&#91;</span>SFE<span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo sitio registrado en MBProxy SFE
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> - <span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo cliente: 190.136.29.16:<span style="color: #000000;">30519</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> - <span style="color: #7a0874; font-weight: bold;">&#93;</span> Total: <span style="color: #000000;">2</span>
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> - <span style="color: #7a0874; font-weight: bold;">&#93;</span> G24 dice:  :0090SFE00
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>SFE<span style="color: #7a0874; font-weight: bold;">&#93;</span> SITIO SFE
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">49</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>SFE<span style="color: #7a0874; font-weight: bold;">&#93;</span> SFE ya estaba conectado. Borrando anterior.
<span style="color: #000000;">2010</span>-05-<span style="color: #000000;">28</span> 07:<span style="color: #000000;">45</span>:<span style="color: #000000;">51</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>SFE<span style="color: #7a0874; font-weight: bold;">&#93;</span> Nuevo sitio registrado en MBProxy SFE</pre></div></div>

<p>Para cambiar aún más el formato de la salida, la única forma que encontré es extender <strong>FileLogObserver</strong> y sobreescribir su método <strong>emit</strong>. Discutimos un poco esto <a href="http://stackoverflow.com/questions/3700955/how-to-format-twisted-logs" target="_blank">en StackOverflow.</a></p>
<p><strong>nota:</strong> En Twisted también podemos usar el <a href="http://docs.python.org/library/logging.html" target="_blank">sistema de logging de Python</a>, esto tiene la ventaja de que podemos trabajar con niveles de log y controlar mejor el formato y la forma en que se generan los logs, pero el problema de que no está preparado para funcionar en forma asincrónica y esto puede traer algunos problemas con Twisted.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2010/09/14/cambiando-el-formato-de-los-logs-en-twisted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puedo disfrazar cualquier cosa de Modbus</title>
		<link>http://www.juanjoconti.com.ar/2010/08/06/puedo-disfrazar-cualquier-cosa-de-modbus/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puedo-disfrazar-cualquier-cosa-de-modbus</link>
		<comments>http://www.juanjoconti.com.ar/2010/08/06/puedo-disfrazar-cualquier-cosa-de-modbus/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 02:05:49 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[Modbus]]></category>
		<category><![CDATA[pymodbus]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SCADA]]></category>
		<category><![CDATA[twisted]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=2574</guid>
		<description><![CDATA[Hace más de un año participo en un proyecto de desarrollo de un sistema SCADA, específicamente en la capa de comunicación. La distribución física es algo como esto: En cada edificio hay una red 485 con dispositivos de hardware propio &#8230; <a href="http://www.juanjoconti.com.ar/2010/08/06/puedo-disfrazar-cualquier-cosa-de-modbus/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hace más de un año participo en un proyecto de desarrollo de un sistema <a href="http://es.wikipedia.org/wiki/SCADA" target="_blank">SCADA</a>, específicamente en la capa de comunicación. La distribución física es algo como esto:</p>
<p><a href="http://www.juanjoconti.com.ar/wp-content/uploads/2010/08/esquema_kimera.jpg"><img class="aligncenter size-large wp-image-2589" title="esquema_kimera" src="http://www.juanjoconti.com.ar/wp-content/uploads/2010/08/esquema_kimera-1024x595.jpg" alt="" width="640" height="371" /></a>En cada edificio hay una <a href="http://es.wikipedia.org/wiki/RS-485" target="_blank">red 485</a> con dispositivos de hardware propio (aka Robot) y un módulo celular (Motorolla G24) con salida a Internet vía GPRS. Esos módulos se registran en un servidor (escrito con <a href="http://twistedmatrix.com/" target="_blank">Twisted</a>) para ser luego sondeados: se registran sus mediciones, hay gráficos en tiempo real, se puede hacer telecomando y encender un equipo a la distancia o cambiar un set point; entre otras cosas.</p>
<p>Nuestra primera implementación estaba inspirada en el protocolo Modbus ASCII, pero bastante alejada del estándar. Nos sirvió por bastante tiempo y no apegarnos a una especificación nos permitió acelerar el desarrollo; especialmente del hardware.</p>
<p>Modbus es un protocolo de línea maestro/esclavo en donde el maestro realiza peticiones de lectura o escritura sobre algún o algunos registros en un esclavo. El protocolo define 4 tipos de registros (analógicos o digitales, de solo lectura o lectura-escritura) y fue pensado para funcionar sobre una línea serie; existen dos sabores: RTU, dónde los datos viajan en forma binaria y la ocupación del canal es optimizada y ASCII, menos eficiente pero legible por humanos. Se puedo leer más al respecto en <a href="http://es.wikipedia.org/wiki/Modbus" target="_blank">Wikipedia</a> o en la <a href="http://www.modbus.org/" target="_blank">página oficial del protocolo</a>.</p>
<p>Hace algunos meses empezamos a utilizar <a href="http://mango.serotoninsoftware.com/" target="_blank">Mango m2m</a>. Mango tiene todos los componentes de interfaz de usuario que se pueden necesitar en un SCADA en adición a la posibilidad de conectarle distintas fuentes de datos (desde Modbus Serie a un motor de base de datos); las más interesante para nosotros es Modbus TCP.<br />
<a href="http://www.juanjoconti.com.ar/wp-content/uploads/2010/08/mango.jpg"></a><a href="http://www.juanjoconti.com.ar/wp-content/uploads/2010/08/mango.jpg"><img class="aligncenter size-full wp-image-2603" title="mango" src="http://www.juanjoconti.com.ar/wp-content/uploads/2010/08/mango.jpg" alt="" width="572" height="413" /></a></p>
<p>Modbus TCP extiende el protocolo original para poder utilizarlo sobre la red de redes en lugar de sobre una línea serie. Por ejemplo, una de las cosas que hace es agregar al paquete enviado un número consecutivo para solucionar el problema de paquetes perdidos o duplicados.</p>
<p>Teníamos entonces, por un lado Mango que sabe hablar Modbus TCP y por el otro los robotitos hablando un dialecto de Modbus ASCII. En el medio, el servidor de comunicaciones. La pregunta en este punto era cómo unir ambos extremos, de manera de aprovechar esta herramienta que soluciona muchos de nuestros requerimientos.</p>
<p>Allí es donde entra en acción <a href="http://code.google.com/p/pymodbus/" target="_blank">pymodbus</a>, una implementación en Python del stack Modbus. No solo está escrita en Python, sino que está implementada utilizando el framework Twisted, el mismo que venía usando para el servidor de comunicaciones. Utilizando pymodbus pude engañar a Mango y hacerle creer que hablaba contar dispositivos Modbus TCP cuando en realidad interceptaba sus peticiones, enviaba los comandos necesarios a los robots y contestaba con la respuesta correcta.</p>
<p>En el camino encontré varios problemas en la librería, los fui reportando y enviando parches para solucionarlos. A lo último eran tanto los cambios que enviaba y empecé a modificar el core de la librería para que funcione con <a href="http://twistedmatrix.com/documents/current/core/howto/defer.html" target="_blank">deferrers</a> (es decir, siguiendo la filosofía de Twisted) que <a href="http://code.google.com/p/pymodbus/people/list" target="_blank">recibí permiso de commit</a> en la rama <a href="http://code.google.com/p/pymodbus/source/browse/#svn/branches/devel" target="_blank">devel</a>.</p>
<p><em>Nota: el esquema descripto funcionó bastante tiempo. Actualmente seguimos avanzando y los robots ya hablan Modbus ASCII estándar a la vez que el componente intermedio adelgazó para convertirse en un traductor o gateway.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2010/08/06/puedo-disfrazar-cualquier-cosa-de-modbus/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Charla relámpago: Comet en Twisted</title>
		<link>http://www.juanjoconti.com.ar/2009/09/06/charla-relampago-comet-en-twisted/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=charla-relampago-comet-en-twisted</link>
		<comments>http://www.juanjoconti.com.ar/2009/09/06/charla-relampago-comet-en-twisted/#comments</comments>
		<pubDate>Sun, 06 Sep 2009 02:16:39 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[pyconar09]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=1763</guid>
		<description><![CDATA[Ayer en las charlas relámpago de PyCon Argentina 2009 mostré cómo utilizar Comet desde Twisted. Tenía un slide disparador que no pude mostrar por que OpenOffice no se abrió y como las charlas relámpago duran 5 minutos, no podía darme &#8230; <a href="http://www.juanjoconti.com.ar/2009/09/06/charla-relampago-comet-en-twisted/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ayer en las <a href="http://ar.pycon.org/2009/conference/lightning/" target="_blank">charlas relámpago</a> de <a href="http://ar.pycon.org/2009/about/" target="_self">PyCon Argentina 2009</a> mostré cómo utilizar <a href="http://es.wikipedia.org/wiki/Comet" target="_blank">Comet</a> desde <a href="http://twistedmatrix.com/" target="_blank">Twisted</a>. Tenía <em>un</em> slide disparador que no pude mostrar por que OpenOffice no se abrió y como las charlas relámpago duran 5 minutos, no podía darme el lujo de investigar que pasaba.</p>
<p>&#8220;No importa&#8221;, dije, &#8220;de todas formas el slide tenía solo cuatro palabras&#8221;. Y para hacer justicia sobre las <a href="http://es.wikipedia.org/wiki/Ley_de_Murphy" target="_blank">Leyes de Murphy</a> publico aquí ese slide:</p>
<p><img class="aligncenter size-medium wp-image-1764" title="comet" src="http://www.juanjoconti.com.ar/wp-content/uploads/2009/09/comet-300x225.jpg" alt="comet" width="300" height="225" /><a href="http://www.divmod.org/trac/browser/trunk/Nevow/doc/howto/chattutorial/part01" target="_blank">El ejemplo que mostré en vivo puede bajarse del sitio web de Nevow/Athena.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2009/09/06/charla-relampago-comet-en-twisted/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Shell Python administrativo sobre SSH para tu servidor Twisted en 10 líneas</title>
		<link>http://www.juanjoconti.com.ar/2009/04/09/shell-python-administrativo-sobre-ssh-para-tu-servidor-twisted-en-10-lineas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=shell-python-administrativo-sobre-ssh-para-tu-servidor-twisted-en-10-lineas</link>
		<comments>http://www.juanjoconti.com.ar/2009/04/09/shell-python-administrativo-sobre-ssh-para-tu-servidor-twisted-en-10-lineas/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 05:30:10 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[twisted]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=1409</guid>
		<description><![CDATA[entre tu reactor.listeTCP(puerto, factory) y reactor.run(): from twisted.conch import manhole, manhole_ssh from twisted.cred import portal, checkers &#160; def getManholeFactory&#40;namespace, **passwords&#41;: realm = manhole_ssh.TerminalRealm&#40;&#41; def getManhole&#40;_&#41;: return manhole.Manhole&#40;namespace&#41; realm.chainedProtocolFactory.protocolFactory = getManhole p = portal.Portal&#40;realm&#41; p.registerChecker&#40; checkers.InMemoryUsernamePasswordDatabaseDontUse&#40;**passwords&#41;&#41; f = manhole_ssh.ConchFactory&#40;p&#41; return f &#8230; <a href="http://www.juanjoconti.com.ar/2009/04/09/shell-python-administrativo-sobre-ssh-para-tu-servidor-twisted-en-10-lineas/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>entre tu reactor.listeTCP(puerto, factory) y reactor.run():</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span> <span style="color: #ff7700;font-weight:bold;">import</span> manhole, manhole_ssh
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">cred</span> <span style="color: #ff7700;font-weight:bold;">import</span> portal, checkers 
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> getManholeFactory<span style="color: black;">&#40;</span>namespace, <span style="color: #66cc66;">**</span>passwords<span style="color: black;">&#41;</span>:
    realm = manhole_ssh.<span style="color: black;">TerminalRealm</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> getManhole<span style="color: black;">&#40;</span>_<span style="color: black;">&#41;</span>: <span style="color: #ff7700;font-weight:bold;">return</span> manhole.<span style="color: black;">Manhole</span><span style="color: black;">&#40;</span>namespace<span style="color: black;">&#41;</span>
    realm.<span style="color: black;">chainedProtocolFactory</span>.<span style="color: black;">protocolFactory</span> = getManhole
    p = portal.<span style="color: black;">Portal</span><span style="color: black;">&#40;</span>realm<span style="color: black;">&#41;</span>
    p.<span style="color: black;">registerChecker</span><span style="color: black;">&#40;</span>
    checkers.<span style="color: black;">InMemoryUsernamePasswordDatabaseDontUse</span><span style="color: black;">&#40;</span><span style="color: #66cc66;">**</span>passwords<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    f = manhole_ssh.<span style="color: black;">ConchFactory</span><span style="color: black;">&#40;</span>p<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> f
&nbsp;
reactor.<span style="color: black;">listenTCP</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2222</span>, getManholeFactory<span style="color: black;">&#40;</span><span style="color: #008000;">globals</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, admin=<span style="color: #483d8b;">'aaa'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Los aplausos para <a href="http://www.devshed.com/c/a/Python/SSH-with-Twisted/3/" target="_blank">este tutorial</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2009/04/09/shell-python-administrativo-sobre-ssh-para-tu-servidor-twisted-en-10-lineas/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Servidor SSH con Twisted</title>
		<link>http://www.juanjoconti.com.ar/2009/04/08/servidor-ssh-con-twisted/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=servidor-ssh-con-twisted</link>
		<comments>http://www.juanjoconti.com.ar/2009/04/08/servidor-ssh-con-twisted/#comments</comments>
		<pubDate>Wed, 08 Apr 2009 21:54:35 +0000</pubDate>
		<dc:creator>Juanjo</dc:creator>
				<category><![CDATA[Aprendiendo Python]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[twisted]]></category>

		<guid isPermaLink="false">http://www.juanjoconti.com.ar/?p=1403</guid>
		<description><![CDATA[Actualicé este ejemplo, tamibién incluido en el libro de Twisted para que no tire Deprecation Warnings: from twisted.cred import portal, checkers, credentials from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces from twisted.conch.ssh import factory, userauth, connection, keys, session, common &#8230; <a href="http://www.juanjoconti.com.ar/2009/04/08/servidor-ssh-con-twisted/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Actualicé <a href="http://www.devshed.com/c/a/Python/SSH-with-Twisted/" target="_blank">este ejemplo</a>, tamibién incluido en el <a href="http://books.google.com/books?id=Fm5kw3lZ7zEC&amp;printsec=frontcover&amp;hl=es&amp;source=gbs_summary_r&amp;cad=0" target="_blank">libro de Twisted</a> para que no tire Deprecation Warnings:</p>
<p><span id="more-1403"></span></p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">cred</span> <span style="color: #ff7700;font-weight:bold;">import</span> portal, checkers, credentials
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span> <span style="color: #ff7700;font-weight:bold;">import</span> error, avatar, recvline, interfaces <span style="color: #ff7700;font-weight:bold;">as</span> conchinterfaces
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span>.<span style="color: black;">ssh</span> <span style="color: #ff7700;font-weight:bold;">import</span> factory, userauth, connection, keys, session, common
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span>.<span style="color: black;">insults</span> <span style="color: #ff7700;font-weight:bold;">import</span> insults
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">application</span> <span style="color: #ff7700;font-weight:bold;">import</span> service, internet
<span style="color: #ff7700;font-weight:bold;">from</span> zope.<span style="color: black;">interface</span> <span style="color: #ff7700;font-weight:bold;">import</span> implements
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> SSHDemoProtocol<span style="color: black;">&#40;</span>recvline.<span style="color: black;">HistoricRecvLine</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #dc143c;">user</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: #dc143c;">user</span> = <span style="color: #dc143c;">user</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> connectionMade<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span> :
        recvline.<span style="color: black;">HistoricRecvLine</span>.<span style="color: black;">connectionMade</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Welcome to my test SSH server.&quot;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">do_help</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">showPrompt</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> showPrompt<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;$ &quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> getCommandFunc<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #dc143c;">cmd</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">getattr</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #483d8b;">'do_'</span> + <span style="color: #dc143c;">cmd</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> lineReceived<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, line<span style="color: black;">&#41;</span>:
        line = line.<span style="color: black;">strip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> line:
            cmdAndArgs = line.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #dc143c;">cmd</span> = cmdAndArgs<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
            args = cmdAndArgs<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span>
            func = <span style="color: #008000;">self</span>.<span style="color: black;">getCommandFunc</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">cmd</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">if</span> func:
               <span style="color: #ff7700;font-weight:bold;">try</span>:
                   func<span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span>
               <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">Exception</span>, e:
                   <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Error: %s&quot;</span> <span style="color: #66cc66;">%</span> e<span style="color: black;">&#41;</span>
                   <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">else</span>:
               <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;No such command.&quot;</span><span style="color: black;">&#41;</span>
               <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">showPrompt</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_help<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #dc143c;">cmd</span>=<span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;Get help on a command. Usage: help command&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #dc143c;">cmd</span>:
            func = <span style="color: #008000;">self</span>.<span style="color: black;">getCommandFunc</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">cmd</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">if</span> func:
                <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>func.__doc__<span style="color: black;">&#41;</span>
                <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
                <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
        publicMethods = <span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>
            <span style="color: #ff7700;font-weight:bold;">lambda</span> funcname: funcname.<span style="color: black;">startswith</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'do_'</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">dir</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">commands</span> = <span style="color: black;">&#91;</span><span style="color: #dc143c;">cmd</span>.<span style="color: black;">replace</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'do_'</span>, <span style="color: #483d8b;">''</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> <span style="color: #dc143c;">cmd</span> <span style="color: #ff7700;font-weight:bold;">in</span> publicMethods<span style="color: black;">&#93;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Commands: &quot;</span> + <span style="color: #483d8b;">&quot; &quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">commands</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_echo<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;Echo a string. Usage: echo my line of text&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot; &quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>args<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_whoami<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;Prints your user name. Usage: whoami&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: #dc143c;">user</span>.<span style="color: black;">username</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_quit<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;Ends your session. Usage: quit&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Thanks for playing!&quot;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">nextLine</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">loseConnection</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_clear<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;Clears the screen. Usage: clear&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">terminal</span>.<span style="color: black;">reset</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> SSHDemoAvatar<span style="color: black;">&#40;</span>avatar.<span style="color: black;">ConchUser</span><span style="color: black;">&#41;</span>:
    implements<span style="color: black;">&#40;</span>conchinterfaces.<span style="color: black;">ISession</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, username<span style="color: black;">&#41;</span>:
        avatar.<span style="color: black;">ConchUser</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">username</span> = username
        <span style="color: #008000;">self</span>.<span style="color: black;">channelLookup</span>.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#123;</span><span style="color: #483d8b;">'session'</span>:session.<span style="color: black;">SSHSession</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> openShell<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, protocol<span style="color: black;">&#41;</span>:
        serverProtocol = insults.<span style="color: black;">ServerProtocol</span><span style="color: black;">&#40;</span>SSHDemoProtocol, <span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        serverProtocol.<span style="color: black;">makeConnection</span><span style="color: black;">&#40;</span>protocol<span style="color: black;">&#41;</span>
        protocol.<span style="color: black;">makeConnection</span><span style="color: black;">&#40;</span>session.<span style="color: black;">wrapProtocol</span><span style="color: black;">&#40;</span>serverProtocol<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> getPty<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, terminal, windowSize, attrs<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">None</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> execCommand<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, protocol, <span style="color: #dc143c;">cmd</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">raise</span> <span style="color: #008000;">NotImplementedError</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> closed<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">pass</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> SSHDemoRealm:
    implements<span style="color: black;">&#40;</span>portal.<span style="color: black;">IRealm</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> requestAvatar<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, avatarId, mind, <span style="color: #66cc66;">*</span>interfaces<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> conchinterfaces.<span style="color: black;">IConchUser</span> <span style="color: #ff7700;font-weight:bold;">in</span> interfaces:
            <span style="color: #ff7700;font-weight:bold;">return</span> interfaces<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>, SSHDemoAvatar<span style="color: black;">&#40;</span>avatarId<span style="color: black;">&#41;</span>, <span style="color: #ff7700;font-weight:bold;">lambda</span>: <span style="color: #008000;">None</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #ff7700;font-weight:bold;">raise</span> <span style="color: #008000;">Exception</span>, <span style="color: #483d8b;">&quot;No supported interfaces found.&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> getRSAKeys<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">exists</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'public.key'</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">and</span> <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">exists</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'private.key'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;"># generate a RSA keypair</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Generating RSA keypair...&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">from</span> Crypto.<span style="color: black;">PublicKey</span> <span style="color: #ff7700;font-weight:bold;">import</span> RSA
        KEY_LENGTH = <span style="color: #ff4500;">1024</span>
        rsaKey = RSA.<span style="color: black;">generate</span><span style="color: black;">&#40;</span>KEY_LENGTH, common.<span style="color: black;">entropy</span>.<span style="color: black;">get_bytes</span><span style="color: black;">&#41;</span>
        publicKeyString = keys.<span style="color: black;">Key</span><span style="color: black;">&#40;</span>rsaKey<span style="color: black;">&#41;</span>.<span style="color: black;">toString</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        privateKeyString = keys.<span style="color: black;">makePrivateKeyString</span><span style="color: black;">&#40;</span>rsaKey<span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># save keys for next time</span>
        <span style="color: #008000;">file</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'public.key'</span>, <span style="color: #483d8b;">'w+b'</span><span style="color: black;">&#41;</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>publicKeyString<span style="color: black;">&#41;</span>
        <span style="color: #008000;">file</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'private.key'</span>, <span style="color: #483d8b;">'w+b'</span><span style="color: black;">&#41;</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>privateKeyString<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;done.&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        publicKeyString = <span style="color: #008000;">file</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'public.key'</span><span style="color: black;">&#41;</span>.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        privateKeyString = <span style="color: #008000;">file</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'private.key'</span><span style="color: black;">&#41;</span>.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> publicKeyString, privateKeyString
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    sshFactory = factory.<span style="color: black;">SSHFactory</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    sshFactory.<span style="color: black;">portal</span> = portal.<span style="color: black;">Portal</span><span style="color: black;">&#40;</span>SSHDemoRealm<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    users = <span style="color: black;">&#123;</span><span style="color: #483d8b;">'admin'</span>: <span style="color: #483d8b;">'aaa'</span>, <span style="color: #483d8b;">'guest'</span>: <span style="color: #483d8b;">'bbb'</span><span style="color: black;">&#125;</span>
    sshFactory.<span style="color: black;">portal</span>.<span style="color: black;">registerChecker</span><span style="color: black;">&#40;</span>
 checkers.<span style="color: black;">InMemoryUsernamePasswordDatabaseDontUse</span><span style="color: black;">&#40;</span><span style="color: #66cc66;">**</span>users<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    pubKeyString, privKeyString = getRSAKeys<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    sshFactory.<span style="color: black;">publicKeys</span> = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">'ssh-rsa'</span>: keys.<span style="color: black;">Key</span>.<span style="color: black;">fromString</span><span style="color: black;">&#40;</span>pubKeyString<span style="color: black;">&#41;</span><span style="color: black;">&#125;</span>
    sshFactory.<span style="color: black;">privateKeys</span> = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">'ssh-rsa'</span>: keys.<span style="color: black;">Key</span>.<span style="color: black;">fromString</span><span style="color: black;">&#40;</span>privKeyString<span style="color: black;">&#41;</span><span style="color: black;">&#125;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">internet</span> <span style="color: #ff7700;font-weight:bold;">import</span> reactor
    reactor.<span style="color: black;">listenTCP</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2222</span>, sshFactory<span style="color: black;">&#41;</span>
    reactor.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.juanjoconti.com.ar/2009/04/08/servidor-ssh-con-twisted/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

