[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
SlideShare a Scribd company logo
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

More Related Content

What's hot (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
Tim Pettersen
 
PEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case StudyPEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case Study
Henry 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 filters
Acá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 filters
Acácio Oliveira
 
Git and Unity
Git and UnityGit and Unity
Git and Unity
Tim Pettersen
 
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
Acá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 Assembly
ice799
 
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 filters
Acácio Oliveira
 
System log
System logSystem log
System log
buza1
 
CMake best practices
CMake best practicesCMake best practices
CMake best practices
Henry Schreiner
 
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
it-people
 
Filelist
FilelistFilelist
Filelist
trinhhuusam
 
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
Seong-Hun Choe
 
Raspberry Pi + ROS
Raspberry Pi + ROSRaspberry Pi + ROS
Raspberry Pi + ROS
ArnoldBail
 
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
ice799
 
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
cloudbeatsch
 
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
Tim Pettersen
 
PEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case StudyPEARC17: Modernizing GooFit: A Case Study
PEARC17: Modernizing GooFit: A Case Study
Henry 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 filters
Acá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 filters
Acá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 filters
Acá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 Assembly
ice799
 
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 filters
Acácio Oliveira
 
System log
System logSystem log
System log
buza1
 
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
it-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 pi
Seong-Hun Choe
 
Raspberry Pi + ROS
Raspberry Pi + ROSRaspberry Pi + ROS
Raspberry Pi + ROS
ArnoldBail
 
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
ice799
 
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
cloudbeatsch
 

Viewers also liked (7)

Giuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIPGiuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIP
Andrea 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 gestori
Babel
 
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 sicurezza
Babel
 
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
Babel
 
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
Babel
 
Giuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIPGiuseppe Dezzani, Intercettazioni e VoIP
Giuseppe Dezzani, Intercettazioni e VoIP
Andrea 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 gestori
Babel
 
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 sicurezza
Babel
 
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
Babel
 
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
Babel
 

Similar to Will iPython replace Bash? (20)

Python for System Administrators
Python for System AdministratorsPython for System Administrators
Python for System Administrators
Roberto 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++-API
Yoni Davidson
 
Happy porting x86 application to android
Happy porting x86 application to androidHappy porting x86 application to android
Happy porting x86 application to android
Owen Hsu
 
Learn python
Learn pythonLearn python
Learn python
Kracekumar Ramaraju
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
Henry 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 research
Andrew 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 Linardos
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)?
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 More
Matt Harrison
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
Henry Schreiner
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
Marwan Osman
 
Ladypy 01
Ladypy 01Ladypy 01
Ladypy 01
Calvin Cheng
 
AIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translationAIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translation
2040.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 matters
Alexandre Moneger
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
Yuvaraja Ravi
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
vceder
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
Mattupallipardhu
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
Maxym Kharchenko
 
05 python.pdf
05 python.pdf05 python.pdf
05 python.pdf
SugumarSarDurai
 
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
aspyker
 
Python for System Administrators
Python for System AdministratorsPython for System Administrators
Python for System Administrators
Roberto 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++-API
Yoni Davidson
 
Happy porting x86 application to android
Happy porting x86 application to androidHappy porting x86 application to android
Happy porting x86 application to android
Owen Hsu
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
Henry 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 research
Andrew 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 Linardos
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)?
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 More
Matt Harrison
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
Henry Schreiner
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
Marwan Osman
 
AIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translationAIMeetup #4: Neural-machine-translation
AIMeetup #4: Neural-machine-translation
2040.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 matters
Alexandre Moneger
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
Yuvaraja Ravi
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
vceder
 
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
aspyker
 

More from 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 ...
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 Cobbler
Babel
 
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
Babel
 
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 Virtualization
Babel
 
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
 
Babel presenta: Opsview
Babel presenta: OpsviewBabel presenta: Opsview
Babel presenta: Opsview
Babel
 
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
Babel
 
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
Babel
 
Testing with MySQL embedded
Testing with MySQL embeddedTesting with MySQL embedded
Testing with MySQL embedded
Babel
 
Cross compiler per uso domestico
Cross compiler per uso domesticoCross compiler per uso domestico
Cross compiler per uso domestico
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 
Git: un'introduzione pratica
Git: un'introduzione praticaGit: un'introduzione pratica
Git: un'introduzione pratica
Babel
 
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
Babel
 
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
Babel
 
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
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 Cobbler
Babel
 
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
Babel
 
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 Virtualization
Babel
 
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
 
Babel presenta: Opsview
Babel presenta: OpsviewBabel presenta: Opsview
Babel presenta: Opsview
Babel
 
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
Babel
 
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
Babel
 
Testing with MySQL embedded
Testing with MySQL embeddedTesting with MySQL embedded
Testing with MySQL embedded
Babel
 
Cross compiler per uso domestico
Cross compiler per uso domesticoCross compiler per uso domestico
Cross compiler per uso domestico
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 
Git: un'introduzione pratica
Git: un'introduzione praticaGit: un'introduzione pratica
Git: un'introduzione pratica
Babel
 
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
Babel
 
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
Babel
 
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
Babel
 

Recently uploaded (20)

Both Feet on the Ground - Generative Artificial Intelligence
Both Feet on the Ground - Generative Artificial IntelligenceBoth Feet on the Ground - Generative Artificial Intelligence
Both Feet on the Ground - Generative Artificial Intelligence
Pete Nieminen
 
Brave Browser Crack 1.45.133 Activated 2025
Brave Browser Crack 1.45.133 Activated 2025Brave Browser Crack 1.45.133 Activated 2025
Brave Browser Crack 1.45.133 Activated 2025
kherorpacca00126
 
UiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and OpportunitiesUiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and Opportunities
DianaGray10
 
Understanding Traditional AI with Custom Vision & MuleSoft.pptx
Understanding Traditional AI with Custom Vision & MuleSoft.pptxUnderstanding Traditional AI with Custom Vision & MuleSoft.pptx
Understanding Traditional AI with Custom Vision & MuleSoft.pptx
shyamraj55
 
Technology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptxTechnology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptx
kaylagaze
 
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & TipsTrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc
 
Q4_TLE-7-Lesson-6-Week-6.pptx 4th quarter
Q4_TLE-7-Lesson-6-Week-6.pptx 4th quarterQ4_TLE-7-Lesson-6-Week-6.pptx 4th quarter
Q4_TLE-7-Lesson-6-Week-6.pptx 4th quarter
MariaBarbaraPaglinaw
 
UiPath Document Understanding - Generative AI and Active learning capabilities
UiPath Document Understanding - Generative AI and Active learning capabilitiesUiPath Document Understanding - Generative AI and Active learning capabilities
UiPath Document Understanding - Generative AI and Active learning capabilities
DianaGray10
 
Fl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free DownloadFl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free Download
kherorpacca127
 
SMART SENTRY CYBER THREAT INTELLIGENCE IN IIOT
SMART SENTRY CYBER THREAT INTELLIGENCE IN IIOTSMART SENTRY CYBER THREAT INTELLIGENCE IN IIOT
SMART SENTRY CYBER THREAT INTELLIGENCE IN IIOT
TanmaiArni
 
Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)
nick896721
 
Transform Your Future with Front-End Development Training
Transform Your Future with Front-End Development TrainingTransform Your Future with Front-End Development Training
Transform Your Future with Front-End Development Training
Vtechlabs
 
Integrated Operating Window - A Gateway to PM
Integrated Operating Window - A Gateway to PMIntegrated Operating Window - A Gateway to PM
Integrated Operating Window - A Gateway to PM
Farhan Tariq
 
World Information Architecture Day 2025 - UX at a Crossroads
World Information Architecture Day 2025 - UX at a CrossroadsWorld Information Architecture Day 2025 - UX at a Crossroads
World Information Architecture Day 2025 - UX at a Crossroads
Joshua Randall
 
Technology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptxTechnology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptx
kaylagaze
 
BoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is DynamicBoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is Dynamic
Ortus Solutions, Corp
 
Replacing RocksDB with ScyllaDB in Kafka Streams by Almog Gavra
Replacing RocksDB with ScyllaDB in Kafka Streams by Almog GavraReplacing RocksDB with ScyllaDB in Kafka Streams by Almog Gavra
Replacing RocksDB with ScyllaDB in Kafka Streams by Almog Gavra
ScyllaDB
 
EaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial KeyEaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial Key
kherorpacca127
 
UiPath Automation Developer Associate Training Series 2025 - Session 1
UiPath Automation Developer Associate Training Series 2025 - Session 1UiPath Automation Developer Associate Training Series 2025 - Session 1
UiPath Automation Developer Associate Training Series 2025 - Session 1
DianaGray10
 
Wondershare Filmora Crack 14.3.2.11147 Latest
Wondershare Filmora Crack 14.3.2.11147 LatestWondershare Filmora Crack 14.3.2.11147 Latest
Wondershare Filmora Crack 14.3.2.11147 Latest
udkg888
 
Both Feet on the Ground - Generative Artificial Intelligence
Both Feet on the Ground - Generative Artificial IntelligenceBoth Feet on the Ground - Generative Artificial Intelligence
Both Feet on the Ground - Generative Artificial Intelligence
Pete Nieminen
 
Brave Browser Crack 1.45.133 Activated 2025
Brave Browser Crack 1.45.133 Activated 2025Brave Browser Crack 1.45.133 Activated 2025
Brave Browser Crack 1.45.133 Activated 2025
kherorpacca00126
 
UiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and OpportunitiesUiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and Opportunities
DianaGray10
 
Understanding Traditional AI with Custom Vision & MuleSoft.pptx
Understanding Traditional AI with Custom Vision & MuleSoft.pptxUnderstanding Traditional AI with Custom Vision & MuleSoft.pptx
Understanding Traditional AI with Custom Vision & MuleSoft.pptx
shyamraj55
 
Technology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptxTechnology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptx
kaylagaze
 
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & TipsTrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc
 
Q4_TLE-7-Lesson-6-Week-6.pptx 4th quarter
Q4_TLE-7-Lesson-6-Week-6.pptx 4th quarterQ4_TLE-7-Lesson-6-Week-6.pptx 4th quarter
Q4_TLE-7-Lesson-6-Week-6.pptx 4th quarter
MariaBarbaraPaglinaw
 
UiPath Document Understanding - Generative AI and Active learning capabilities
UiPath Document Understanding - Generative AI and Active learning capabilitiesUiPath Document Understanding - Generative AI and Active learning capabilities
UiPath Document Understanding - Generative AI and Active learning capabilities
DianaGray10
 
Fl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free DownloadFl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free Download
kherorpacca127
 
SMART SENTRY CYBER THREAT INTELLIGENCE IN IIOT
SMART SENTRY CYBER THREAT INTELLIGENCE IN IIOTSMART SENTRY CYBER THREAT INTELLIGENCE IN IIOT
SMART SENTRY CYBER THREAT INTELLIGENCE IN IIOT
TanmaiArni
 
Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)
nick896721
 
Transform Your Future with Front-End Development Training
Transform Your Future with Front-End Development TrainingTransform Your Future with Front-End Development Training
Transform Your Future with Front-End Development Training
Vtechlabs
 
Integrated Operating Window - A Gateway to PM
Integrated Operating Window - A Gateway to PMIntegrated Operating Window - A Gateway to PM
Integrated Operating Window - A Gateway to PM
Farhan Tariq
 
World Information Architecture Day 2025 - UX at a Crossroads
World Information Architecture Day 2025 - UX at a CrossroadsWorld Information Architecture Day 2025 - UX at a Crossroads
World Information Architecture Day 2025 - UX at a Crossroads
Joshua Randall
 
Technology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptxTechnology use over time and its impact on consumers and businesses.pptx
Technology use over time and its impact on consumers and businesses.pptx
kaylagaze
 
BoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is DynamicBoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is Dynamic
Ortus Solutions, Corp
 
Replacing RocksDB with ScyllaDB in Kafka Streams by Almog Gavra
Replacing RocksDB with ScyllaDB in Kafka Streams by Almog GavraReplacing RocksDB with ScyllaDB in Kafka Streams by Almog Gavra
Replacing RocksDB with ScyllaDB in Kafka Streams by Almog Gavra
ScyllaDB
 
EaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial KeyEaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial Key
kherorpacca127
 
UiPath Automation Developer Associate Training Series 2025 - Session 1
UiPath Automation Developer Associate Training Series 2025 - Session 1UiPath Automation Developer Associate Training Series 2025 - Session 1
UiPath Automation Developer Associate Training Series 2025 - Session 1
DianaGray10
 
Wondershare Filmora Crack 14.3.2.11147 Latest
Wondershare Filmora Crack 14.3.2.11147 LatestWondershare Filmora Crack 14.3.2.11147 Latest
Wondershare Filmora Crack 14.3.2.11147 Latest
udkg888
 

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