SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Roberto Polli - roberto.polli@babel.it
Will iPython replace Bash?
s/bash/ipython/g
EuroPython 2013, 3th
July - Firenze
Babel Srl P.zza S. Benedetto da Norcia, 33 0040, Pomezia (RM) – www.babel.it
Roberto Polli - roberto.polli@babel.it
What? Who? Why?
How ipython can speed up your daily bash work, improve
reusability and your python confidence...without entirely
replacing bash.
Roberto Polli - Community Manager @ Babel.it. Loves writing in C,
Java and Python. Red Hat Certified Engineer and Virtualization
Administrator.
Babel – Proud sponsor of this talk ;) Delivers large mail
infrastructures based on Open Source software for Italian ISP and
PA. Contributes to various FLOSS.
Roberto Polli - roberto.polli@babel.it
Agenda - 1
Bash Rocks
Simple bash patterns
Python vs Bash: strenght and limits
Can python save the day?
SysAdmins can gently learn python!
Roberto Polli - roberto.polli@babel.it
Agenda - 2
Real life scenarios
●
using fields
●
parsing /proc/ files
●
reusing stuff
●
flaskize
●
test
You can manage it faster ;)
Roberto Polli - roberto.polli@babel.it
Python vs Bash
–Bash is "The" shell
–Python is the widespreading system
language
–A reunion?
# bash
for f in ${files[@]}; do
name=${f%.*}; ext=${f##*.}
mv "$f" "${name,,}.${ext}
done
# python
for f in files:
name, ext = f.splitext()
shutil.move(f,name.lower()+"."+ext)
Roberto Polli - roberto.polli@babel.it
Bash rocks - 1
Job Control
Simple pipelines and streams
# zipinfo -t just_files.zip | xargs rm --
Clean I/O redirection
# kinit user <<< 'secret' # kerberos login
# script.py 2>py.err < /etc/hosts # redirect stdin
for x in $(seq 1 10); do
sleep $x &
done
jobs -l;
wait %1
Roberto Polli - roberto.polli@babel.it
Bash rocks - 2
Braces and Globbing
# du -ms .[a-z]*
# touch {01..20}.out
...bash3 behaves differently from bash2
History and readline substitution
# mv foo.out foo-$(date -I).out
# !!:gs/foo/bar # same as above with "bar"
Long commands
# fc;
Roberto Polli - roberto.polli@babel.it
Wishes - 1
Safe system scripts
# touch -- -rf; rm * #ouch!
Readability
# mv "$file" "${file,,}"
# [ x$1 != x ] || exit
# ${WTF[@]}
Reusability
# . /etc/init.d/functions
# are you sure
# bash scripts
# are short?
RM=$(which rm)
? ${RM:?Missing rm}
WTF=(world taekwondo fed)
for file in ${A[@]}; do
$RM -- "$file";
done
Roberto Polli - roberto.polli@babel.it
Wishes - 2
Code consistency
●
bash3 != bash4
One language
●
perl
●
awk, gawk, mawk
●
grep, egrep, fgrep
●
sed, gsed,
●
gnuplot, bc
#bash4
if [[ $file =~ ^p ]]
then
strace $file |& 
grep inputrc
fi
# bash3
if echo "$file" | 
egrep -q "^p"
then
strace 2>&1 $file | 
grep inputrc
fi
Roberto Polli - roberto.polli@babel.it
Interactive Python
●
CPython delivers an interactive interpreter
●
Limited Readline and History support
●
Requires parenthesis and string quoting
●
Batteries included (math, telnetlib, shutil, ...)
$ telnet localhost 80
telnet: command not found
$ python -m telnetlib 0 80
Present by default
in almost
all Linux distros!
Roberto Polli - roberto.polli@babel.it
Interactive Python
Cpython shell can autocomplete!
import readline as rl
import rlcompleter
rl.parse_and_bind('tab: complete')
...but you can use iPython!
Roberto Polli - roberto.polli@babel.it
iPython: interactivity += 1
Easy to install
●
pip install ipython
Various flavours!
●
vanilla#ipython
●
math# ipython --pylab
●
shell# ipython --profile=[py]sh
Customizable
~/.ipython/profile_XX/ipython_config.py
Customize:
prompt
spacing
functions
shotcuts
modules
...
Roberto Polli - roberto.polli@babel.it
iPython
/bin/sh passthru:
●
ls -ld ~/python; # run via sh
●
ll /tmp; # alias pointing to ls -l
Capture both stdout and stderr
●
ret = !cat /etc/hosts #run via sh
●
ret = !ls /MISSING
Get exit status
●
print(_exit_code, "resembles $?")
ipython uses
os.system
# output is
# in a flexible
# list (SList)
type(ret)
_exit_code may
not be exactly
as expected
Roberto Polli - roberto.polli@babel.it
iPython features
Use SList as:
●
list or string
●
w or w/o newlines
Various Magics
%autocall
%edit
%debug
Automagic string-ify
and parenthesis
#ret = !cat /etc/resolv.conf
[ "search babel.it",
"nameserver 127.0.0.1" ]
#ret.s == ' '.join(ret)
True
#ret.nlstr == 'n'.join(ret)
True
#, ret.grep babel.it
Roberto Polli - roberto.polli@babel.it
iPython expansion
Pass python stuff to the shell
# import os
# ret = !cat /proc/{os.getpid()}/status
Consider the following steps during expansion
1. ipython parses the line and expands {contents}
2. prepare the command to be executed to the shell
3. fork/exec the shell
4. the shell interprets the command!
# from os import getpid as PID
# ret = !cat /proc/{PID()}/* # guess what?
Roberto Polli - roberto.polli@babel.it
Parsing system files
Get ipython Memory usage
# ret = !cat /proc/{os.getpid()}/status
Replace AWK
# ret.fields(0) # awk '{print $1;}'
# ret.fields(2,1,3) # awk '{print $2, $1, $3;}'
# ret.fields(*range(1,10)) # print 2..9th fields
# ret.fields(-1) # awk '{print $NF;}'
VmPeak: 27308 kB
VmSize: 27244 kB
VmHWM: 7080 kB
VmRSS: 7072 kB
Roberto Polli - roberto.polli@babel.it
Unpack data
SList.fields() just splits
by white-space
fieldize() is more
generic!
iPython profiles loads
custom files under
./startup/ directory.
# 99-fieldize.py
# save under the ./startup/
# of the rofile directory:
# ~/.ipython/profile_xx/
def fieldize(ret, sep=":"):
"""Let's be generic"""
return dict([
map(str.strip,
x.split(sep,1))
for x in ret ])
Roberto Polli - roberto.polli@babel.it
monitoring.ipy
#!/usr/bin/ipython --profile=pysh
# Important: save as .ipy to run with ipython
from time import sleep
from os import getpid
fields = '{VmSize},{VmRSS},{VmSwap}'
while sleep(1) == None:
ret = !grep ^Vm /proc/{getpid()}/status
d = fieldize(ret)
print(fields.format(**d))
Roberto Polli - roberto.polli@babel.it
$PITFALLS - 1
Beware of bash expansion/substitution
ret = !echo /proc/$$/cmdline
1.ipython replaces $fn with its
python value - eg. "cwd"
2.then uses os.system
3.fork() happens before bash
expansion
4.the shell interprets $$ as the
pid of the current process (the
forked one!)
Roberto Polli - roberto.polli@babel.it
$PITFALLS - 1
Expand Early and in Python
unless you know what you're doing!
GOOD: ! echo /proc/{os.getpid()}/cmdline
EVIL: ! echo /proc/$$/cmdline
Roberto Polli - roberto.polli@babel.it
$PITFALLS - 2
os.system|subprocess use /bin/shell
# this = !{echo does; echo >&2 not; } |& grep work
We can work it out ;)
edit _process_common.py
add the `executable` argument to
subprocess.Popen (
executable= '/bin/bash',
shell=True, ...)
IMHO: Don't you trust os.environ.get('SHELL')? Don't trust
os.system too!
quick &
dirty
Roberto Polli - roberto.polli@babel.it
Plotting system data
A sysadmin must plot...
# from matplotlib import pyplot
Collect data...
#ret = !ping -t 100 -w 100 foo.com
#ret = ret.fields(7).grep('time')
Mangle it... (get just millisecs)
#ret = [ x.split("=")[1]
for x in ret ]
And show!
# pyplot.hist(map(float, ret))
# pyplot.show()
Roberto Polli - roberto.polli@babel.it
Flaskize
Scripting in python you'll collect a
lot of useful snippets in a very
short time.
%history #use history magic
Flask is a web microframework
you can use to convert them in
webservices!
Can't use the !command syntax
with Flask...(can I?)
"""Things are easy even without
the !command stuff
"""
from flask import Flask
import simplejson
from fieldize import fieldize
app = Flask(__name__)
@app.route('/r/mem.view/<pid>')
def monitor(pid):
"""Return some process info"""
int(pid) # trigger ValueError
fpath = '/proc/%s/status' % pid
# a file is iterable ;)
with open(fpath) as ret
d = fieldize(fpath, ":")
return simplejson.dumps(d)
app.run(debug=True)
Roberto Polli - roberto.polli@babel.it
Nosetests: speed up your tests!
Three simple steps
●
put your test files in ./test/
●
run #nosetests ./test/
●
nose discovers and runs
them all
...really! That's all!
"""Test is easy with nose.
Docstrings are used in reports!
"""
from telnetlib import Telnet
def mping(ip):
# ICMP requires root privileges ;)
cmd = '/bin/ping -w 2 -t 2 '+ip
return os.system(cmd)
def test_ping_gw():
"ping default gw"
assert mping('192.168.1.254')==0
def test_ping_remote():
"ping remote host"
assert mping('10.0.11.1')==0
def test_tcp_remote():
"port 80 remote"
port, timeout = 80, 1
Telnet('10.0.11.1', port, timeout).close()
Roberto Polli - roberto.polli@babel.it
Bonus tracks: Ovirt and 389ds
iPython auto-complete helps learning new API
●
Ovirt open-source virtualization infrastructure
●
389 LDAP directory server
#!sudo pip install ovirt-engine-sdk
from ovirtsdk.api import API
client = API(**{'url':.., 'username':..})
for vm in client.vm.list():
name = vm.get_name()
try: vm.stop() # PEP8 who? ;)
except: log.exception("Error stopping " + name)
Roberto Polli - roberto.polli@babel.it
Bonus tracks: Ovirt and 389ds
389 API are under development: feedback is important!
#git clone https://github.com/ioggstream/dsadmin
from dsadmin import DSAdmin
# connect to the server
ds = DSAdmin(**{'binddn':..., 'bindpw': ...})
# configure 389 to use SSL
ds.setupSSL()
# weird name? iPython will auto-complete!
ds.getReplStatus()
Development releases includes method name refactoring!
ds.replica.status()
ds.replica.agreements()
Roberto Polli - roberto.polli@babel.it
Will iPython replace Bash?
Not in the near future ;)
Can lead to a different use of bash
Compete with weakly interactive
toos like perl, awk, sed
It is a tool that you shouldn't miss!
Roberto Polli - roberto.polli@babel.it
Thank You!
roberto.polli@babel.it
Code
http://ipython.org/
http://flask.pocoo.org/
http://nose.readthedocs.org/
https://github.com/ioggstream/dsadmin/
Babel
http://www.babel.it
http://vaunaspada.babel.it/blog

Weitere ähnliche Inhalte

Was ist angesagt?

Tracking large game assets with Git LFS
Tracking large game assets with Git LFSTracking large game assets with Git LFS
Tracking large game assets with Git LFSTim Pettersen
 
PEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case StudyPEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case StudyHenry Schreiner
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filtersAcácio Oliveira
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filtersAcácio Oliveira
 
3.2 process text streams using filters
3.2 process text streams using filters3.2 process text streams using filters
3.2 process text streams using filtersAcácio Oliveira
 
[Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi
[Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi [Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi
[Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi Tomomi Imura
 
Deconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and AssemblyDeconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and Assemblyice799
 
Python入門 : 4日間コース社内トレーニング
Python入門 : 4日間コース社内トレーニングPython入門 : 4日間コース社内トレーニング
Python入門 : 4日間コース社内トレーニングYuichi Ito
 
Licão 06 process text streams with filters
Licão 06 process text streams with filtersLicão 06 process text streams with filters
Licão 06 process text streams with filtersAcácio Oliveira
 
System log
System logSystem log
System logbuza1
 
Holger Krekel: Re-inventing packaging and testing with python
Holger Krekel: Re-inventing packaging and testing with pythonHolger Krekel: Re-inventing packaging and testing with python
Holger Krekel: Re-inventing packaging and testing with pythonit-people
 
Installing tensorflow object detection on raspberry pi
Installing tensorflow object detection on raspberry piInstalling tensorflow object detection on raspberry pi
Installing tensorflow object detection on raspberry piSeong-Hun Choe
 
Raspberry Pi + ROS
Raspberry Pi + ROSRaspberry Pi + ROS
Raspberry Pi + ROSArnoldBail
 
All of Your Network Monitoring is (probably) Wrong
All of Your Network Monitoring is (probably) WrongAll of Your Network Monitoring is (probably) Wrong
All of Your Network Monitoring is (probably) Wrongice799
 
Large scale nlp using python's nltk on azure
Large scale nlp using python's nltk on azureLarge scale nlp using python's nltk on azure
Large scale nlp using python's nltk on azurecloudbeatsch
 

Was ist angesagt? (18)

Tracking large game assets with Git LFS
Tracking large game assets with Git LFSTracking large game assets with Git LFS
Tracking large game assets with Git LFS
 
PEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case StudyPEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case Study
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filters
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filters
 
Git and Unity
Git and UnityGit and Unity
Git and Unity
 
3.2 process text streams using filters
3.2 process text streams using filters3.2 process text streams using filters
3.2 process text streams using filters
 
[Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi
[Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi [Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi
[Forward4 Webinar 2016] Building IoT Prototypes w/ Raspberry Pi
 
Deconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and AssemblyDeconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and Assembly
 
Python入門 : 4日間コース社内トレーニング
Python入門 : 4日間コース社内トレーニングPython入門 : 4日間コース社内トレーニング
Python入門 : 4日間コース社内トレーニング
 
Licão 06 process text streams with filters
Licão 06 process text streams with filtersLicão 06 process text streams with filters
Licão 06 process text streams with filters
 
System log
System logSystem log
System log
 
CMake best practices
CMake best practicesCMake best practices
CMake best practices
 
Holger Krekel: Re-inventing packaging and testing with python
Holger Krekel: Re-inventing packaging and testing with pythonHolger Krekel: Re-inventing packaging and testing with python
Holger Krekel: Re-inventing packaging and testing with python
 
Filelist
FilelistFilelist
Filelist
 
Installing tensorflow object detection on raspberry pi
Installing tensorflow object detection on raspberry piInstalling tensorflow object detection on raspberry pi
Installing tensorflow object detection on raspberry pi
 
Raspberry Pi + ROS
Raspberry Pi + ROSRaspberry Pi + ROS
Raspberry Pi + ROS
 
All of Your Network Monitoring is (probably) Wrong
All of Your Network Monitoring is (probably) WrongAll of Your Network Monitoring is (probably) Wrong
All of Your Network Monitoring is (probably) Wrong
 
Large scale nlp using python's nltk on azure
Large scale nlp using python's nltk on azureLarge scale nlp using python's nltk on azure
Large scale nlp using python's nltk on azure
 

Andere mochten auch

Giuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIPGiuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIPAndrea Rossetti
 
Intercettazioni e posta elettronica: le misure di sicurezza per i gestori
Intercettazioni e posta elettronica: le misure di sicurezza per i gestoriIntercettazioni e posta elettronica: le misure di sicurezza per i gestori
Intercettazioni e posta elettronica: le misure di sicurezza per i gestoriBabel
 
Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...
Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...
Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...Babel
 
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...Babel
 
Sophos Complete Security: arte e scienza della sicurezza
Sophos Complete Security: arte e scienza della sicurezzaSophos Complete Security: arte e scienza della sicurezza
Sophos Complete Security: arte e scienza della sicurezzaBabel
 
La gestione integrata della sicurezza in ANSA: dal firewalling all'UTM
La gestione integrata della sicurezza in ANSA: dal firewalling all'UTMLa gestione integrata della sicurezza in ANSA: dal firewalling all'UTM
La gestione integrata della sicurezza in ANSA: dal firewalling all'UTMBabel
 
Intercettazioni: guida alle nuove norme per i provider
Intercettazioni: guida alle nuove norme per i providerIntercettazioni: guida alle nuove norme per i provider
Intercettazioni: guida alle nuove norme per i providerBabel
 

Andere mochten auch (7)

Giuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIPGiuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIP
 
Intercettazioni e posta elettronica: le misure di sicurezza per i gestori
Intercettazioni e posta elettronica: le misure di sicurezza per i gestoriIntercettazioni e posta elettronica: le misure di sicurezza per i gestori
Intercettazioni e posta elettronica: le misure di sicurezza per i gestori
 
Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...
Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...
Dalla virtualizzazione al private cloud: Il Patronato INCA rinnova la fiducia...
 
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
 
Sophos Complete Security: arte e scienza della sicurezza
Sophos Complete Security: arte e scienza della sicurezzaSophos Complete Security: arte e scienza della sicurezza
Sophos Complete Security: arte e scienza della sicurezza
 
La gestione integrata della sicurezza in ANSA: dal firewalling all'UTM
La gestione integrata della sicurezza in ANSA: dal firewalling all'UTMLa gestione integrata della sicurezza in ANSA: dal firewalling all'UTM
La gestione integrata della sicurezza in ANSA: dal firewalling all'UTM
 
Intercettazioni: guida alle nuove norme per i provider
Intercettazioni: guida alle nuove norme per i providerIntercettazioni: guida alle nuove norme per i provider
Intercettazioni: guida alle nuove norme per i provider
 

Ähnlich wie Will iPython replace Bash?

Python for System Administrators
Python for System AdministratorsPython for System Administrators
Python for System AdministratorsRoberto Polli
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIYoni Davidson
 
Happy porting x86 application to android
Happy porting x86 application to androidHappy porting x86 application to android
Happy porting x86 application to androidOwen Hsu
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Henry Schreiner
 
Language-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchLanguage-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchAndrew Lowe
 
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosEuangelos Linardos
 
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?Jonas Hecht
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Henry Schreiner
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
AIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translationAIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translation2040.io
 
05 - Bypassing DEP, or why ASLR matters
05 - Bypassing DEP, or why ASLR matters05 - Bypassing DEP, or why ASLR matters
05 - Bypassing DEP, or why ASLR mattersAlexandre Moneger
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-pythonYuvaraja Ravi
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administrationvceder
 
Season 7 Episode 1 - Tools for Data Scientists
Season 7 Episode 1 - Tools for Data ScientistsSeason 7 Episode 1 - Tools for Data Scientists
Season 7 Episode 1 - Tools for Data Scientistsaspyker
 

Ähnlich wie Will iPython replace Bash? (20)

Python for System Administrators
Python for System AdministratorsPython for System Administrators
Python for System Administrators
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-API
 
Happy porting x86 application to android
Happy porting x86 application to androidHappy porting x86 application to android
Happy porting x86 application to android
 
Learn python
Learn pythonLearn python
Learn python
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
 
Language-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible researchLanguage-agnostic data analysis workflows and reproducible research
Language-agnostic data analysis workflows and reproducible research
 
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
 
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Ladypy 01
Ladypy 01Ladypy 01
Ladypy 01
 
AIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translationAIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translation
 
05 - Bypassing DEP, or why ASLR matters
05 - Bypassing DEP, or why ASLR matters05 - Bypassing DEP, or why ASLR matters
05 - Bypassing DEP, or why ASLR matters
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
 
05 python.pdf
05 python.pdf05 python.pdf
05 python.pdf
 
Season 7 Episode 1 - Tools for Data Scientists
Season 7 Episode 1 - Tools for Data ScientistsSeason 7 Episode 1 - Tools for Data Scientists
Season 7 Episode 1 - Tools for Data Scientists
 

Mehr von Babel

L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...Babel
 
Installare i server via rete con Cobbler
Installare i server via rete con CobblerInstallare i server via rete con Cobbler
Installare i server via rete con CobblerBabel
 
Shell Control Box - Il Gusto della Sicurezza
Shell Control Box - Il Gusto della SicurezzaShell Control Box - Il Gusto della Sicurezza
Shell Control Box - Il Gusto della SicurezzaBabel
 
Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...
Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...
Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...Babel
 
La Desktop Virtualization
La Desktop VirtualizationLa Desktop Virtualization
La Desktop VirtualizationBabel
 
Crittografia e integrazione dei sistemi con Python
Crittografia e integrazione dei sistemi con PythonCrittografia e integrazione dei sistemi con Python
Crittografia e integrazione dei sistemi con PythonBabel
 
Babel presenta: Opsview
Babel presenta: OpsviewBabel presenta: Opsview
Babel presenta: OpsviewBabel
 
Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4
Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4
Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4Babel
 
OpenVAS, lo strumento open source per il vulnerability assessment
OpenVAS, lo strumento open source per il vulnerability assessmentOpenVAS, lo strumento open source per il vulnerability assessment
OpenVAS, lo strumento open source per il vulnerability assessmentBabel
 
Testing with MySQL embedded
Testing with MySQL embeddedTesting with MySQL embedded
Testing with MySQL embeddedBabel
 
Cross compiler per uso domestico
Cross compiler per uso domesticoCross compiler per uso domestico
Cross compiler per uso domesticoBabel
 
Sicurezza flessibile con SELinux: architettura e configurazione
Sicurezza flessibile con SELinux: architettura e configurazioneSicurezza flessibile con SELinux: architettura e configurazione
Sicurezza flessibile con SELinux: architettura e configurazioneBabel
 
Ridirezionamento di I/O con Bash: un breve approfondimento
Ridirezionamento di I/O con Bash: un breve approfondimentoRidirezionamento di I/O con Bash: un breve approfondimento
Ridirezionamento di I/O con Bash: un breve approfondimentoBabel
 
Nagios in alta affidabilità con strumenti open source
Nagios in alta affidabilità con strumenti open sourceNagios in alta affidabilità con strumenti open source
Nagios in alta affidabilità con strumenti open sourceBabel
 
Il fenomeno dello spam: origine e contromisure
Il fenomeno dello spam: origine e contromisureIl fenomeno dello spam: origine e contromisure
Il fenomeno dello spam: origine e contromisureBabel
 
Il software open source: regole e licenze
Il software open source: regole e licenzeIl software open source: regole e licenze
Il software open source: regole e licenzeBabel
 
Git: un'introduzione pratica
Git: un'introduzione praticaGit: un'introduzione pratica
Git: un'introduzione praticaBabel
 
Mobile Data Security: Sicurezza IT per aziende in movimento
Mobile Data Security: Sicurezza IT per aziende in movimentoMobile Data Security: Sicurezza IT per aziende in movimento
Mobile Data Security: Sicurezza IT per aziende in movimentoBabel
 
Installazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red HatInstallazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red HatBabel
 
Il DLP, uno strumento di difesa del patrimonio informativo aziendale
Il DLP, uno strumento di difesa del patrimonio informativo aziendaleIl DLP, uno strumento di difesa del patrimonio informativo aziendale
Il DLP, uno strumento di difesa del patrimonio informativo aziendaleBabel
 

Mehr von Babel (20)

L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
L’innovazione a difesa della tradizione: il caso dell’Archivio Storico della ...
 
Installare i server via rete con Cobbler
Installare i server via rete con CobblerInstallare i server via rete con Cobbler
Installare i server via rete con Cobbler
 
Shell Control Box - Il Gusto della Sicurezza
Shell Control Box - Il Gusto della SicurezzaShell Control Box - Il Gusto della Sicurezza
Shell Control Box - Il Gusto della Sicurezza
 
Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...
Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...
Tracciamento delle attività di amministrazione mediante i BalaBit Shell Contr...
 
La Desktop Virtualization
La Desktop VirtualizationLa Desktop Virtualization
La Desktop Virtualization
 
Crittografia e integrazione dei sistemi con Python
Crittografia e integrazione dei sistemi con PythonCrittografia e integrazione dei sistemi con Python
Crittografia e integrazione dei sistemi con Python
 
Babel presenta: Opsview
Babel presenta: OpsviewBabel presenta: Opsview
Babel presenta: Opsview
 
Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4
Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4
Monitoraggio di infrastrutture IT mediante Opsview Enteprise V4
 
OpenVAS, lo strumento open source per il vulnerability assessment
OpenVAS, lo strumento open source per il vulnerability assessmentOpenVAS, lo strumento open source per il vulnerability assessment
OpenVAS, lo strumento open source per il vulnerability assessment
 
Testing with MySQL embedded
Testing with MySQL embeddedTesting with MySQL embedded
Testing with MySQL embedded
 
Cross compiler per uso domestico
Cross compiler per uso domesticoCross compiler per uso domestico
Cross compiler per uso domestico
 
Sicurezza flessibile con SELinux: architettura e configurazione
Sicurezza flessibile con SELinux: architettura e configurazioneSicurezza flessibile con SELinux: architettura e configurazione
Sicurezza flessibile con SELinux: architettura e configurazione
 
Ridirezionamento di I/O con Bash: un breve approfondimento
Ridirezionamento di I/O con Bash: un breve approfondimentoRidirezionamento di I/O con Bash: un breve approfondimento
Ridirezionamento di I/O con Bash: un breve approfondimento
 
Nagios in alta affidabilità con strumenti open source
Nagios in alta affidabilità con strumenti open sourceNagios in alta affidabilità con strumenti open source
Nagios in alta affidabilità con strumenti open source
 
Il fenomeno dello spam: origine e contromisure
Il fenomeno dello spam: origine e contromisureIl fenomeno dello spam: origine e contromisure
Il fenomeno dello spam: origine e contromisure
 
Il software open source: regole e licenze
Il software open source: regole e licenzeIl software open source: regole e licenze
Il software open source: regole e licenze
 
Git: un'introduzione pratica
Git: un'introduzione praticaGit: un'introduzione pratica
Git: un'introduzione pratica
 
Mobile Data Security: Sicurezza IT per aziende in movimento
Mobile Data Security: Sicurezza IT per aziende in movimentoMobile Data Security: Sicurezza IT per aziende in movimento
Mobile Data Security: Sicurezza IT per aziende in movimento
 
Installazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red HatInstallazione di Joomla nel cloud di Red Hat
Installazione di Joomla nel cloud di Red Hat
 
Il DLP, uno strumento di difesa del patrimonio informativo aziendale
Il DLP, uno strumento di difesa del patrimonio informativo aziendaleIl DLP, uno strumento di difesa del patrimonio informativo aziendale
Il DLP, uno strumento di difesa del patrimonio informativo aziendale
 

Kürzlich hochgeladen

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Kürzlich hochgeladen (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Will iPython replace Bash?

  • 1. Roberto Polli - roberto.polli@babel.it Will iPython replace Bash? s/bash/ipython/g EuroPython 2013, 3th July - Firenze Babel Srl P.zza S. Benedetto da Norcia, 33 0040, Pomezia (RM) – www.babel.it
  • 2. Roberto Polli - roberto.polli@babel.it What? Who? Why? How ipython can speed up your daily bash work, improve reusability and your python confidence...without entirely replacing bash. Roberto Polli - Community Manager @ Babel.it. Loves writing in C, Java and Python. Red Hat Certified Engineer and Virtualization Administrator. Babel – Proud sponsor of this talk ;) Delivers large mail infrastructures based on Open Source software for Italian ISP and PA. Contributes to various FLOSS.
  • 3. Roberto Polli - roberto.polli@babel.it Agenda - 1 Bash Rocks Simple bash patterns Python vs Bash: strenght and limits Can python save the day? SysAdmins can gently learn python!
  • 4. Roberto Polli - roberto.polli@babel.it Agenda - 2 Real life scenarios ● using fields ● parsing /proc/ files ● reusing stuff ● flaskize ● test You can manage it faster ;)
  • 5. Roberto Polli - roberto.polli@babel.it Python vs Bash –Bash is "The" shell –Python is the widespreading system language –A reunion? # bash for f in ${files[@]}; do name=${f%.*}; ext=${f##*.} mv "$f" "${name,,}.${ext} done # python for f in files: name, ext = f.splitext() shutil.move(f,name.lower()+"."+ext)
  • 6. Roberto Polli - roberto.polli@babel.it Bash rocks - 1 Job Control Simple pipelines and streams # zipinfo -t just_files.zip | xargs rm -- Clean I/O redirection # kinit user <<< 'secret' # kerberos login # script.py 2>py.err < /etc/hosts # redirect stdin for x in $(seq 1 10); do sleep $x & done jobs -l; wait %1
  • 7. Roberto Polli - roberto.polli@babel.it Bash rocks - 2 Braces and Globbing # du -ms .[a-z]* # touch {01..20}.out ...bash3 behaves differently from bash2 History and readline substitution # mv foo.out foo-$(date -I).out # !!:gs/foo/bar # same as above with "bar" Long commands # fc;
  • 8. Roberto Polli - roberto.polli@babel.it Wishes - 1 Safe system scripts # touch -- -rf; rm * #ouch! Readability # mv "$file" "${file,,}" # [ x$1 != x ] || exit # ${WTF[@]} Reusability # . /etc/init.d/functions # are you sure # bash scripts # are short? RM=$(which rm) ? ${RM:?Missing rm} WTF=(world taekwondo fed) for file in ${A[@]}; do $RM -- "$file"; done
  • 9. Roberto Polli - roberto.polli@babel.it Wishes - 2 Code consistency ● bash3 != bash4 One language ● perl ● awk, gawk, mawk ● grep, egrep, fgrep ● sed, gsed, ● gnuplot, bc #bash4 if [[ $file =~ ^p ]] then strace $file |& grep inputrc fi # bash3 if echo "$file" | egrep -q "^p" then strace 2>&1 $file | grep inputrc fi
  • 10. Roberto Polli - roberto.polli@babel.it Interactive Python ● CPython delivers an interactive interpreter ● Limited Readline and History support ● Requires parenthesis and string quoting ● Batteries included (math, telnetlib, shutil, ...) $ telnet localhost 80 telnet: command not found $ python -m telnetlib 0 80 Present by default in almost all Linux distros!
  • 11. Roberto Polli - roberto.polli@babel.it Interactive Python Cpython shell can autocomplete! import readline as rl import rlcompleter rl.parse_and_bind('tab: complete') ...but you can use iPython!
  • 12. Roberto Polli - roberto.polli@babel.it iPython: interactivity += 1 Easy to install ● pip install ipython Various flavours! ● vanilla#ipython ● math# ipython --pylab ● shell# ipython --profile=[py]sh Customizable ~/.ipython/profile_XX/ipython_config.py Customize: prompt spacing functions shotcuts modules ...
  • 13. Roberto Polli - roberto.polli@babel.it iPython /bin/sh passthru: ● ls -ld ~/python; # run via sh ● ll /tmp; # alias pointing to ls -l Capture both stdout and stderr ● ret = !cat /etc/hosts #run via sh ● ret = !ls /MISSING Get exit status ● print(_exit_code, "resembles $?") ipython uses os.system # output is # in a flexible # list (SList) type(ret) _exit_code may not be exactly as expected
  • 14. Roberto Polli - roberto.polli@babel.it iPython features Use SList as: ● list or string ● w or w/o newlines Various Magics %autocall %edit %debug Automagic string-ify and parenthesis #ret = !cat /etc/resolv.conf [ "search babel.it", "nameserver 127.0.0.1" ] #ret.s == ' '.join(ret) True #ret.nlstr == 'n'.join(ret) True #, ret.grep babel.it
  • 15. Roberto Polli - roberto.polli@babel.it iPython expansion Pass python stuff to the shell # import os # ret = !cat /proc/{os.getpid()}/status Consider the following steps during expansion 1. ipython parses the line and expands {contents} 2. prepare the command to be executed to the shell 3. fork/exec the shell 4. the shell interprets the command! # from os import getpid as PID # ret = !cat /proc/{PID()}/* # guess what?
  • 16. Roberto Polli - roberto.polli@babel.it Parsing system files Get ipython Memory usage # ret = !cat /proc/{os.getpid()}/status Replace AWK # ret.fields(0) # awk '{print $1;}' # ret.fields(2,1,3) # awk '{print $2, $1, $3;}' # ret.fields(*range(1,10)) # print 2..9th fields # ret.fields(-1) # awk '{print $NF;}' VmPeak: 27308 kB VmSize: 27244 kB VmHWM: 7080 kB VmRSS: 7072 kB
  • 17. Roberto Polli - roberto.polli@babel.it Unpack data SList.fields() just splits by white-space fieldize() is more generic! iPython profiles loads custom files under ./startup/ directory. # 99-fieldize.py # save under the ./startup/ # of the rofile directory: # ~/.ipython/profile_xx/ def fieldize(ret, sep=":"): """Let's be generic""" return dict([ map(str.strip, x.split(sep,1)) for x in ret ])
  • 18. Roberto Polli - roberto.polli@babel.it monitoring.ipy #!/usr/bin/ipython --profile=pysh # Important: save as .ipy to run with ipython from time import sleep from os import getpid fields = '{VmSize},{VmRSS},{VmSwap}' while sleep(1) == None: ret = !grep ^Vm /proc/{getpid()}/status d = fieldize(ret) print(fields.format(**d))
  • 19. Roberto Polli - roberto.polli@babel.it $PITFALLS - 1 Beware of bash expansion/substitution ret = !echo /proc/$$/cmdline 1.ipython replaces $fn with its python value - eg. "cwd" 2.then uses os.system 3.fork() happens before bash expansion 4.the shell interprets $$ as the pid of the current process (the forked one!)
  • 20. Roberto Polli - roberto.polli@babel.it $PITFALLS - 1 Expand Early and in Python unless you know what you're doing! GOOD: ! echo /proc/{os.getpid()}/cmdline EVIL: ! echo /proc/$$/cmdline
  • 21. Roberto Polli - roberto.polli@babel.it $PITFALLS - 2 os.system|subprocess use /bin/shell # this = !{echo does; echo >&2 not; } |& grep work We can work it out ;) edit _process_common.py add the `executable` argument to subprocess.Popen ( executable= '/bin/bash', shell=True, ...) IMHO: Don't you trust os.environ.get('SHELL')? Don't trust os.system too! quick & dirty
  • 22. Roberto Polli - roberto.polli@babel.it Plotting system data A sysadmin must plot... # from matplotlib import pyplot Collect data... #ret = !ping -t 100 -w 100 foo.com #ret = ret.fields(7).grep('time') Mangle it... (get just millisecs) #ret = [ x.split("=")[1] for x in ret ] And show! # pyplot.hist(map(float, ret)) # pyplot.show()
  • 23. Roberto Polli - roberto.polli@babel.it Flaskize Scripting in python you'll collect a lot of useful snippets in a very short time. %history #use history magic Flask is a web microframework you can use to convert them in webservices! Can't use the !command syntax with Flask...(can I?) """Things are easy even without the !command stuff """ from flask import Flask import simplejson from fieldize import fieldize app = Flask(__name__) @app.route('/r/mem.view/<pid>') def monitor(pid): """Return some process info""" int(pid) # trigger ValueError fpath = '/proc/%s/status' % pid # a file is iterable ;) with open(fpath) as ret d = fieldize(fpath, ":") return simplejson.dumps(d) app.run(debug=True)
  • 24. Roberto Polli - roberto.polli@babel.it Nosetests: speed up your tests! Three simple steps ● put your test files in ./test/ ● run #nosetests ./test/ ● nose discovers and runs them all ...really! That's all! """Test is easy with nose. Docstrings are used in reports! """ from telnetlib import Telnet def mping(ip): # ICMP requires root privileges ;) cmd = '/bin/ping -w 2 -t 2 '+ip return os.system(cmd) def test_ping_gw(): "ping default gw" assert mping('192.168.1.254')==0 def test_ping_remote(): "ping remote host" assert mping('10.0.11.1')==0 def test_tcp_remote(): "port 80 remote" port, timeout = 80, 1 Telnet('10.0.11.1', port, timeout).close()
  • 25. Roberto Polli - roberto.polli@babel.it Bonus tracks: Ovirt and 389ds iPython auto-complete helps learning new API ● Ovirt open-source virtualization infrastructure ● 389 LDAP directory server #!sudo pip install ovirt-engine-sdk from ovirtsdk.api import API client = API(**{'url':.., 'username':..}) for vm in client.vm.list(): name = vm.get_name() try: vm.stop() # PEP8 who? ;) except: log.exception("Error stopping " + name)
  • 26. Roberto Polli - roberto.polli@babel.it Bonus tracks: Ovirt and 389ds 389 API are under development: feedback is important! #git clone https://github.com/ioggstream/dsadmin from dsadmin import DSAdmin # connect to the server ds = DSAdmin(**{'binddn':..., 'bindpw': ...}) # configure 389 to use SSL ds.setupSSL() # weird name? iPython will auto-complete! ds.getReplStatus() Development releases includes method name refactoring! ds.replica.status() ds.replica.agreements()
  • 27. Roberto Polli - roberto.polli@babel.it Will iPython replace Bash? Not in the near future ;) Can lead to a different use of bash Compete with weakly interactive toos like perl, awk, sed It is a tool that you shouldn't miss!
  • 28. Roberto Polli - roberto.polli@babel.it Thank You! roberto.polli@babel.it Code http://ipython.org/ http://flask.pocoo.org/ http://nose.readthedocs.org/ https://github.com/ioggstream/dsadmin/ Babel http://www.babel.it http://vaunaspada.babel.it/blog