Home > varie > python tricky way

python tricky way

marzo 23, 2012

I’m using python for several script this days and I’m figured out how much is powerful compared to the bash script language. So I’ve decided to write here some script or some fuzzy trick to get easy the sysadmin’s life .

Also it is a good way to start writing some code and get out from the secure shell scripting and copy-edit-pasted-perl-code.

Python is different …

WHY

First of all let me try to explain why python .

python is a very simple language, it is intuitive and for who knows different program languages you will feel secure, quick and easy to learn. Sure it has some syntax limit, but is a chooice. I’ve spent more the few weeks to understand why there is the need to indenting the code, then I’ve understood it… It’s for the one who read the code.. not only for who stay writing everyday!

The limit of python is the result of his powers!

There is no need to define new vars, or to repeat some code, because create a function is very quickly and finally let me see it: the world is better without brackets

🙂

Take a look at this:

# s@mba - python & pexpect
# python simple ssh connection withouth password
import pexpect

myhost = "user@machiname.lan"
commands = ["ls","uptime","some other fucking commands", "exit"]
p = pexpect.spwan("ssh " + myhost)
conn = p.expect(["Are you sure","[Pp]assoword",pexpect.EOF])
if conn == 0:
  p.sendline("yes")
if conn == 1:
  passw = raw_input("Password: ")
  p.sendline(passw)
if conn == 2:
  sys.exit("no ssh session, exit")
for cmd in commands:
  p.sendline(cmd)
p.sendline("\n")
p.expect("\r\n")
print p.before

This is a very simple way to execute some code on a remote server if you cannot store ssh_keys in authorzed_keys, easy no?

Why using pexpect and not expect language?

Beacuse in this way I can manage all the exception, timeout and other issue just using the “try:” option in python

So stay tuned sysadmin, probably you will find something interesting, maybe some fuzzy scripts  about python🙂

you know a good sysadmin always finding a way to solve, workaround and automatize all the mountain of problem here we have

and if you really don’t know nothing about it, it could be a good way to start.

🙂

Categorie:varie Tag:, , , ,