practical python for sysadmins

67
Prac%cal Python for Sysadmins Hello, PSU MacAdmins Conference 2013! Saturday, May 25, 13

Upload: others

Post on 19-Apr-2022

20 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Practical Python for Sysadmins

Prac%cal  Python  for  Sysadmins

Hello,  PSU  MacAdmins  Conference  2013!

Saturday, May 25, 13

Page 2: Practical Python for Sysadmins

Prac%cal  Python  for  Sysadmins

PSU  MacAdmins  Conference  2013

Tamman  Technologies,  Inc.Philadelphia,  Pennsylvania

Jeremy  Reichman@jaharmi

Nate  Walck@natewalck

Saturday, May 25, 13

Page 3: Practical Python for Sysadmins

‣ You  will  be  using  OS  X

‣ You  will  not  install  Python  yourself

‣ Feel  free  to  follow  along  in  Terminal

AssumpLons

Saturday, May 25, 13

Page 4: Practical Python for Sysadmins

Examples

‣ Text  file  with  commands,  try  them  yourself

‣ goo.gl/dgMjW

Saturday, May 25, 13

Page 5: Practical Python for Sysadmins

Quick  demo

Saturday, May 25, 13

Page 6: Practical Python for Sysadmins

No  need  to  be  afraid

PracLcal  Python  for  Mac  Admins

Saturday, May 25, 13

Page 7: Practical Python for Sysadmins

Why  Python?

Saturday, May 25, 13

Page 8: Practical Python for Sysadmins

Pros

‣ Escapes  symbols/spaces  for  you  (mostly)

‣ Easy  to  reuse  code

‣ No  need  to  reinvent  the  wheel

Saturday, May 25, 13

Page 9: Practical Python for Sysadmins

Cons

‣ Cannot  bash  things  (you  must  shell-­‐out)

‣ Different  from  command  prompt

‣ Can  be  hard  to  switch  mindset  from  bash

Saturday, May 25, 13

Page 10: Practical Python for Sysadmins

The  Python  Interpreter

Saturday, May 25, 13

Page 11: Practical Python for Sysadmins

‣ InteracLve  (Like  bash,  except  not)

‣ Starts  in  current  working  directory

‣ Inherits  your  shell  environment

‣ ‘>>>’  is  your  command  prompt

Python  Interpreter

Saturday, May 25, 13

Page 12: Practical Python for Sysadmins

Get  Current  Working  Directory

Python  Interpreter

>>> import os>>> os.getcwd()

Saturday, May 25, 13

Page 13: Practical Python for Sysadmins

Show  Environment  Variables

Python  Interpreter

>>> import os>>> print(os.environ)>>> for k, v in os.environ.items():>>> print(k, v)>>>

Saturday, May 25, 13

Page 14: Practical Python for Sysadmins

PEP  8  and  style‣ 4  spaces  per  indentaLon  level

‣ Wrap  long  lines  within  parentheses

‣ \  to  break  a  line

‣ Words  with  underscores

‣ this_is_the_style

‣ ThisIsNotTheStyle

Saturday, May 25, 13

Page 15: Practical Python for Sysadmins

IndenLng

‣ Applies  to  code  blocks

‣ Starts  and  ends  a  block

‣ Whitespace  must  be  consistent

Saturday, May 25, 13

Page 16: Practical Python for Sysadmins

Variables‣ Names  of  arbitrary  length

‣ Leders,  numbers,  symbols

‣ Must  begin  with  a  leder

‣ Some  names  reserved

‣ Values

‣ Any  object

Saturday, May 25, 13

Page 17: Practical Python for Sysadmins

Data  Types

Saturday, May 25, 13

Page 18: Practical Python for Sysadmins

‣ Dynamically  typed

‣ Strongly  typed

‣ Almost  everything  is  an  object…But  you  don’t  need  to  care

‣ Many  helpful  types  of  objects  are  built-­‐in

Data  Types

Saturday, May 25, 13

Page 19: Practical Python for Sysadmins

Data  Types

‣ type()  tells  you  what  an  object’s  type  is

‣ type(some_object)

‣ help()  gives  docs  on  objects

‣ help(some_object)

Saturday, May 25, 13

Page 20: Practical Python for Sysadmins

Numbers‣ Integers

‣ Floats

‣ FloaLng  point

‣ Decimal  numbers

‣ Not  quoted

‣ help(int),  help(float)

Saturday, May 25, 13

Page 21: Practical Python for Sysadmins

number1 = 7number2 = .256number3 = -1024

number1 + number2 + number3number1 < number2number2 == number3

Numbers

Saturday, May 25, 13

Page 22: Practical Python for Sysadmins

Strings

‣ Alphanumeric,  punctuaLon,  whitespace,  character  codes

‣ Quoted

‣ Single  or  double

‣ Triple

‣ help(str)

Saturday, May 25, 13

Page 23: Practical Python for Sysadmins

string1 = "Hello world"string2 = '''Lorem ipsum dolor sit

amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'''

Strings

Saturday, May 25, 13

Page 24: Practical Python for Sysadmins

string3 = u'1024 \u00D7 768'

print(string3)1024 × 768

Edit  >  Special  Characters  …

Saturday, May 25, 13

Page 25: Practical Python for Sysadmins

SubsLtute  Values  (or  Objects)  into  a  String

print "Some text %s" % substitute_this

print “A number %d”.format(substitute_this)

String  format

Saturday, May 25, 13

Page 26: Practical Python for Sysadmins

Lists

‣ Arrays  or  sequences

‣ Order  is  important

‣ Contains  any  data  type

‣ Square  brackets,  []

‣ help(list)  or  help([])

Saturday, May 25, 13

Page 27: Practical Python for Sysadmins

Booleans

True False

Bool True False,  None

String 'a',  'Any  text' ''

Int,  Float 1,  7,  256,  -­‐1024 0

List [1,  2,  3] []

Saturday, May 25, 13

Page 28: Practical Python for Sysadmins

DicLonaries‣ Key-­‐value  pairs

‣ Keys

‣ Case-­‐sensiLve

‣ No  duplicates

‣ New  value  overwrites

‣ Curly  braces,  {}

Saturday, May 25, 13

Page 29: Practical Python for Sysadmins

DicLonaries

‣ Values

‣ Any  data  type

‣ Mix  and  match  types

‣ Unordered

‣ help(dict)  or  help({})

Saturday, May 25, 13

Page 30: Practical Python for Sysadmins

Control  and  Logic

‣ Some  are  very  similar  to  bash

‣ Others  are  more  powerful  than  bash  logic

Saturday, May 25, 13

Page 31: Practical Python for Sysadmins

for  loops

‣ Use  “for”  reserved  keyword

‣ If  output  is  an  array,  consider  using  a  list  comprehension

Saturday, May 25, 13

Page 32: Practical Python for Sysadmins

for model in ${model_list[@]}do    echo $modeldone

for  loop  comparison

Bash {

Saturday, May 25, 13

Page 33: Practical Python for Sysadmins

for model in model_list:    print(model)

for model in ${model_list[@]}do    echo $modeldone

for  loop  comparison

Bash {Python {

Saturday, May 25, 13

Page 34: Practical Python for Sysadmins

if...then

‣ Use  “if,”  “elif,”  and  “else”  reserved  keywords

‣ First  true  statement  wins

Saturday, May 25, 13

Page 35: Practical Python for Sysadmins

if [ "$motivation" -gt "0" ]; then     echo "Script all the things"fi

if...then

Bash {

Saturday, May 25, 13

Page 36: Practical Python for Sysadmins

if motivation > 0:     print("Script all the things")

if [ "$motivation" -gt "0" ]; then     echo "Script all the things"fi

if...then

Bash {Python {

Saturday, May 25, 13

Page 37: Practical Python for Sysadmins

case

‣ No  such  thing  in  Python

‣ Use  the  if...elif...else  structure  to  accomplish  the  same  thing

Saturday, May 25, 13

Page 38: Practical Python for Sysadmins

case  statement

case $model in    "MacBookAir")        echo "Thin and Light"        ;;    "MacBookPro")        echo "Thick and Heavy"        ;;    "MacPro")        echo "Forever alone?"        ;;    *)        echo "Everything else"esac

Bash

Saturday, May 25, 13

Page 39: Practical Python for Sysadmins

case  statement

case $model in    "MacBookAir")        echo "Thin and Light"        ;;    "MacBookPro")        echo "Thick and Heavy"        ;;    "MacPro")        echo "Forever alone?"        ;;    *)        echo "Everything else"esac

Bash

Saturday, May 25, 13

Page 40: Practical Python for Sysadmins

if model == "MacBookAir":    print("Thin and Light")elif model == "MacBookPro":    print("Thick and Heavy")elif model == "MacPro":    print("Forever alone?")else:    print("Everything else")

case $model in    "MacBookAir")        echo "Thin and Light"        ;;    "MacBookPro")        echo "Thick and Heavy"        ;;    "MacPro")        echo "Forever alone?"        ;;    *)        echo "Everything else"esac

case  statementBash Python

Saturday, May 25, 13

Page 41: Practical Python for Sysadmins

FuncLons

‣ Use  “def”  reserved  keyword

‣ May  use  “return”  keyword

Saturday, May 25, 13

Page 42: Practical Python for Sysadmins

function hello_world (){    echo "Hello World!"} hello_world

FuncLons

Bash {

Saturday, May 25, 13

Page 43: Practical Python for Sysadmins

def hello_world():    print("Hello World!") hello_world()

function hello_world (){    echo "Hello World!"} hello_world

FuncLons

Bash {Python {

Saturday, May 25, 13

Page 44: Practical Python for Sysadmins

Working  with  Files

‣ Building  paths

‣ Pathname  components

Saturday, May 25, 13

Page 45: Practical Python for Sysadmins

Joining  Pathsimport ossilverlight_plugin_path = os.path.join("/", \ "Library", \ "Internet Plug-Ins", \ "Silverlight.plugin")

print(silverlight_plugin_path)/Library/Internet Plug-Ins/Silverlight.plugin

Working  with  Files

Saturday, May 25, 13

Page 46: Practical Python for Sysadmins

ManipulaLng  Paths

os.path.basename(silverlight_plugin_path)'Silverlight.plugin'

os.path.dirname(silverlight_plugin_path)'/Library/Internet Plug-Ins'

os.path.splitext("com.apple.Safari.plist")('com.apple.Safari', '.plist')

Working  with  Files

Saturday, May 25, 13

Page 47: Practical Python for Sysadmins

Tests  on  Files

‣ Does  the  path  exist?

‣ What  kind  of  object  is  at  that  path?

Saturday, May 25, 13

Page 48: Practical Python for Sysadmins

os.path.exists(silverlight_plugin_path)True

os.path.isdir(silverlight_plugin_path)True

os.path.islink("/etc")True

Tests  on  Files

Saturday, May 25, 13

Page 49: Practical Python for Sysadmins

glob

‣ Equivalent  to  shell  globbing

‣ Returns  matching  path(s)

glob  uses  the  fnmatch  module

Saturday, May 25, 13

Page 50: Practical Python for Sysadmins

import globosx_install = glob.glob("/Applications/" \ "Install*OS X*.app")

print(osx_install)['/Applications/Install Mac OS X Lion.app', '/Applications/Install OS X Mountain Lion.app']

glob

Saturday, May 25, 13

Page 51: Practical Python for Sysadmins

Version  numbers

‣ distuLls.version  supports  version  objects

‣ StrictVersion

‣ LooseVersion

‣ setuptools.pkg_resources

‣ parse_version

Saturday, May 25, 13

Page 52: Practical Python for Sysadmins

from distutils import versionversion.LooseVersion('10.4.1') > \version.StrictVersion('10.4.11a4')

False

Version  numbers

Saturday, May 25, 13

Page 53: Practical Python for Sysadmins

from pkg_resources import parse_version as V

V('10.4.1') > V('10.4.11a4')

False

Version  numbers

Saturday, May 25, 13

Page 54: Practical Python for Sysadmins

PyObjC

‣ You  can  run  ObjecLve-­‐C  code  via  a  Python  bridge  (Stop  the  madness!)

‣ Allows  access  to  naLve  methods  for  manipulaLng  the  OS.

Saturday, May 25, 13

Page 55: Practical Python for Sysadmins

Read  plist  via  CFPreferences

PyObjC

from Foundation import CFPreferencesCopyAppValue

preference_value = CFPreferencesCopyAppValue( \ 'AutoBackup', 'com.apple.TimeMachine')

print(preference_value)True

Saturday, May 25, 13

Page 56: Practical Python for Sysadmins

Get  Screen  ResoluLon

PyObjC

from AppKit import NSScreenwidth = NSScreen.mainScreen().frame().size.widthheight = NSScreen.mainScreen().frame().size.heightprint(width, height)(1440.0, 900.0)

Saturday, May 25, 13

Page 57: Practical Python for Sysadmins

Is  this  thing  working?Saturday, May 25, 13

Page 58: Practical Python for Sysadmins

syslog

‣ Send  messages  to  system  log

‣ Facility  (sender)

‣ Priority  (level)

Saturday, May 25, 13

Page 59: Practical Python for Sysadmins

import syslogsyslog.openlog("TEST")syslog.syslog(syslog.LOG_NOTICE, "No nonsense found.")syslog.closelog()

5/12/13 4:54:12.689 PM TEST[47885]: No nonsense found.

syslog

Saturday, May 25, 13

Page 60: Practical Python for Sysadmins

Running  shell  commands  in  Python?

Sure,  why  not

Saturday, May 25, 13

Page 61: Practical Python for Sysadmins

Running  Commands

‣ Subprocess  module

‣ Call  external  shell  commands

Returns

subprocess.call Return  code

subprocess.check_call Return  code  or  excepLon

subprocess.check_output Output  string  or  excepLon

Saturday, May 25, 13

Page 62: Practical Python for Sysadmins

‣ Arguments

‣ Command  as  a  list  of  strings

‣ Example:  [“echo”,  “Hello”]

‣ Using  shell=True

‣ Command  as  a  single  string

‣ Executed  directly  through  shell

‣ Strongly  Discouraged

Running  Commands

Saturday, May 25, 13

Page 63: Practical Python for Sysadmins

import subprocess

cmd_str = '/usr/bin/dsmemberutil checkmembership \-U jeremy -G admin'

cmd = cmd_str.split()

retcode = subprocess.call(cmd)retcode = subprocess.check_call(cmd)

output = subprocess.check_output(cmd)

Running  Commands

Saturday, May 25, 13

Page 64: Practical Python for Sysadmins

Helpful  ResourcesBecause  Learning  is  fun

Saturday, May 25, 13

Page 65: Practical Python for Sysadmins

Learning  More

‣ Think  Python  -­‐  goo.gl/G53Pa

‣ Code  Academy  -­‐  goo.gl/exxcw

‣ Dive  Into  Python  -­‐  goo.gl/h9QHZ

‣ Python.org  -­‐  goo.gl/Zpr3t

‣ Learn  Python  the  Hard  Way  -­‐  goo.gl/6Mw6u

Saturday, May 25, 13

Page 66: Practical Python for Sysadmins

GitHub

‣ Search  Github  to  see  if  it  already  exists

‣ Clone  a  project  and  use  it

‣ Tweak  if  necessary

‣ Read  their  code/documentaLon  to  make  sure  you  understand  how  it  works

Saturday, May 25, 13

Page 67: Practical Python for Sysadmins

irc.freenode.net

‣ Official  Python  Channel  -­‐  #python

‣ Several  helpful  Python  +  Mac  users  on                          ##osx-­‐server

Saturday, May 25, 13