<?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>John Roach &#187; python</title>
	<atom:link href="http://johnroach.info/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnroach.info</link>
	<description>Coding for life</description>
	<lastBuildDate>Wed, 18 Jan 2012 19:30:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Image Capturing from WebCAM using OpenCV and Pygame in Python</title>
		<link>http://johnroach.info/2011/03/02/image-capturing-from-webcam-using-opencv-and-pygame-in-python/</link>
		<comments>http://johnroach.info/2011/03/02/image-capturing-from-webcam-using-opencv-and-pygame-in-python/#comments</comments>
		<pubDate>Wed, 02 Mar 2011 16:03:29 +0000</pubDate>
		<dc:creator>John Roach</dc:creator>
				<category><![CDATA[Coding for fun]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[opencv]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[webcam]]></category>

		<guid isPermaLink="false">http://johnroach.info/?p=545</guid>
		<description><![CDATA[I know there a lot of examples of WebCAM image capturing on the net. Mine is one of that but the main difference is that this little script here simply captures frames in a certain fps and simply saves those &#8230; <a href="http://johnroach.info/2011/03/02/image-capturing-from-webcam-using-opencv-and-pygame-in-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I know there a lot of examples of WebCAM image capturing on the net. Mine is one of that but the main difference is that this little script here simply captures frames in a certain fps and simply saves those images. There a numerous usages fro such a thing. One usage could be a script that uploads this image to a certain ftp site so you can display it in your web page. I needed this little script to follow a moving object. I did not write the whole script. You may think this as a little upgrade from <a href="http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux" target="_blank">the one on the internet</a>. The script uses OpenCV and Pygame libs. Without further ado the script :</p>
<pre name="code" class="python">import pygame
import Image
from pygame.locals import *
import sys

import opencv
import cv

#this is important for capturing/displaying images
from opencv import highgui

camera = highgui.cvCreateCameraCapture(0)
i=0
def get_image():
    im = highgui.cvQueryFrame(camera)
    # Add the line below if you need it (Ubuntu 8.04+)
    #im = opencv.cvGetMat(im)
    #convert Ipl image to PIL image
    return opencv.adaptors.Ipl2PIL(im)

fps = 25.0
pygame.init()
window = pygame.display.set_mode((640,480))
pygame.display.set_caption("WebCAM Demo")
screen = pygame.display.get_surface()

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == QUIT or event.type == KEYDOWN:
            sys.exit(0)
    im = get_image()
    if i&gt;100:
	#allowing the camera to focus
	#auto focus is really annoying
        im.save("image_"+str(i)+"", "JPEG")
    i=i+1
    pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)

    screen.blit(pg_img, (0,0))
    pygame.display.flip()
    pygame.time.delay(int(1000 * 1.0/fps))</pre>
]]></content:encoded>
			<wfw:commentRss>http://johnroach.info/2011/03/02/image-capturing-from-webcam-using-opencv-and-pygame-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting raw data from a USB mouse in Linux using Python</title>
		<link>http://johnroach.info/2011/02/16/getting-raw-data-from-a-usb-mouse-in-linux-using-python/</link>
		<comments>http://johnroach.info/2011/02/16/getting-raw-data-from-a-usb-mouse-in-linux-using-python/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 07:15:32 +0000</pubDate>
		<dc:creator>John Roach</dc:creator>
				<category><![CDATA[Coding for fun]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mice]]></category>
		<category><![CDATA[mouse]]></category>
		<category><![CDATA[multiple]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[raw data]]></category>
		<category><![CDATA[usb]]></category>

		<guid isPermaLink="false">http://johnroach.info/?p=534</guid>
		<description><![CDATA[If you are geek your mouth should be watering by now. I will like to thank Oscar Lindberg and his cool Linux friend for this code! I was trying to get multiple-mice movement data. This is the code that got &#8230; <a href="http://johnroach.info/2011/02/16/getting-raw-data-from-a-usb-mouse-in-linux-using-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you are geek your mouth should be watering by now. I will like to thank Oscar Lindberg and his cool Linux friend for this code! I was trying to get multiple-mice movement data. This is the code that got me started. Once I beautify my multiple-mouse code I will be posting it here as well. Without further ado :</p>
<pre name="code" class="py">
mouse = file('/dev/input/mouse0')
while True:
    status, dx, dy = tuple(ord(c) for c in mouse.read(3))

    def to_signed(n):
        return n - ((0x80 &#038; n) << 1)

    dx = to_signed(dx)
    dy = to_signed(dy)
    print "%#02x %d %d" % (status, dx, dy)
</pre>
<p>I hope this just made your day!</p>
]]></content:encoded>
			<wfw:commentRss>http://johnroach.info/2011/02/16/getting-raw-data-from-a-usb-mouse-in-linux-using-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>From the beginning please</title>
		<link>http://johnroach.info/2010/10/11/from-the-beginning-please/</link>
		<comments>http://johnroach.info/2010/10/11/from-the-beginning-please/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 15:24:10 +0000</pubDate>
		<dc:creator>John Roach</dc:creator>
				<category><![CDATA[just fun]]></category>
		<category><![CDATA[grandpa]]></category>
		<category><![CDATA[IBM]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[john roach]]></category>
		<category><![CDATA[Jython]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[renko]]></category>

		<guid isPermaLink="false">http://johnroach.info/?p=382</guid>
		<description><![CDATA[Hi there. Summer over and so is my work with the company RENKO ITH.  IHR. LTD. STI.. Worked for peanuts doing lots. Proud of it. Paid my school tuition with the peanuts. I think this makes my school a three &#8230; <a href="http://johnroach.info/2010/10/11/from-the-beginning-please/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hi there. Summer over and so is my work with the company RENKO ITH.  IHR. LTD. STI.. Worked for peanuts doing lots. Proud of it. Paid my school tuition with the peanuts. I think this makes my school a <a class="zem_slink" title="Circus" rel="wikipedia" href="http://en.wikipedia.org/wiki/Circus">three ring circus</a> <img src='http://johnroach.info/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> .</p>
<p>Work was good and honest in RENKO. I wore three hats at all times ;</p>
<p><span id="more-382"></span></p>
<p style="padding-left: 60px;"><strong>Hat#1. </strong>Software Engineer/Programmer : Basically I wrote one main program and couple of dozen other programs. The main program used the following languages; <a class="zem_slink" title="Python (programming language)" rel="wikipedia" href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, <a class="zem_slink" title="PHP" rel="wikipedia" href="http://en.wikipedia.org/wiki/PHP">PHP</a>, C, <a class="zem_slink" title="JavaScript" rel="wikipedia" href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a>. The small scripts I wrote used <a class="zem_slink" title="Jython" rel="wikipedia" href="http://en.wikipedia.org/wiki/Jython">Jython</a>. And as for what these programs did; <a class="zem_slink" title="Picasa" rel="homepage" href="http://picasa.google.com/">Picassa</a> and/or <a class="zem_slink" title="Flickr" rel="homepage" href="http://flickr.com">Flickr</a> like internet site. Processed image.</p>
<p style="padding-left: 60px;"><strong>Hat#2. </strong><a class="zem_slink" title="Network engineer" rel="wikipedia" href="http://en.wikipedia.org/wiki/Network_engineer">Network Engineer</a> : As you may have read from <a href="http://johnroach.info/2010/06/being-the-master-of-a-ibm-x3200/" target="_blank">the previous post</a> I set up an <a class="zem_slink" title="IBM" rel="wikipedia" href="http://en.wikipedia.org/wiki/IBM">IBM</a> server and changed the whole <a class="zem_slink" title="Network topology" rel="wikipedia" href="http://en.wikipedia.org/wiki/Network_topology">network topology</a>. (Argh! moment here) Lots of manual labor. However now the company has a faster and secured network. My biggest problem was parts. Network parts are really expensive. And trying to do it cheap is really hard.</p>
<p style="padding-left: 60px;"><strong>Hat#3. </strong>Floor manager in a photo shop : Yeah you heard it here, John Roach worked as a mean guy trying to sell wedding photos to young couples. This hat I must admit I didn&#8217;t really like. Not because it was hard or it was all about selling. But because the person before me was just so&#8230; how can I put it politically correct&#8230; basically he was messy. Can&#8217;t tell everything on the internet can we?</p>
<p>Just because I worked hard doesn&#8217;t mean I didn&#8217;t have fun. I had lots of it. And learned a lot! The one thing I am proud to say I have learned is Jython! What a quick fix language! And the other thing is Image processing. A hands out to <a class="zem_slink" title="OpenCV" rel="wikipedia" href="http://en.wikipedia.org/wiki/OpenCV">Open-CV</a> and Python Image Library (PIL).</p>
<p>And talking of a good summer. My grandpa came all the way from a far land called USA. This his first visit to Turkey! So we are very happy to have him. We are trying to con him in to staying here in Turkey.  Me and my brother already has plans to hide his tickets and shoes. Don&#8217;t know if it will work or not. Mom will probably catch up to us. Meh&#8230; My love met my grandfather. They seemed to like each other which is also good <img src='http://johnroach.info/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Below you will see images from my work place and my love with grandpa. Enjoy!</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="600" height="400" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="flashvars" value="host=picasaweb.google.com&amp;hl=en_GB&amp;feat=flashalbum&amp;RGB=0x000000&amp;feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2Fjohnroach1985%2Falbumid%2F5526800870689483185%3Falt%3Drss%26kind%3Dphoto%26hl%3Den_GB" /><param name="src" value="http://picasaweb.google.com/s/c/bin/slideshow.swf" /><embed type="application/x-shockwave-flash" width="600" height="400" src="http://picasaweb.google.com/s/c/bin/slideshow.swf" flashvars="host=picasaweb.google.com&amp;hl=en_GB&amp;feat=flashalbum&amp;RGB=0x000000&amp;feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2Fjohnroach1985%2Falbumid%2F5526800870689483185%3Falt%3Drss%26kind%3Dphoto%26hl%3Den_GB"></embed></object></p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/"><img class="zemanta-pixie-img" style="border: none; float: right;" src="http://img.zemanta.com/zemified_e.png?x-id=c4453c81-b8a4-4d0d-836d-fc96365ac4aa" alt="Enhanced by Zemanta" /></a><span class="zem-script more-related pretty-attribution"><script src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://johnroach.info/2010/10/11/from-the-beginning-please/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing Ångström Linux on BeagleBoard</title>
		<link>http://johnroach.info/2009/11/27/installing-angstrom-linux-on-beagleboard/</link>
		<comments>http://johnroach.info/2009/11/27/installing-angstrom-linux-on-beagleboard/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 07:57:21 +0000</pubDate>
		<dc:creator>John Roach</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[ip home automation project]]></category>
		<category><![CDATA[angstrom]]></category>
		<category><![CDATA[beagleboard]]></category>
		<category><![CDATA[embedded device]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[paramiko]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[sd card]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://johnroach.info/?p=164</guid>
		<description><![CDATA[We have been able to install Ångström Linux to our beagle board. Ran into couple problems. The first one was we trusted BeagleBoard Beginners wiki just too much!! You see we learned that we should NOT set any environment variables while using &#8230; <a href="http://johnroach.info/2009/11/27/installing-angstrom-linux-on-beagleboard/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We have been able to install Ångström Linux to our beagle board. Ran into couple problems. The first one was we trusted <a title="BeagleBoardBeginners Wiki" href="http://elinux.org/BeagleBoardBeginners" target="_blank">BeagleBoard Beginners</a> wiki just too much!!</p>
<p>You see we learned that we should NOT set any environment variables while using demo u-boot image which was downloaded from <a title="Angstrom demo images" href="http://www.angstrom-distribution.org/demo/beagleboard/" target="_blank">here</a>. In fact what we did is we created our own Ångström image (from Ångström site) and simply installed that to our Linux partition of our SDHC card. And it worked beautifully. Though I must say first boot is a drag, very very slow.</p>
<p><span id="more-164"></span></p>
<p>Ran to some problems again. It seems BeagleBoard only works with DVI-D LCD&#8217;s and we had a HDMI to VGA instead of a HDMI to DVI-D cable.We ended up connecting to it from SSH and installing our programs like that. We really don&#8217;t need an LCD any time soon. And to connect to it from SSH we had to learn it&#8217;s IP from terminal. So no problems there. And we were very happy with the outcome.</p>
<div class="flashalbum">
<div class="flagallery_swfobject" id="sid_52173980_div"><style type="text/css">
.flashalbum { clear: both; }
.flag_alternate { display: none; }
.flag_alternate .flagcatlinks { padding: 7px 3px; margin:0 0 3px; background-color: #292929; }
.flag_alternate .flagcatlinks a.flagcat { padding: 4px 10px; margin: 0; border: none; border-left: 1px dotted #ffffff; font: 14px Tahoma; text-decoration: none; background: none; color: #ffffff; background-color: #292929; }
.flag_alternate .flagcatlinks a.flagcat:hover { text-decoration: none; background: none; border: none; border-left: 1px dotted #ffffff; }
.flag_alternate .flagcatlinks a.active, .flag_alternate .flagcatlinks a.flagcat:hover { color: #ffffff; background-color: #737373; outline: none; }
.flag_alternate .flagcatlinks a.flagcat:first-child { border: none; }
.flag_alternate .flagcategory { display: none; font-size: 0; line-height: 0; }
.flag_alternate { background-color: transparent; margin: 7px 0; }
.flag_alternate .flagcategory { width: 100%; height: auto; position: relative; text-align: center; padding-bottom: 4px; }
.flag_alternate .flagcategory a.flag_pic_alt { display: inline-block; margin: 1px 0 0 1px; padding: 0; height: 100px; width: 115px; line-height: 96px; position:relative; z-index: 2; text-align: center; z-index:99; cursor:pointer; background-color: #ffffff; border: 2px solid #ffffff; text-decoration: none; background-image: url(http://johnroach.info/wp-content/plugins/flash-album-gallery/admin/images/loadingAnimation.gif); background-repeat: no-repeat; background-position: 50% 50%; font-size: 8px; color: #ffffff; }
.flag_alternate .flagcategory a.flag_pic_alt > .flag_pic_desc { display: none; padding: 4px; line-height: 140%; font-size: 12px; }
.flag_alternate .flagcategory a.flag_pic_alt > .flag_pic_desc * { display: none; line-height: 140%; font-size: 12px !important; }
.flag_alternate .flagcategory a.flag_pic_alt:hover { background-color: #ffffff; border: 2px solid #4a4a4a; color: #4a4a4a; text-decoration: none; z-index: 3; }
.flag_alternate .flagcategory a.flag_pic_alt.current, .flag_alternate .flagcategory a.flag_pic_alt.last { border-color: #4a4a4a; }
.flag_alternate .flagcategory a.flag_pic_alt > img { vertical-align: middle; display:inline-block; position: static; margin: 0 auto; padding: 0; border: none; height: 100px !important; width: 115px !important; max-width: 115px; min-width: 115px; }

#fancybox-title-over .title { color: #ff9900; }
#fancybox-title-over .descr { color: #cfcfcf; }
.flag_alternate .flagcatlinks { background-color: #292929; }
.flag_alternate .flagcatlinks a.flagcat { border-color: #ffffff; color: #ffffff; background-color: #292929; }
.flag_alternate .flagcatlinks a.flagcat:hover { border-color: #ffffff; }
.flag_alternate .flagcatlinks a.active, .flag_alternate .flagcatlinks a.flagcat:hover { color: #ffffff; background-color: #737373; }
	.flag_alternate .flagcategory a.flag_pic_alt { background-color: #ffffff; border: 2px solid #ffffff; color: #ffffff; }
.flag_alternate .flagcategory a.flag_pic_alt:hover { background-color: #ffffff; border: 2px solid #4a4a4a; color: #4a4a4a; }
.flag_alternate .flagcategory a.flag_pic_alt.current, .flag_alternate .flagcategory a.flag_pic_alt.last { border-color: #4a4a4a; }
</style>
<script type="text/javascript">var ExtendVar='http://johnroach.info/wp-content/plugins/flash-album-gallery/';</script>
<div id="sid_52173980_jq" class="flag_alternate">
		<div class="flagcatlinks"></div>
			<div class="flagCatMeta">
			<h4>angstrombeagleboard</h4>
			<p></p>
		</div>
		<div class="flagcategory" id="gid_4_sid_52173980">
			<a class="i0 flag_pic_alt" href="http://johnroach.info/wp-content/flagallery/angstrombeagleboard/angstrom.png" id="flag_pic_5" rel="gid_4_sid_52173980" title="">[img src=http://johnroach.info/wp-content/flagallery/angstrombeagleboard/thumbs/thumbs_angstrom.png]<span class="flag_pic_desc" id="flag_desc_5"><strong></strong><br /><span></span></span></a><a class="i1 flag_pic_alt" href="http://johnroach.info/wp-content/flagallery/angstrombeagleboard/image000.jpg" id="flag_pic_6" rel="gid_4_sid_52173980" title="">[img src=http://johnroach.info/wp-content/flagallery/angstrombeagleboard/thumbs/thumbs_image000.jpg]<span class="flag_pic_desc" id="flag_desc_6"><strong></strong><br /><span></span></span></a><a class="i2 flag_pic_alt" href="http://johnroach.info/wp-content/flagallery/angstrombeagleboard/image001.jpg" id="flag_pic_8" rel="gid_4_sid_52173980" title="">[img src=http://johnroach.info/wp-content/flagallery/angstrombeagleboard/thumbs/thumbs_image001.jpg]<span class="flag_pic_desc" id="flag_desc_8"><strong></strong><br /><span></span></span></a>		</div>
	</div>

</div></div>
<script type="text/javascript" defer="defer">
flag_alt['sid_52173980'] = jQuery("div#sid_52173980_jq").clone().wrap(document.createElement('div')).parent().html();
var sid_52173980_div = {
	params : {
		wmode : "opaque",
		allowfullscreen : "true",
		allowScriptAccess : "always",
		saling : "lt",
		scale : "noScale",
		menu : "false",
		bgcolor : "##262626"},
	flashvars : {
		path : "http://johnroach.info/wp-content/plugins/flagallery-skins/default/",
		gID : "4",
		galName : "Gallery",
		skinID : "sid_52173980",
		postID : "164",
		postTitle : "Installing+%C3%85ngstr%C3%B6m+Linux+on+BeagleBoard+"},
	attr : {
		styleclass : "flashalbum",
		id : "sid_52173980"},
	start : function() {
		swfobject.embedSWF("http://johnroach.info/wp-content/plugins/flagallery-skins/default/gallery.swf", "sid_52173980_div", "100%", "500", "10.1.52", "http://johnroach.info/wp-content/plugins/flash-album-gallery/skins/expressInstall.swf", this.flashvars, this.params , this.attr );
swfobject.createCSS("#sid_52173980","outline:none");
	}
}
sid_52173980_div.start();
</script>
<p>Installing python libraries; as installing python libraries go this one was a little tricky. You see it seems that Ångström doesn&#8217;t update its python libs that frequently. So calling the package by</p>
<p><code>opkg intall python-pycrypto</code></p>
<p>Didn&#8217;t quite work since installed itself to python2.5 directory. Had to install pycrypto manually. I hated every moment of it. I  than uploaded my own program and I was very happy with the outcome. The program worked perfectly.</p>
<p>Stay tuned for more updates on The Black Box project! Remember you can find it at<a href="http://sourceforge.net/projects/theblackbox/">http://sourceforge.net/projects/theblackbox/</a> .</p>
<p>Live coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://johnroach.info/2009/11/27/installing-angstrom-linux-on-beagleboard/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Workflow of the BlackBox System and Connecting in Two Steps (Python+SSH)</title>
		<link>http://johnroach.info/2009/10/31/workflow-of-the-blackbox-system-and-connecting-in-two-steps-pythonssh/</link>
		<comments>http://johnroach.info/2009/10/31/workflow-of-the-blackbox-system-and-connecting-in-two-steps-pythonssh/#comments</comments>
		<pubDate>Sat, 31 Oct 2009 19:00:12 +0000</pubDate>
		<dc:creator>John Roach</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[ip home automation project]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[paramiko]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://johnroach.info/?p=97</guid>
		<description><![CDATA[If you have been following this blog you probably knew that this post was coming. I have been able to use SSH and Python together with some dependencies. These dependencies are Paramiko from http://www.lag.net/paramiko/ and a python sript (which I &#8230; <a href="http://johnroach.info/2009/10/31/workflow-of-the-blackbox-system-and-connecting-in-two-steps-pythonssh/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you have been following this blog you probably knew that this post was coming. I have been able to use SSH and Python together with some dependencies. These dependencies are Paramiko from <a href="http://www.lag.net/paramiko/ " target="_blank">http://www.lag.net/paramiko/</a> and a python sript (which I had to edit more on that later) which was written by Zeth from  <a href="http://commandline.org.uk" target="_blank">http://commandline.org.uk</a>.</p>
<p>In this short time using python let me say that it is a very organic programming language that should bring happiness to all programmer that have been muddling with other scripting languages. Saying that let&#8217;s go back to business.</p>
<p style="text-align: left;">Because I changed from Telnet to SSH some things had to change. A new design frenzy ensued. And the result was as below.</p>
<div id="attachment_98" class="wp-caption aligncenter" style="width: 583px"><a href="http://johnroach.info/wp-content/uploads/2009/10/connectionsteps.png"><img class="size-large wp-image-98  " title="connectionsteps" src="http://johnroach.info/wp-content/uploads/2009/10/connectionsteps-1024x640.png" alt="connectionsteps" width="573" height="358" /></a><p class="wp-caption-text">connectionsteps</p></div>
<p>Please click on the image above to see it more clearly.</p>
<p style="text-align: left;">So let my explain the above flow step by step.</p>
<p><span id="more-97"></span></p>
<p style="text-align: left;">First of all let us first check out the dependencies. The first dependency is Paramiko. You can download it from <a href="http://www.lag.net/paramiko/ " target="_blank">http://www.lag.net/paramiko/</a>. Paramiko has two dependencies. Phython and pycrypto. You can get pycrypto by using</p>
<p><code>#yum install python-pycrypto*</code></p>
<p style="text-align: left;">or</p>
<p><code>#yum install pycrypto</code></p>
<p>If none of the above work than you have to do it the hardware. I myself built pycrypto and paramiko myself. I used no RPM packages. For that I am proud of myself. However if you really need the rpm packages for paramiko you can find it from <a href="http://dag.wieers.com/rpm/packages/python-paramiko/" target="_blank">http://dag.wieers.com/rpm/packages/python-paramiko/</a>.</p>
<p>So now you have Paramiko. However you will quickly notice that learning all the nice things that Paramiko does takes time and if you are hard-pressed on time like me you can simply download a friendly Python SSH2 interface written by Zeth from <a href="http://commandline.org.uk/" target="_blank">http://commandline.org.uk</a>.</p>
<p>Now let&#8217;s first check this interface ;</p>
<pre  name="code" class="python">"""Friendly Python SSH2 interface."""
"""Created by Zeth from  http://commandline.org.uk"""
"""Edited by John Roach from http://johnroach.info"""

import os
import tempfile
import paramiko
import sys

class Connection(object):
"""Connects and logs into the specified hostname.
Arguments that are not given are guessed from the environment."""

def __init__(self,
host,
username = None,
private_key = None,
password = None,
port = 22,
):
self._sftp_live = False
self._sftp = None
if not username:
username = os.environ['LOGNAME']

# Log to a temporary file.
templog = tempfile.mkstemp('.txt', 'ssh-')[1]
paramiko.util.log_to_file(templog)

# Begin the SSH transport.
self._transport = paramiko.Transport((host, port))
self._tranport_live = True
# Authenticate the transport.
if password:
# Using Password.
self._transport.connect(username = username, password = password)
else:
# Use Private Key.
if not private_key:
# Try to use default key.
if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
private_key = '~/.ssh/id_rsa'
elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
private_key = '~/.ssh/id_dsa'
else:
raise (TypeError, "You have not specified a password or key.")

private_key_file = os.path.expanduser(private_key)
rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
self._transport.connect(username = username, pkey = rsa_key)

def _sftp_connect(self):
"""Establish the SFTP connection."""
if not self._sftp_live:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp_live = True

def get(self, remotepath, localpath = None):
"""Copies a file between the remote host and the local host."""
if not localpath:
localpath = os.path.split(remotepath)[1]
self._sftp_connect()
self._sftp.get(remotepath, localpath)

def put(self, localpath, remotepath = None):
"""Copies a file between the local host and the remote host."""
if not remotepath:
remotepath = os.path.split(localpath)[1]
self._sftp_connect()
self._sftp.put(localpath, remotepath)

def execute(self, command):
"""Execute the given commands on a remote machine."""
channel = self._transport.open_session()
channel.exec_command(command)
output = channel.makefile('rb', -1).readlines()
if output:
"""This line has been added to ssh.py by John Roach"""
for line in output:
print (line.strip('\n'))
"""This line has been added to ssh.py by John Roach"""
return output
else:
return channel.makefile_stderr('rb', -1).readlines()

def close(self):
"""Closes the connection and cleans up."""
# Close SFTP Connection.
if self._sftp_live:
self._sftp.close()
self._sftp_live = False
# Close the SSH Transport.
if self._tranport_live:
self._transport.close()
self._tranport_live = False

def __del__(self):
"""Attempt to clean up if not explicitly closed."""
self.close()

def main():
"""Little test when called directly."""
# Set these to your own details.
myssh = Connection('example.com')
myssh.put('ssh.py')
myssh.close()

# start the ball rolling.
if __name__ == "__main__":
main()</pre>
<p>So you can see above what I changed. I simply added a way to get the output of any SSH command.</p>
<p>The other dependency for my main program is functions.py this is where I hold my functions so the main Python file can be easier to read. I don&#8217;t know if this is good practice or not in Python programming language. But I thought I looked more pleasing like this.</p>
<p>Hence let&#8217;s check out our functions.py file;</p>
<pre  name="code" class="python">import os
import sys
import urllib
import re

class func(object):

def getMacAddress(self, type):
"""
This has been added by John Roach.
works in both windows and linux
Why Windows? Because I can!!!
"""

if sys.platform == 'win32':
for line in os.popen("ipconfig /all"):
if line.lstrip().startswith('Physical Address'):
mac = line.split(':')[1].strip().replace('-',':')
break
else:
for line in os.popen("/sbin/ifconfig"):
if line.find(type) &gt; -1:
mac = line.split()[4]
break
return mac

def getIPAddress(self):
"""
This program gets your external ip
from whatismyip.com
this program must be called every
5 minutes not more or else you must
have your own server.
"""
site = urllib.urlopen("http://www.whatismyip.com/automation/n09230945.asp").read()
grab = re.findall('\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3}',site)
address = grab[0]
return address</pre>
<p>Probably need some explaining on the functions. <strong>getMacAddress</strong> simply gets the MAC address of the embedded board. This function can work on both Windows and Linux. Why? Because I can! <img src='http://johnroach.info/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  <strong>getIPAddress </strong>finds out your external address. You must remember if you did the simple host trick in python you will get your LAN IP. However what I needed was the external address. So I simple steal it from www.whatismyip.com. These functions are called within the main program.</p>
<p>So atlast. The main program sshtry.py ;</p>
<pre  name="code" class="python">import ssh
import functions

""" This connection is basicly to the server                    """
""" For testing this is basicly my desktop-computer running     """
""" A special user has been created for this project with       """
""" limited privilages this user is johnroach                   """
""" The IP of the server is IP                       """
s = ssh.Connection(host = 'IP, username = 'username', password = 'passowrd')

""" Calling the functions functions <img src='http://johnroach.info/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  """
f = functions.func()

"""          Get MAC           """
"""Ethernet = eth  Wi-Fi = wlan"""
mac = f.getMacAddress(type = 'wlan')

"""          Get IP         """
ip = f.getIPAddress()

s.execute('python getip.py '+mac+' '+ip)

s.close()</pre>
<p>I bet you can guess what this program does. But please remember getip.py is actually in the server and is called using SSH.</p>
<p>So now we finished with the embedded device side of the problem. Now we have to see what happens in the server side.</p>
<p>The server side programs ( getipmac.py ) dependencies are different. We really don&#8217;t need SSH and we are simply going to connect to the MySQL database. For this we use a interface named MySQLdb. MySQLdb can be downloaded from http://sourceforge.net/projects/mysql-python/ or simply installed by using<br />
<code><br />
#yum install mysql-python<br />
</code><br />
getipmac.py simply gets the MAC and IP address of the embedded device and stores it in the database. The two parameters are called when the scripts is executed. The program is as below;</p>
<pre name="code"  class="python">import sys
import MySQLdb

if len(sys.argv)!=3:
"""the program name, mac and ip makes three"""
"""stop program and send error"""
sys.exit("Must provide mac and ip!")

mac = sys.argv[1]
ip = sys.argv[2]

try:
conn = MySQLdb.connect (host = "localhost", user = "user", passwd = "pass", db = "theblackbox")
except MySQLdb.Error, e:
print ("Error %d: %s" % (e.args[0], e.args[1]))
sys.exit(1)

cursor = conn.cursor()

cursor.execute ("""UPDATE mac_list SET ip = %s WHERE mac = %s """, (ip, mac))

print ("Number of rows updated: %d" % cursor.rowcount)

cursor.close ()
conn.commit ()
conn.close ()</pre>
<p>Ah so we have reached the end. If you have any questions from above feel free to ask. The program works fine. Now I have to code a chat server like script in python and make it work with PHP. If you look back at the top you will see what I mean. More will come!</p>
]]></content:encoded>
			<wfw:commentRss>http://johnroach.info/2009/10/31/workflow-of-the-blackbox-system-and-connecting-in-two-steps-pythonssh/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

