Archive

Posts Tagged ‘python’

RESTful APIs and Python

September 16th, 2014 No comments
Categories: software Tags: ,

Automatic Login for Hotel WiFi, …

October 14th, 2012 3 comments

The internet in my current apartment pisses me off. I have to login (usr/pw) into a strange website every time I connect the laptop. The login uses the POST method, so that I can’t control the cgi script via URL variables. ping isn’t available (maybe blocked by the router or ISP, not sure). And it’s only a LAN router, which had 24 hours ago a 0.5m LAN cable. The cable was upgraded to 3m :-), enough to write this post in my bed.

I’m also not sure about the security and logging of my ISP and a new Japanese copyright law is really hard. This why I wrote my last post, but lets fix the login problem first.

Willi gave me a hint to try pexpect, which is expect for python. That wasn’t exactly what I was searching for, but a good starting point and probably a handy tool for other purposes. I kind of wanted to stay with python, and found mechanize (Ubuntu has the package already “python-mechanize”; for Mac OSX just download package from their website). This python module is among other stuff able to emulate a browser and interact with the elements on the website, like following links, fill out forms, …

Here is my current script to login on the ISP webpage in my apartment to get a IP lease. In my case the URL is an IP address since I use external DNS servers.

import mechanize

br = mechanize.Browser()
br.open("http://172.16.dead.beef")

br.select_form(name="LoginUser")
br["username"]="fucking"
br["passwd"]="capitalism"
br.form.find_control("LoginMode").get("AutoLogin").selected = False
response = br.submit()

if response.get_data().find("Success") > 0:
    print "Login successful"
    br.close()
else:
    print "Error: something has gone wrong"
    print ""
    print "Page returned from server:"
    print response.read()
    br.close()

Ok, the basics are: start the browser; get the form for the login, change the input variables for username and password (HTML source looks like: <INPUT type=”text” name=”username”>); deselect the AutoLogin checkbox (which doesn’t work anyway) and in the end “click” the submit button.

In case you want to know more, the website of mechanize has some examples or just use the help function of python. The mechanize package and its function are well documented.

My script can easily be modified to connect to a Hotel/Airport WiFi or other websites you want to control in an automatic fashion.

Apache with Python on Linux in 2 minutes

September 20th, 2011 1 comment

After 2 hourse of googleing and reading outdated threads, I got it working and want you to save time.

  1. Install Apache2 and Python
  2. CGI-path is /usr/lib/cgi-bin so this is where to put your Python scripts
  3. To use the scripts in your HTML files you have to prefix the path to the .py files with /cgi-bin/
  4. To generate proper output the first print call in your script has to be
    print "Content-type: text/html\n\n"
  5. With the python module cgi you are able to access content of the calling HTML form
  6. If something went wrong /var/log/apache2/error.log is your friend!

For more information see: http://httpd.apache.org/docs/2.0/howto/cgi.html But not everything in there worked for me…
For usage of Pythons CGI module see: http://docs.python.org/library/cgi.html

Have Fun!

Categories: linux, software Tags: , ,

Manifesto For Programming

June 24th, 2011 No comments

http://programming-motherfucker.com/

Not much more to add to this I’d say 😉 Other than that this site also features a good python programming book (for absolute beginners like in “i dont know how to create a directory”-beginners).

Categories: nerdcore Tags: ,

Python by Example

April 27th, 2011 No comments

Just a few moments ago I discovered an interesting project called Acire Snippets. The aim is to provide an easy way to learn (or better use) Python by suppling code snippets of common tasks. But go an see for yourself!

Categories: software Tags: ,

A little more Eclipse in Vim

June 13th, 2010 2 comments

I am currently coding Java using Eclipse and what I find particularly helpful is that Eclipse highlights all occurrences of the word under the cursor. So I decided that my favorite editor, vim, should do that too. After a lot of struggling and fiddling I finally understood and got it working.

Here is a quick snapshot what it will look like when we are finished:

snapshot

The following code also serves as a general example on how to use python for scripting vim.

So let’s get started:

First we define a new look for our highlighting. I use simple bold text for that purpose.
Using ctermfg=white and ctermbg=gray (e.g.) you can also adjust the background and foreground color.

 
highlight MyWordUnderCursorHighlight cterm=bold

The second step is to hook up to the proper input events.
Therefor we use the auto command on cursor moved in normal mode (CursorMoved)
and in insert mode (CursorMovedI). The star stands for “every filetype”.
We simply let it call our to-be-defined function for highlighting.

autocmd CursorMoved * call MyHighlightWordUnderCursor()
autocmd CursorMovedI * call MyHighlightWordUnderCursor()

The function for highlighting (explanation in-lined):

function! MyHighlightWordUnderCursor()
" tell vim to use python from now on
python < < endpython
import vim
 
# get the character under the cursor
row, col = vim.current.window.cursor
characterUnderCursor = ''
try:
    characterUnderCursor = vim.current.buffer[row-1][col]
except:
    pass
 
# remove last highlight
vim.command("match MyWordUnderCursorHighlight //")
 
# if the cursor is currently located on a real word, move on and
# highlight it. We don't want to highlight anything when the cursor is not
# on a word.
if characterUnderCursor.isalpha()  or characterUnderCursor.isdigit() or characterUnderCursor is '_':
 
    # expand cword (a keyword in vim) to get the word under the cursor
    wordUnderCursor = vim.eval("expand(\'<cword>\')")
    if wordUnderCursor is None :
        wordUnderCursor = ""
    else :
        wordUnderCursor = "\< " + wordUnderCursor + "\>"
 
    currentSearch = vim.eval("@/")
    if currentSearch != wordUnderCursor :
        # highlight it
        vim.command("match MyWordUnderCursorHighlight /" + wordUnderCursor + "/")
 
# has to be the word after < < in the first line. Ends the python interpreter
endpython
endfunction

all source again

That’s it. Have fun and may the force be with you.

PS: for some reason. wordpress screws up the formatting. Please use the above link for copy and paste

PS2: before pasting indented text into vim use “set paste” / “set nopaste”.

Update:
Here is the vimscript only version: (click)
Thanks bart!

Update 2:

  • words can now also consist of numbers and underscores
  • do not highlight the wordUnderCursor if it is the currently searched term

Categories: software Tags: , , , ,

Python und Unicode

April 8th, 2009 No comments

Python mag normalerweise keine Scripte die Umlaute und dergleichen enthalten. Abhilfe schafft da folgender Einzeiler, den man am Anfang des Dokuments einfügt. Hier für UTF-8:

# -*- coding: utf-8 -*-

Ich konnte dabei keinen Unterschied feststellen ob man ihn vor oder nach der Shebang einfügt. Falls es einer genau weiß, bitte posten 😉

Wichtig: Die Zeichenkodierung gilt zwar für das gesamte Dokument, aber alles was vom Interpreter verstanden werden soll, muss ausschließlich ASCII-Zeichen enthalten. Kurz: Variablen- und Funktionsnamen in ASCII, Kommentare und Stringinhalte unterliegen der gewählten Zeichenkodierung.

Weitere Informationen und andere Beispiele für mögliche Kodierungen gibt es HIER

Categories: linux, software Tags: ,