Search results for 'python'
Some times there is need to automitize all tasks.
Like login on page download some info and go out.
There is html parsers they can do such tasks
For example it can be login script for some browser game or mail account that doesnt allow
SMTP or SMTP is not for free.
For example there is web-browser game travian an it after some time playing
it becomes very boring to play because only thing that you do it waiting
while some game events take too many time. Like when you click upgdade
something than you need to wait some hours until finish.
Now here we will make login example.
We need external libraries:
httplib2 http://code.google.com/p/httplib2/
lxml http://lxml.de/
First thing that we need its to get page source.
conn = httplib2.Http("cache")
resp,cont = conn.request("http://travian.com")
After we have source we look on login form
<form method="post" name="snd" action="dorf1.php">
<input class="text" type="text" name="name" value="">
<input class="text" type="password" name="password" value="" maxlength="20">
<input type="image" value="login" name="s1" onclick="xy();" id="btn_login" class="dynamic_img">
<input type="hidden" name="w" value="">
<input type="hidden" name="login" value="1299937743">
</form>
As we see here is many inputs
As ther is only 1 form we dont check and simply take first form from array
from lxml.html import parse,tostring,fromstring,submit_form
page = fromstring( cont )
form = page.forms[0]
for inp in form.inputs:
if inp.type == "text":
inp.value = name
if inp.type == "password":
inp.value = password
Dont forget about method="post"
headers = {'Content-type': 'application/x-www-form-urlencoded'}
Now we are ready to send data and get cookie that will allow us
get inside the page
resp , cont = self.conn.request( self.server+"/"+form.action , "POST" , body=urllib.urlencode(body) , headers=headers )
Response has cookie that we need to save if would like to work with page in future
cookie = resp['set-cookie']
Also cookie is needed if whant to logout:
headers = { 'Content-type': 'application/x-www-form-urlencoded' }
headers = { 'Cookie': self.cookie }
body = {}
resp,cont = self.conn.request(self.server+"/logout.php", body=urllib.urlencode(body) , headers=headers)
As you see now cookie is inside headers. You should allways place cookie
inside headers if whant to be loged in. Because only cookie that you get at login
says for server that you are loged in and can see what is behind the wall.
Thers is also easy way how to access DOM components
With your favorite browser you can easly get DOM path to prefered tag in HTML source.
tmp = page.xpath("/html//div//div//div//div//p//span")
You can find some tag by class name using find_class()
Or get text content from tag with text_content()
tmp = page.xpath("/html//div//div//div//div//p//span")[2].find_class("none")[0].text_content()
To make your own script that can parse and get info you need only
reguest()
find_class()
text_content()
xpath()
fromstring()
It is very easy. Now you know everything to make your first script that can login on
you favorite page.
Mood text in skype is simple and not very interactive. Trought skype api there can be done some animations.First step was to test set mood text trought api.Here is script that directly sends to skype Skype commnd for setting rich mood text. Linux dont support latest skype Protocol 7 (API version 3.0) but on Win there everything words ok. Here you type in commandline
./setrichmood.py "New mood"
and rich mood text changed
import sys
import os
import Skype4Py
skype = Skype4Py.Skype()
skype.Attach()
if len(sys.argv) == 2:
if os.path.exists( sys.argv[1] ):
f = open( sys.argv[1] , "r" )
s = unicode(f.read())
f.close()
c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+s )
skype.SendCommand( c )
else:
s = unicode(sys.argv[1])
c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+s )
skype.SendCommand( c )
Why I it call rich mood text? because it support some xml like commands.from skype api there is such commands
Example:
//------------------------------------------------------------------
// For purpose of bit conservation we omit feedback notifications
SET PROFILE RICH_MOOD_TEXT Smiley: <ss type="smile">:-)</ss>
SET PROFILE RICH_MOOD_TEXT <font color="#ff0010">Red text</font>
SET PROFILE RICH_MOOD_TEXT <blink>Blinking text</blink>
SET PROFILE RICH_MOOD_TEXT <b>Bold text</b>
SET PROFILE RICH_MOOD_TEXT <i>Italics</i>
SET PROFILE RICH_MOOD_TEXT <u>Underlined</u>
SET PROFILE RICH_MOOD_TEXT First lineSecond lineThird line
<ss type="smile"></ss> also accepts following smileys:
* smile, sad, laugh, cool, surprised, wink, cry, sweat, speechless, kiss, tongueout, blush, wonder, sleepy, snooze, dull, inlove, talk, yawn, puke, doh, angry, wasntme, party, worry, mmm, nerdy, lipssealed, hi, call, devil, angel, envy, wait, hug, makeup, giggle, clap, think, bow, rofl, whew, happy, smirk, nod, shake, punch, emo, no, yes, handshake, skype, heart, brokenheart, mail, flower, rain, sun, time, music, movie, phone, coffee, pizza, cash, muscle, beer, drink, dance, ninja, star, mooning, finger, bandit, smoke, toivo, rock, headbang, poolparty, swear, bug, fubar, tmi. I have tryed use them one inside other but it doesnt worked.How there can be made animations? Here is very simple example that reads from file linesand after time delay shows lines.
./moodanime.py anime.xml
Here is new peace of script:
import sys
import os
import Skype4Py
import time
skype = Skype4Py.Skype()
skype.Attach()
s = []
if os.path.exists( sys.argv[1] ):
f = open( sys.argv[1] , "r" )
for line in f:
s.append(line)
f.close()
while True:
for frame in s:
c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+frame )
skype.SendCommand( c )
time.sleep( 1 )
as example file can be:
____Bonanza____
___#Bonanza#___
__##Bonanza##__
_###Bonanza###_
####Bonanza####
_###Bonanza###_
__##Bonanza##__
___#Bonanza#___
And now everything works fine. I have tested this scipts with python2.7 and on ArchLinux. If there is some problems try static or dynamic skype from skype download page
This is programming game where you have to controll your robots with simple assembler like language. Game is inspired by AutoWars. Source contains source,small turorial and examples.
Robatik Game
Terminal snake. First project in python by wudu
Author: wudu
Source
Google Code
After reading chapter form MIT Introduction in algorithms about trees I have implemented same algorithm in pythonI haven't tryed to make best perfomance only easy to understund and one to one like is in pseudo-codeTree python class that are used to represent BinaryTree.
class Tree:
p = None
left = None
right = None
key = 0
pseudo-code
Inorder_Tree_Walk( x )
if x != NIL
then Inorder_Tree_Walk( left[x] )
print key[x]
Inorder_Tree_Walk( right[x] )
python code
def inorder_tree_walk( t ):
if t != None:
inorder_tree_walk( t.left )
print t.key,
inorder_tree_walk( t.right )pseudo codeTree_Search( x , k )
if x = NIL or k = key[x]
then return x
if k < key[x]
then return Tree_Search( left[x] , k )
else return Tree_Search( right[x] , k )python codedef tree_search( t , k ):
if (t == None) or (k == t.key):
return t
if k < t.key:
return tree_search( t.left, k )
return tree_search( t.right, k )pseudo codeTree_Minimum( x )
while left[x] != NIL
do x <- left[x]
return xpython codedef tree_minimum( t ):
while t.left != None:
t = t.left
return tpseudo codeTree_Maximum( x )
while right[x] != NIL
do x <- right[x]
return xpython codedef tree_maximum( t ):
while t.right != None:
t = t.right
return tpython codedef tree_root( t ):
while ( t.p != None):
t = t.p
return tpseudo codeTree_Successor( x )
if right[x] != NIL
then return Tree_Minimum( right[x] )
y <- p[x]
while y != NIL and x = right[y]
do x <- y
y <- p[y]
return ypython codedef tree_successor( t ):
if t.right != None:
return tree_minimum( t.right )
y = t.p
while (y != None) and (t == y.right):
t = y
y = y.p
return ypseudo codeTree_Insert( T , z )
y <- NIL
x <- root[T]
while x != NIL
do y <- x
if key[z] < key[x]
then x <- left[x]
else x <- right[x]
p[x] <- y
if y = NIL
then root[T] <- z
else if key[z] < key[y]
then left[y] <- z
else right[y] <- zpython codedef tree_insert( t , z ):
y = None
x = tree_root( t )
while x != None:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.p = y
if y == None:
r = tree_root( t )
r = z
else:
if z.key < y.key:
y.left = z
else:
y.right = z def tree_insert_recrusive( t , z ):
if t.left == None and t.right == None:
if z.key < t.key:
t.left = z
else:
t.right = z
return
if z.key < t.key:
tree_insert_recrusive( t.left , z )
else:
tree_insert_recrusive( t.right , z )pseudo codeTree_Delete( T , z )
if left[z] = NIL or right[z] = NIL
then y <- z
else y <- Tree_Successor( z )
if left[y] != NIL
then x <- left[y]
else x <- right[y]
if x != NIL
then p[x] <- p[y]
if p[y] = NIL
then root[T] <- x
else if y = left[p[y]]
then left[p[y]] <- x
else right[p[y]] <- x
if y != z
then key[z] <- key[y]
return ypython codedef tree_delete( t , z ):
if (z.left == None) or (z.right == None):
y = z
else:
y = tree_successor( z )
if y.left != None:
x = y.left
else:
x = y.right
if x != None:
x.p = y.p
if y.p == None:
r = tree_root( t )
r = x
t = r
else:
if y == y.p.left:
y.p.left = x
else:
y.p.right = x
if y != z:
z.key = y.key
return yExample of usage:Now we can use out tree. There is some more functions like create_tree that creates binary tree from given array. And print_tree that print all ree values.keys = [10,6,1,0,3,8,7,9,21,15,11,17,25,23,46]
max_deep = log(len(keys),2)
def create_tree( n=0 , p=None):
if (len(keys) == 0) or (n >= max_deep):
return None
t = Tree()
t.p = p
t.key = keys.pop(0)
t.left = create_tree( n+1 , t )
t.right = create_tree( n+1 , t)
return t
def print_tree( t ):
if (t != None) and (t.key != None):
if t.left == t.right == None:
print "Key:%d "%(t.key)
return
if t.left.key == None:
print "Key:%d Right:%d"%(t.key,t.right.key)
print_tree( t.right )
return
if t.right.key == None:
print "Key:%d Left:%d"%(t.key,t.left.key)
print_tree( t.left )
return
print "Key:%d Left:%d Right:%d"%(t.key,t.left.key,t.right.key)
print_tree( t.left )
print_tree( t.right )
t = create_tree()
r = tree_search( t, 10 )
n = Tree()
n.key = 150
tree_insert_recrusive( t , n )
inorder_tree_walk( t )
print ""
tree_delete( t , r )
inorder_tree_walk( t )
print ""
r = tree_root( t )
print r.key
Source
CVE-2010-1160 Nano Changed File Symlink Privilege EscalationUsualy if I have to edit some file I am using nano editor. It is almost on every distribution and easy and fast to use. Some time ago i hated vim beacouse of Ctrl-D =] and that way used nano or pico. Now I know how to exit from vim :q!. After this bugreported in CVE i was exited to check it out in real life. It is first bug that i have fully tested.This bug is fixed in newest versions. Testing all nano version this bug works on < 2.1.7 versions now on my system is latest nano version and I have compiled many < 2.1.7 versions to test this bug. To get your nano version run:$ nano -VWhen user is editing file nano don't check if it is edited by some one else. When saving file it simply save it and dont check if it was modified. If file was changed by some one else then nano will overwrite it with his text. But it can be changed to symlink that points to other file. How to use it in real life:
1) Open file with nano
2) Change file or set symlink
3) Make changes in file and save file in nano
4) See result in symlinked file
Everytning looks like$nano text.txtNow some one do:$ls -s empty.txt text.txtNano savewhach you save in text.txtIn python it looks like:
os.remove( "text.txt" )
open( "empty.txt" , "w" ).close()
os.symlink( "empty.txt" , "text.txt"
Python step by step
If you are root and opening file with owner isnt you. Than owner while you editing his file can setsymlink to some "/etc/important.conf" and you will overwrite it with some other unrelated info. This can make some harm to your system.How can it be exploited in real life by "small unpreviliged user". Make some interesting file that root will interested in. Make some process that whachs nanos running in system.
If nano opened file is our , symlink it.
1)Detect running nano in system
2)Check with file is opened
3)If file is yours make symlink
Nano catch
Script is only for user and dont work if you try to symlink root opened nano. It makesall steps as described above. Change script variables for your tests:
debug = True
nano = "nano-2.0.9"
user = "user"
sym_path="/home/user/empty.txt"
Tested only with python 2.6.5
Simply be uptodated or if you using old nano dont open with privileged user unpriveleged user files. It will save you from this bug.
Linkage:
[1] http://osvdb.org/show/osvdb/63872
[2] http://cve.mitre.org/cgi-bin/cvename.cgi?name=2010-1160
[3] http://drosenbe.blogspot.com/2010/03/nano-as-root.html
[4] http://svn.savannah.gnu.org/viewvc/trunk/nano/ChangeLog?revision=4503&root=nano&view=markup
Good fellow asked me to write some script that will help him to turn on/off passway to global network. There was used linksys machine for controlling such stuffHere is some code that login, change some rulles and logout. Also pygtk script that doit in visual way
from linksys import *
ls = LinkSys( "http://192.168.1.1/" )
ls.login( "admin" , "admin" )
ls.setip( STATIC_IP , "gateway" , 10 , 66 , 66 , 66 )
ls.setip( STATIC_IP , "subnet" , 255 , 255 , 255 , 0 )
if ls.response():
print "Succes"
else:
print "O_O AIam BAd GUy -^-"
ls.logout()
Everything was writen in early 2009. I have tested at that days. Now I don't have linksys machine to test it.
Source
This script synhronize your status with selected user status.
python SyncStat.py favorite_uzer
added new variable tha tcheck in with mode now screen is
Used new event type
if event.type == pygame.KEYDOWN:
When pressing key m we making new screen surface in fullscreen mode. If screen is in fuulscreen mode make window.
if event.key == pygame.K_m:
if not fullscreen:
screen = pygame.display.set_mode( (SCREEN_X,SCREEN_Y) , pygame.FULLSCREEN )
fullscreen = True
else:
screen = pygame.display.set_mode( (SCREEN_X,SCREEN_Y) )
fullscreen = False
Basic HTTP server. When you type url it shows listing of your local directory. If you tipe with path to file name noting hapens
Use:
http://*.*.*.*:<port>/ -> disk start directory
http://*.*.*.*:<port>/home/ -> home directory
Run:
./server port
Compile:
gcc server.c -o server
C Source
Here is also python source. It runs on port:8081 and prints in terminal HTTP request. You can see what browser sends to server.
Py Source
All boxes moving with same speed in same directions and all boxes have same size and colorMake changes step by step to see result
self.dx = randint(1,BOX_SPEED)
self.dy = randint(1,BOX_SPEED)
and boxes now moving all seperatly at diferent directions. self.boxes.append( Box( i*2 , i*2 , randint(BOX_MIN_SIZE,BOX_MAX_SIZE) ,
(i,0,0) )
now boxes have diferent sizes
Tutorial source
New class boxes handles many boxes. Number of boxes depends on cpnstant MAX_BOXES.
MAX_BOXES = 100
and all class Boxes methods is the same only diference is that it handles many boxes.Tutorial Source
Here is Lorenz attractor whery popular attractor i have used basic coloring tehnique.
Script
PovRay source
added constants that helps controlling screen size
SCREEN_X = 500
SCREEN_Y = 500
BOX_SIZE = 20
BOX_SPEED = 1
box have speed by axisself.dx = BOX_SPEED
self.dy = BOX_SPEE
detecting if given rect is inside screen borders or not if not then change it directiondef move( self ):
if self.rect.left+BOX_SIZE > SCREEN_X:
self.dx = -BOX_SPEED
if self.rect.left < 0:
self.dx = BOX_SPEED
if self.rect.top+BOX_SIZE > SCREEN_Y:
self.dy = -BOX_SPEED
if self.rect.top < 0:
self.dy = BOX_SPEED
self.rect.left += self.dx
self.rect.top += self.dyafter few line of code where added box move inside given screen and coalide with screen borders
Tutorial Source
There is new object Box. We can draw, mask and move it.Once you init it you can use it with simple interface
box = Box( position_x , position_y , size ,
(color_red,color_green,color_blue,color_alpha) )
moving box to new position. new position calculates x_new = x_old + xbox.move( add_x , add_y )
drawes box on the screenbox.draw()
draw black box on the screenbox.mask()
Tutorial Source
Draw some image and make for it
surface image = pygame.image.load("image_name.format")
then copy image surface to screen surface. screen.blit( source_surface , (position_x,position_y) )
Tutorial source
Now you can set application window. But there is one problem you have to terminate application by killing.
Adding event handling help us exit from application by clicking close button or pressing some other button.
for event in pygame.event.get():
if event.type == pygame.QUIT:
runing = False
Now you can exit from application by clicking close button.
Event types
There are defined other event types pygame.(KEYUP, KEYDOWN, MOUSEMOTION, MOUSEBUTTONP, MOUSEBUTTONDOWN, VIDEORESIZE). All of these events described in pygame documentation
Tutorial source
First application and we opening window
screen = pygame.display.set_mode( (width_of_window ,height_of_window ) )
In future we will use screen for drawing.
Also there possible make full screen with value pygame.FULLSCREEN
it looks like:
pygame.display.set_mode( (width,height), pygame.FULLSCREEN )
Tutorial Source
Python Pygame tutorial. This tutorial goal show how to make small and simple pygame pythone script that include all that is need for bigger application. Every tutorial part add only few new lines of code.
Moving Boxes
Goal
Make featured applications with boxes that coaliding one with another.
1. [Set Display]
2. [Event Sytem]
3. [Image loading]
4. [Box object]
5. [Box move]
6. [Boxes move]
7. [Randomnes]
8. [Fullscreen]
Script that checks and writes (in case of change) status of Skype users to the SQLite database. Communication with Skype is done via Skype4Py module.
Use:
Create database file:
python SetDB.py
Run Skype Status check:
python CheckStatus.py
Generate Hourly statistics: