<?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; paramiko</title>
	<atom:link href="http://johnroach.info/tag/paramiko/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnroach.info</link>
	<description>Coding for life</description>
	<lastBuildDate>Wed, 25 Apr 2012 07:48:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<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" style="width:100%;height:500px;">
<div class="flagallery_swfobject" id="sid_2030196868_div"><style type="text/css">
@import url("http://johnroach.info/wp-content/plugins/flash-album-gallery/admin/css/flagallery_nocrawler.css");@import url("http://johnroach.info/wp-content/plugins/flash-album-gallery/admin/css/flagallery_noflash.css");
#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='fancybox', hitajax = 'http://johnroach.info/wp-content/plugins/flash-album-gallery/lib/hitcounter.php';</script>
	<div id="sid_2030196868_jq" class="flag_alternate">
		<div class="flagcatlinks"></div>
			<div class="flagCatMeta">
			<h4>angstrombeagleboard</h4>
			<p></p>
		</div>
		<div class="flagcategory" id="gid_4_sid_2030196868">
			<a class="i0 flag_pic_alt" href="http://johnroach.info/wp-content/flagallery/angstrombeagleboard/angstrom.png" id="flag_pic_5" rel="gid_4_sid_2030196868" 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_2030196868" 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_2030196868" 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_2030196868'] = jQuery("div#sid_2030196868_jq").clone().wrap(document.createElement('div')).parent().html();
var sid_2030196868_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_2030196868",
		postID : "164",
		postTitle : "Installing+%C3%85ngstr%C3%B6m+Linux+on+BeagleBoard+"},
	attr : {
		styleclass : "flashalbum",
		id : "sid_2030196868"},
	start : function() {
		swfobject.embedSWF("http://johnroach.info/wp-content/plugins/flagallery-skins/default/gallery.swf", "sid_2030196868_div", "100%", "100%", "10.1.52", "http://johnroach.info/wp-content/plugins/flash-album-gallery/skins/expressInstall.swf", this.flashvars, this.params , this.attr );
swfobject.createCSS("#sid_2030196868","outline:none");
	}
}
sid_2030196868_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>

