SlideShare a Scribd company logo
1 of 37
Download to read offline
Python

for Linux system administration




       (yes, this is a commercial)




              Vern Ceder
            Fort Wayne LUG
            Fort Wayne, IN
Instead of?

the “official” languages for sysamins



    bash* (and awk and sed)
       *or your favorite similar shell


                   perl
       (if you don't believe me,
             ask O'Reilly)
http://www.oreillyschool.com/courses/asac4/
A scripting language should

      handle input & output

 process text – search, replace,
      pattern matching, etc.

       traverse filesystems

use system utilities and libraries
              (glue)
What's wrong with
   bash & perl?



 Nothing, really...
bash


is a great glue language

pipes things like a champ

has a ton of utilities
  (the whole system, in fact)
awk and sed


handle strings brilliantly
perl


combines it all...
but...

  bash is a pain when things
          get complex

         sed is tricky

    perl makes my head hurt

(I always have rather liked awk)
So what about Python?

      handles strings well

        is a good “glue”

   “batteries included” → I/O,
         filesystem, etc

large collection of external libs
Python also

   is very readable
(and easy to maintain)

    is expressive

   is easy to grasp

is either OO (or not)

        is fun
everyone's doing it

        Redhat

        Ubuntu

        Google

   etc, etc, etc...
but...
         (there's always a “but”)


regular expressions aren't built-in

   not (quite) as common as perl
and let's talk about




the elephant in the room
indentation

yes, Python uses indentation
       to organize code

 it makes code more readable

it's no weirder than {} or @$%



         get over it
strings
some built-in string methods
   split             lower
   strip             upper
    join            isdigit
  replace          swapcase
    find          expandtabs
   count             center
startswith      encode/decode
 endswith            format
for example

             to do what wc does:
#!/usr/bin/env python

import sys
data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = len(data.split('n'))
print ("{0}   {1}   {2}".format(lines, words, chars))

doc@paladin:~/work/olf$ ./wc.py < wc.py
12   22   189
or number of occurrences?
             in bash (not mine):
doc@pal:~/olf$ tr " " "n" <    wc.py | grep len | wc -w
3
                   in Python:
#!/usr/bin/env python
import sys
data = sys.stdin.read()
print data.count(sys.argv[1])

doc@paladin:~/work/olf$ ./num_occur.py len < wc.py
3
regular expressions

                   re module

         syntax similar to perl
import re
>>> re.findall("[Ll]en", "len is the Length")
['len', 'Len']
exception handling
y = 10
try:
    x = y / 0
except ZeroDivisionError, e:
    print e
integer division or modulo by zero
glue

 multiple ways to call other
programs and pipe the results
  sys.stdin, sys.stdout, sys.stderr

      os.system(), os.spawnl()

         subprocess.call()

         subprocess.Popen()
Modules: subprocess
from subprocess import *
p = Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
files, directories and more
        the os and sys modules
os.environ         sys.argv
os.getcwd          sys.stdin
os.chmod           sys.stdout
os.chown           sys.stderr
os.link            sys.platform
os.mkdir           sys.exit
os.remove
os.rename
Modules: os

                os.walk()
import os
>>> for x in os.walk('.'):
...     print x
...
('.', ['emptydir'], [ 'chinese-python-
poster.jpg', 'olf_proposal.txt', 'wc.py',
'olf.odp', 'shell.png', 'olf.txt',
'Pil.gif', 'adminscripting.png',
'num_occur.py'])
('./emptydir', [], [])
Modules: os.path

     exists
     getmtime
     isfile
     isdir
     islink
     ismount
     samefile
     split
command line arguments

           sys.argv
      list of all arguments

           optparse
  parsing all types of arguments

  returns options and parameters

         automatic help
Modules: others

databases – sqlite3 and others

             fork

          threading
ssh – paramiko
#!/usr/bin/env python
import paramiko

hostname = 'localhost'
port = 22
username = 'test'
password = 'password'

paramiko.util.log_to_file('paramiko.log')
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, username, password)
    stdin, stdout, stderr = s.exec_command('ifconfig')
    print stdout.read()
    s.close()
daemons

               python-daemon
import daemon
from spam import main_program
with daemon.DaemonContext():
main_program
ctypes
         load and use C libraries
          also works with Windows DLL's

>>> from ctypes import *
>>> libc = CDLL("libc.so.6")
>>> libc.printf("hello %sn", "Python")
hello Python
13
>>> print libc.time(None)
1253757776
>>> import datetime
>>> datetime.datetime.fromtimestamp(libc.time(None))
datetime.datetime(2009, 9, 23, 22, 5, 56)
A 2 line HTTP server
from  http.server import HTTPServer,
              SimpleHTTPRequestHandler
server = HTTPServer(("",8000),
           SimpleHTTPRequestHandler)
server.serve_forever()
What about Python 3?

it's a better language than 2.x

  it's not backward compatible

it's supported by the developers

         it's the future

it's not here (for sysadmins) yet
ipython, the uber shell

             extensive history

        usable as a system shell

        http://ipython.scipy.org
In [1]: print "hello"
------> print("hello")
hello

In [2]: ls
 adminscripting.png      olf.odp   Pil.gif
nd
Quick Python Book, 2            ed

           covering Python 3

        due out late this year
          http://www.manning.com/ceder
World's largest Python conference
             Talks

                         PyCon 2010
                                                             Open Space
         Tutorials
                                                             Hands-On Lab
        Lightning
          Talks           Feb. 17-25                          Exhibit Hall

        Keynotes
                          Atlanta, GA                           Sprints


                            NOW with
                         Poster sessions!




                         us.pycon.org
Photo: james.rintamaki
License: Attribution-
Share Alike 2.0
Generic
Resources
                  & contact info

    Python for Unix and Linux System Administration,
     Noah Gift, Jeremy M. Jones, O'Reilly Media 2008

          Pro Python System Administration,
      Rytis Sileika, Apress, (not yet published)

   “Python for system administrators”, James Knowlton,
                 IBM DeveloperWorks, 2007
http://www.ibm.com/developerworks/aix/library/au-python/

   Python Cookbook, Martelli, Ravenscroft & Ascher,
                  O'Reilly Media 2005
Contact info


http://tech.canterburyschool.org/tech/VernCeder

         http://www.manning.com/ceder

               vceder@gmail.com

More Related Content

What's hot

Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansibleGeorge Shuklin
 
Docker and the Linux Kernel
Docker and the Linux KernelDocker and the Linux Kernel
Docker and the Linux KernelDocker, Inc.
 
Understanding container security
Understanding container securityUnderstanding container security
Understanding container securityJohn Kinsella
 
Introduction to Docker Containers - Docker Captain
Introduction to Docker Containers - Docker CaptainIntroduction to Docker Containers - Docker Captain
Introduction to Docker Containers - Docker CaptainAjeet Singh Raina
 
Linux Container Technology 101
Linux Container Technology 101Linux Container Technology 101
Linux Container Technology 101inside-BigData.com
 
Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusGrafana Labs
 
Getting started with Ansible
Getting started with AnsibleGetting started with Ansible
Getting started with AnsibleIvan Serdyuk
 
Kubernetes #1 intro
Kubernetes #1   introKubernetes #1   intro
Kubernetes #1 introTerry Cho
 
Container Security Vulnerability Scanning with Trivy
Container Security Vulnerability Scanning with TrivyContainer Security Vulnerability Scanning with Trivy
Container Security Vulnerability Scanning with TrivyFaheem Memon
 
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | EdurekaWhat is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | EdurekaEdureka!
 
DevOps Meetup ansible
DevOps Meetup   ansibleDevOps Meetup   ansible
DevOps Meetup ansiblesriram_rajan
 
Optimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesOptimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesDinakar Guniguntala
 
Automation with ansible
Automation with ansibleAutomation with ansible
Automation with ansibleKhizer Naeem
 
Introduction to linux containers
Introduction to linux containersIntroduction to linux containers
Introduction to linux containersGoogle
 

What's hot (20)

Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Docker and the Linux Kernel
Docker and the Linux KernelDocker and the Linux Kernel
Docker and the Linux Kernel
 
Understanding container security
Understanding container securityUnderstanding container security
Understanding container security
 
Introduction to Docker Containers - Docker Captain
Introduction to Docker Containers - Docker CaptainIntroduction to Docker Containers - Docker Captain
Introduction to Docker Containers - Docker Captain
 
Linux Container Technology 101
Linux Container Technology 101Linux Container Technology 101
Linux Container Technology 101
 
CI/CD with Github Actions
CI/CD with Github ActionsCI/CD with Github Actions
CI/CD with Github Actions
 
Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with Prometheus
 
Getting started with Ansible
Getting started with AnsibleGetting started with Ansible
Getting started with Ansible
 
Kubernetes #1 intro
Kubernetes #1   introKubernetes #1   intro
Kubernetes #1 intro
 
Container Security Vulnerability Scanning with Trivy
Container Security Vulnerability Scanning with TrivyContainer Security Vulnerability Scanning with Trivy
Container Security Vulnerability Scanning with Trivy
 
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | EdurekaWhat is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
 
Hands-on Helm
Hands-on Helm Hands-on Helm
Hands-on Helm
 
AWS Code Services
AWS Code ServicesAWS Code Services
AWS Code Services
 
Jenkins tutorial
Jenkins tutorialJenkins tutorial
Jenkins tutorial
 
DevOps Meetup ansible
DevOps Meetup   ansibleDevOps Meetup   ansible
DevOps Meetup ansible
 
Optimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesOptimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on Kubernetes
 
Automation with ansible
Automation with ansibleAutomation with ansible
Automation with ansible
 
Advanced Container Security
Advanced Container Security Advanced Container Security
Advanced Container Security
 
Ansible
AnsibleAnsible
Ansible
 
Introduction to linux containers
Introduction to linux containersIntroduction to linux containers
Introduction to linux containers
 

Viewers also liked

Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin IGuixing Bai
 
Python for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administrationPython for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administrationVictor Marcelino
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
Server Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and WatchdogServer Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and WatchdogConFoo
 
PyOWM - my first open source project
PyOWM - my first open source projectPyOWM - my first open source project
PyOWM - my first open source projectClaudio Sparpaglione
 
Introduction to the rapid prototyping with python and linux for embedded systems
Introduction to the rapid prototyping with python and linux for embedded systemsIntroduction to the rapid prototyping with python and linux for embedded systems
Introduction to the rapid prototyping with python and linux for embedded systemsNaohiko Shimizu
 
Integrando mis librerías C++ con Python
Integrando mis librerías C++ con PythonIntegrando mis librerías C++ con Python
Integrando mis librerías C++ con PythonCarlos Gustavo Ruiz
 
Real world Django deployment using Chef
Real world Django deployment using ChefReal world Django deployment using Chef
Real world Django deployment using Chefcoderanger
 
Python en Android,Charla del FUDcon Latam 2012
Python en Android,Charla del FUDcon Latam 2012Python en Android,Charla del FUDcon Latam 2012
Python en Android,Charla del FUDcon Latam 2012Ernesto Crespo
 
Automated Deployment with Fabric
Automated Deployment with FabricAutomated Deployment with Fabric
Automated Deployment with Fabrictanihito
 
Final Internship presentation
Final Internship presentationFinal Internship presentation
Final Internship presentationAnjan Bhattrai
 
TDC2016SP - Trilha Linux Embarcado
TDC2016SP - Trilha Linux EmbarcadoTDC2016SP - Trilha Linux Embarcado
TDC2016SP - Trilha Linux Embarcadotdc-globalcode
 
Final Internship Presentation
Final Internship Presentation Final Internship Presentation
Final Internship Presentation Minhas Kamal
 
Architecting a Scalable Hadoop Platform: Top 10 considerations for success
Architecting a Scalable Hadoop Platform: Top 10 considerations for successArchitecting a Scalable Hadoop Platform: Top 10 considerations for success
Architecting a Scalable Hadoop Platform: Top 10 considerations for successDataWorks Summit
 
Python Deployment with Fabric
Python Deployment with FabricPython Deployment with Fabric
Python Deployment with Fabricandymccurdy
 
Internship final presentation GraphicPeople
Internship final presentation GraphicPeopleInternship final presentation GraphicPeople
Internship final presentation GraphicPeopleSamsuddoha Sams
 
Where to Deploy Hadoop: Bare Metal or Cloud?
Where to Deploy Hadoop: Bare Metal or Cloud? Where to Deploy Hadoop: Bare Metal or Cloud?
Where to Deploy Hadoop: Bare Metal or Cloud? DataWorks Summit
 
20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영Tae Young Lee
 

Viewers also liked (20)

Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
 
Python for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administrationPython for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administration
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Server Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and WatchdogServer Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and Watchdog
 
PyOWM - my first open source project
PyOWM - my first open source projectPyOWM - my first open source project
PyOWM - my first open source project
 
Programación Segura en python. Owasp Venezuela
Programación Segura en python. Owasp  VenezuelaProgramación Segura en python. Owasp  Venezuela
Programación Segura en python. Owasp Venezuela
 
Introduction to the rapid prototyping with python and linux for embedded systems
Introduction to the rapid prototyping with python and linux for embedded systemsIntroduction to the rapid prototyping with python and linux for embedded systems
Introduction to the rapid prototyping with python and linux for embedded systems
 
Integrando mis librerías C++ con Python
Integrando mis librerías C++ con PythonIntegrando mis librerías C++ con Python
Integrando mis librerías C++ con Python
 
Real world Django deployment using Chef
Real world Django deployment using ChefReal world Django deployment using Chef
Real world Django deployment using Chef
 
Linux system administration - part-2
Linux system administration - part-2Linux system administration - part-2
Linux system administration - part-2
 
Python en Android,Charla del FUDcon Latam 2012
Python en Android,Charla del FUDcon Latam 2012Python en Android,Charla del FUDcon Latam 2012
Python en Android,Charla del FUDcon Latam 2012
 
Automated Deployment with Fabric
Automated Deployment with FabricAutomated Deployment with Fabric
Automated Deployment with Fabric
 
Final Internship presentation
Final Internship presentationFinal Internship presentation
Final Internship presentation
 
TDC2016SP - Trilha Linux Embarcado
TDC2016SP - Trilha Linux EmbarcadoTDC2016SP - Trilha Linux Embarcado
TDC2016SP - Trilha Linux Embarcado
 
Final Internship Presentation
Final Internship Presentation Final Internship Presentation
Final Internship Presentation
 
Architecting a Scalable Hadoop Platform: Top 10 considerations for success
Architecting a Scalable Hadoop Platform: Top 10 considerations for successArchitecting a Scalable Hadoop Platform: Top 10 considerations for success
Architecting a Scalable Hadoop Platform: Top 10 considerations for success
 
Python Deployment with Fabric
Python Deployment with FabricPython Deployment with Fabric
Python Deployment with Fabric
 
Internship final presentation GraphicPeople
Internship final presentation GraphicPeopleInternship final presentation GraphicPeople
Internship final presentation GraphicPeople
 
Where to Deploy Hadoop: Bare Metal or Cloud?
Where to Deploy Hadoop: Bare Metal or Cloud? Where to Deploy Hadoop: Bare Metal or Cloud?
Where to Deploy Hadoop: Bare Metal or Cloud?
 
20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영
 

Similar to Python for Linux System Administration

PenTest using Python By Purna Chander
PenTest using Python By Purna ChanderPenTest using Python By Purna Chander
PenTest using Python By Purna Chandernforceit
 
Developing IT infrastructures with Puppet
Developing IT infrastructures with PuppetDeveloping IT infrastructures with Puppet
Developing IT infrastructures with PuppetAlessandro Franceschi
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Edureka!
 
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
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Raspberry pi Part 4
Raspberry pi Part 4Raspberry pi Part 4
Raspberry pi Part 4Techvilla
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Python: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersGlenn De Backer
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShellBoulos Dib
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Itzik Kotler
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsashukiller7
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docxwkyra78
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackDavid Sanchez
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programmingNimrita Koul
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 

Similar to Python for Linux System Administration (20)

Python1
Python1Python1
Python1
 
Python_intro.ppt
Python_intro.pptPython_intro.ppt
Python_intro.ppt
 
PenTest using Python By Purna Chander
PenTest using Python By Purna ChanderPenTest using Python By Purna Chander
PenTest using Python By Purna Chander
 
Developing IT infrastructures with Puppet
Developing IT infrastructures with PuppetDeveloping IT infrastructures with Puppet
Developing IT infrastructures with Puppet
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Python for Penetration testers
Python for Penetration testersPython for Penetration testers
Python for Penetration testers
 
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
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Raspberry pi Part 4
Raspberry pi Part 4Raspberry pi Part 4
Raspberry pi Part 4
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Python: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopers
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 

Python for Linux System Administration

  • 1. Python for Linux system administration (yes, this is a commercial) Vern Ceder Fort Wayne LUG Fort Wayne, IN
  • 2. Instead of? the “official” languages for sysamins bash* (and awk and sed) *or your favorite similar shell perl (if you don't believe me, ask O'Reilly)
  • 4. A scripting language should handle input & output process text – search, replace, pattern matching, etc. traverse filesystems use system utilities and libraries (glue)
  • 5. What's wrong with bash & perl? Nothing, really...
  • 6. bash is a great glue language pipes things like a champ has a ton of utilities (the whole system, in fact)
  • 7. awk and sed handle strings brilliantly
  • 9. but... bash is a pain when things get complex sed is tricky perl makes my head hurt (I always have rather liked awk)
  • 10. So what about Python? handles strings well is a good “glue” “batteries included” → I/O, filesystem, etc large collection of external libs
  • 11. Python also is very readable (and easy to maintain) is expressive is easy to grasp is either OO (or not) is fun
  • 12. everyone's doing it Redhat Ubuntu Google etc, etc, etc...
  • 13. but... (there's always a “but”) regular expressions aren't built-in not (quite) as common as perl
  • 14. and let's talk about the elephant in the room
  • 15. indentation yes, Python uses indentation to organize code it makes code more readable it's no weirder than {} or @$% get over it
  • 16. strings some built-in string methods split lower strip upper join isdigit replace swapcase find expandtabs count center startswith encode/decode endswith format
  • 17. for example to do what wc does: #!/usr/bin/env python import sys data = sys.stdin.read() chars = len(data) words = len(data.split()) lines = len(data.split('n')) print ("{0} {1} {2}".format(lines, words, chars)) doc@paladin:~/work/olf$ ./wc.py < wc.py 12 22 189
  • 18. or number of occurrences? in bash (not mine): doc@pal:~/olf$ tr " " "n" < wc.py | grep len | wc -w 3 in Python: #!/usr/bin/env python import sys data = sys.stdin.read() print data.count(sys.argv[1]) doc@paladin:~/work/olf$ ./num_occur.py len < wc.py 3
  • 19. regular expressions re module syntax similar to perl import re >>> re.findall("[Ll]en", "len is the Length") ['len', 'Len']
  • 20. exception handling y = 10 try: x = y / 0 except ZeroDivisionError, e: print e integer division or modulo by zero
  • 21. glue multiple ways to call other programs and pipe the results sys.stdin, sys.stdout, sys.stderr os.system(), os.spawnl() subprocess.call() subprocess.Popen()
  • 22. Modules: subprocess from subprocess import * p = Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE) out, err = p.communicate()
  • 23. files, directories and more the os and sys modules os.environ sys.argv os.getcwd sys.stdin os.chmod sys.stdout os.chown sys.stderr os.link sys.platform os.mkdir sys.exit os.remove os.rename
  • 24. Modules: os os.walk() import os >>> for x in os.walk('.'): ... print x ... ('.', ['emptydir'], [ 'chinese-python- poster.jpg', 'olf_proposal.txt', 'wc.py', 'olf.odp', 'shell.png', 'olf.txt', 'Pil.gif', 'adminscripting.png', 'num_occur.py']) ('./emptydir', [], [])
  • 25. Modules: os.path exists getmtime isfile isdir islink ismount samefile split
  • 26. command line arguments sys.argv list of all arguments optparse parsing all types of arguments returns options and parameters automatic help
  • 27. Modules: others databases – sqlite3 and others fork threading
  • 28. ssh – paramiko #!/usr/bin/env python import paramiko hostname = 'localhost' port = 22 username = 'test' password = 'password' paramiko.util.log_to_file('paramiko.log') s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, password) stdin, stdout, stderr = s.exec_command('ifconfig') print stdout.read() s.close()
  • 29. daemons python-daemon import daemon from spam import main_program with daemon.DaemonContext(): main_program
  • 30. ctypes load and use C libraries also works with Windows DLL's >>> from ctypes import * >>> libc = CDLL("libc.so.6") >>> libc.printf("hello %sn", "Python") hello Python 13 >>> print libc.time(None) 1253757776 >>> import datetime >>> datetime.datetime.fromtimestamp(libc.time(None)) datetime.datetime(2009, 9, 23, 22, 5, 56)
  • 31. A 2 line HTTP server from http.server import HTTPServer, SimpleHTTPRequestHandler server = HTTPServer(("",8000), SimpleHTTPRequestHandler) server.serve_forever()
  • 32. What about Python 3? it's a better language than 2.x it's not backward compatible it's supported by the developers it's the future it's not here (for sysadmins) yet
  • 33. ipython, the uber shell extensive history usable as a system shell http://ipython.scipy.org In [1]: print "hello" ------> print("hello") hello In [2]: ls adminscripting.png olf.odp Pil.gif
  • 34. nd Quick Python Book, 2 ed covering Python 3 due out late this year http://www.manning.com/ceder
  • 35. World's largest Python conference Talks PyCon 2010 Open Space Tutorials Hands-On Lab Lightning Talks Feb. 17-25 Exhibit Hall Keynotes Atlanta, GA Sprints NOW with Poster sessions! us.pycon.org Photo: james.rintamaki License: Attribution- Share Alike 2.0 Generic
  • 36. Resources & contact info Python for Unix and Linux System Administration, Noah Gift, Jeremy M. Jones, O'Reilly Media 2008 Pro Python System Administration, Rytis Sileika, Apress, (not yet published) “Python for system administrators”, James Knowlton, IBM DeveloperWorks, 2007 http://www.ibm.com/developerworks/aix/library/au-python/ Python Cookbook, Martelli, Ravenscroft & Ascher, O'Reilly Media 2005
  • 37. Contact info http://tech.canterburyschool.org/tech/VernCeder http://www.manning.com/ceder vceder@gmail.com