SlideShare a Scribd company logo
1 of 43
Download to read offline
WRITING COMMAND-LINE
            TOOLS WITH IRONPYTHON
            AND VISUAL STUDIO
Noah Gift   Including PowerShell, and F#
Talk Objectives

¤  Freak  you out a bit.
¤  Teach you something you
    didn’t know. (Not covered in
    any book).
¤  Be controversial.

¤  Entertain you.
Monty Hall Problem
¤  You are invited to a game
    show.
¤  Game show host shows you
    three doors.
¤  Behind two doors there is a
    goat, and behind one door is
    a $50,000 dollar sports car.
Monty Hall Problem
¤  You  choose a door.
¤  Instead of opening your
    door. The game show
    host then opens up
    another door, to reveal a
    goat.
¤  Do you switch your
    choice?
Monty Hall Problem

¤  You  always switch doors:
    2/3 probability versus ½
    probability.
¤  Bayes Rule shows us this:
    (Think Spam classification).
Monty Hall Takeaway
¤  This isn’t intuitive to most
    people
¤  The human brain’s intuition
    is often broken.
¤  What else is your brain
    wrong about?
Windows Is The Great Satan?
                ¤  Command-line      is feeble
                ¤  People on twitter say it sucks
                ¤  Nothing COOL ever happens
                    on Windows
                ¤  This isn’t “their” conference.

                ¤  What if your brain’s intuition is
                    wrong about this too?
I Used To Hate Windows
                 ¨    I Grew Up
                 ¨    New Philosophy: Write
                       Code in any language,
                       in any environment.
                 ¨    If it is innovative, I don’t
                       care who made it.
                 ¨    Sorry Stallman, we
                       disagree.
What do most developers and admins
think of when they hear Linux?
¨  Power          ¨  The Shell
¨  Flexibility    ¨  Command-tools

¨  Bash           ¨  Man Pages

¨  SSH            ¨  Awk/Sed
What Is The Unifying Theme Around This?
¨  String Output is King   ¨    Tim O’Reilly in Unix
¨  Small Tools                   Power Tools, “A new
¨  Flexibility
                                  user by stringing
                                  together simple
¨  Geek Power.
                                  pipelines….”
The Hardest Part of Writing a *Nix
Command-line tool in Python
¨  Remote Administration:    ¨    Religious war in your
    Pyro vs SSH vs ???              company over using
¨  Dealing with *Nix tools         optparse, getargs,
    that pass you back              or argparse
    unstructured text.
Python/Unix Command-line Tools: The
End Game
                    ¨    Remote Object
                          Invocation (Pyro, SSH,
                          Fabric)
                    ¨    Security (SSH, SSL)
                    ¨    Automation
                    ¨    Application API
                    ¨    Event Management
                          (Pyro)
                    ¨    Transactions (Mercurial?)
How To Write A Classic IronPython CLI
¨  I needed to upgrade 100’s of thousands of lines of
    C# to .NET 4.0.
¨  I wrote a quick and dirty Command-line tool in

    IronPython.
Project Upgrader: Validate Version
         	
  

Step 1   def	
  validate_vsver(slnfile):	
  
         	
  	
  	
  	
  """Validates	
  whether	
  a	
  .sln	
  file	
  has	
  already	
  been	
  upgraded	
  to	
  VS	
  2010"""	
  
         	
  	
  	
  	
  try:	
  
         	
  	
  	
  	
  	
  	
  	
  	
  project_file	
  =	
  open(slnfile)	
  
         	
  	
  	
  	
  	
  	
  	
  	
  for	
  project_version_line	
  in	
  project_file.readlines():	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  if	
  "Visual	
  Studio	
  2010"	
  in	
  project_version_line:	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  log.debug("Found	
  VS	
  2010	
  project	
  line:	
  %s"	
  %	
  project_version_line)	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  log.debug("Project	
  file	
  already	
  upgraded....skipping:	
  %s"	
  %	
  slnfile)	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  False	
  
         	
  	
  	
  	
  	
  	
  	
  	
  return	
  True	
  
         	
  	
  	
  	
  finally:	
  
         	
  	
  	
  	
  	
  	
  	
  	
  project_file.close()	
  
Project Upgrader: Walk A Tree
Step 2   def	
  walk_tree(path,	
  extension="sln",	
  
         version_control_type=".svn",	
  exclude_path=None):	
  
         	
  	
  	
  	
  """Walks	
  a	
  tree,	
  if	
  there	
  is	
  a	
  match	
  to	
  an	
  extension,	
  
         it	
  returns	
  a	
  fullpath.	
  
         	
  	
  	
  	
  	
  
         	
  	
  	
  	
  Skips	
  version_control_type	
  directories,	
  which	
  by	
  
         default	
  is	
  set	
  to	
  .svn	
  	
  
         	
  	
  	
  	
  """	
  
         	
  	
  	
  	
  for	
  dirpath,dirname,filename	
  in	
  os.walk(path):	
  
         	
  	
  	
  	
  	
  	
  	
  	
  #The	
  walk	
  should	
  skip	
  version	
  control	
  directories	
  
         	
  	
  	
  	
  	
  	
  	
  	
  for	
  dir	
  in	
  dirname:	
  
Project Upgrader: Convert Project
         	
  
Step 3   def	
  convert_project(filename):	
  
         	
  	
  	
  	
  """Converts	
  a	
  project	
  to	
  VS2010	
  using	
  deven	
  via	
  .NET	
  Process	
  
         Class"""	
  
         	
  	
  	
  	
  p	
  =	
  Process()	
  
         	
  	
  	
  	
  p.StartInfo.UseShellExecute	
  =	
  False	
  
         	
  	
  	
  	
  p.StartInfo.RedirectStandardOutput	
  =	
  True	
  
         	
  	
  	
  	
  p.StartInfo.RedirectStandardError	
  =	
  True	
  
         	
  	
  	
  	
  p.StartInfo.FileName	
  =	
  """C:Program	
  Files	
  (x86)Microsoft	
  
         Visual	
  Studio	
  10.0Common7IDEdevenv.exe"""	
  
         print	
  "Stdout:	
  %s|	
  Stderr:	
  %s"	
  %	
  (stdout,	
  stderr)	
  
         	
  	
  	
  	
  p.WaitForExit()	
  
         	
  	
  	
  	
  return	
  p.ExitCode	
  
Project Upgrader: Convert Tree
         	
  
Step 4   def	
  convert_tree(path,	
  exclude_path):	
  
         	
  	
  	
  	
  """Recursively	
  modifies	
  a	
  tree	
  of	
  sln	
  files,	
  if	
  they	
  
         haven't	
  been	
  upgraded	
  to	
  VS	
  2010"""	
  
         	
  	
  	
  	
  	
  
         	
  	
  	
  	
  for	
  file	
  in	
  walk_tree(path,	
  exclude_path=exclude_path):	
  
         	
  	
  	
  	
  	
  	
  	
  	
  if	
  not	
  validate_vsver(file):	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  #we	
  should	
  pass	
  upgrading	
  if	
  validate_vsver	
  
         returns	
  False	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  continue	
  
         	
  	
  	
  	
  	
  	
  	
  	
  exit_code	
  =	
  convert_project(file)	
  
         	
  	
  	
  	
  	
  	
  	
  	
  log.info("%s,	
  %s"	
  %	
  (exit_code,	
  file))	
  
Project Upgrader: Run method
         	
  
Step 4   	
  def	
  run(self):	
  
         	
  	
  	
  	
  	
  	
  	
  	
  args,	
  parser	
  =	
  self.options()	
  
         	
  	
  	
  	
  	
  	
  	
  	
  if	
  args.path:	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  exclude	
  =	
  None	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  if	
  args.exclude:	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  exclude	
  =	
  args.exclude	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  log.info("Exclude	
  set:	
  %s"	
  %	
  exclude)	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  log.info("%s	
  Running	
  VS2010	
  upgrade	
  on	
  tree:	
  %s	
  |	
  
         excluding	
  dirs	
  named:	
  %s"	
  %	
  (time.ctime(),	
  args.path,	
  exclude))	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  convert_tree(args.path,	
  exclude_path=exclude)	
  	
  	
  	
  	
  	
  	
  	
  	
  
         	
  	
  	
  	
  	
  	
  	
  	
  else:	
  
         	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  parser.print_help()
Python is like Kudzu
                  ¤  Itsstrength is that it can
                      embed itself into any project,
                      any operating system.
                  ¤  Not always the best tool, but
                      often good enough.
Who Is The Target Audience For
Command-line Tools?
                  ¤  Systems Administrators
                  ¤  Power Users
                  ¤  Developers

                  ¤  Systems Integrators/OEM

                  ¤  Young Geeky Stallman
What Does It Really Mean To Write A
Command-line tool on Linux
                  ¤  You  have an executable that
                      runs in the context of, most
                      likely, Bash.
                  ¤  You output a string, which you
                      can then pipeline into our Unix
                      tools, sed, awk, grep.
                  ¤  If your nice you create –help
What Does It Really Mean To Write A
Command-line tool on Modern Windows
                 ¤  Itis going to run inside of
                     PowerShell. PowerShell is your
                     bash.
                 ¤  You have a unified interface
                     to .NET and every possible
                     high level automation API you
                     can think of.
                 ¤  PowerShell tools expect
                     OBJECTS not strings.
PowerShell is Secure By Default
                         ¤  Default  File
                             Association is
                             Notepad or ISE.
                         ¤  Remoting is
                             disabled.
                         ¤  No execution of
                             scripts.
                         ¤  Script Signing
Learning To Properly Write IronPython
Command-Line Tools: “A two minute affair”
                    ¤  Actually no, not even close.
                    ¤  Forget “most” of what you
                        know from linux.
                    ¤  PowerShell changes
                        everything.
PowerShell Object Passing Changes How
Shells Work
                  ¤  Fundamental   change to
                      understand
                  ¤  You need to understand this to
                      write command-line tools on
                      Windows
                  ¤  Game changer
We’re not in a flyover state anymore
                 ¤  String
                          output is lame!
                 ¤  PowerShell wants objects
                 ¤  What to do…what to do…
Fight the ecosystem and you will die
                 ¤  Command-line     tools should run
                     in PowerShell not cmd.exe.
                 ¤  The bash/linux CPython way,
                     won’t cut it here.
                 ¤  You must think the way .NET
                     thinks.
                 ¤  Everything takes and returns
                     an Object.
PowerShell Endgame: We did
EVERYTHING for you.
                 ¤  Encrypted,  paranoid secure,
                     transactional, asynchronous
                     remoting of serialized objects
                 ¤  High level automation API to
                     everything.
                 ¤  Ignore at your own peril.
Writing a PowerShell Module In IronPython: The
“real” way to write Command-line tools?
¨  Create a New Visual Studio Project
¨  Thinks Objects

¨  Use PowerShell SDK

¨  Write a Binary Module
Installing the PowerShell SDK
¤  Download  the SDK
¤  Add a reference to the DLL in your Visual Studio Project

¤ C:ProgramFiles (x86)Reference
  AssembliesMicrosoftWindowsPowerShell
  v1.0System.Management.Automation
Finding and Loading PowerShell Modules
¨  Get-Module –all
¨  When you create a .dll in IronPython, could then

    simply integrate it into the PowerShell workflow.
What is a Binary Module?
¤  A .NET assembly compiled against PowerShell
   libraries.
¨  For IronPython folks, this is one way to integrate into
    PowerShell
¨  In a lot of documentation it will refer to C# code.

¨  You can also write a PowerShell, non-compiled,
    module.
Creating a Binary Module For Powershell
 in IronPython
¤  http://stackoverflow.com/questions/2094694/launch-
    powershell-under-net-4
¤  You need to tweak some registry settings to support .NET 4.0
    in PowerShell.
Creating a Binary Module For Powershell
 in IronPython: Continued
¤  Should   follow C# example code for best implementation
    advice.
¤  Note, Argparse, Optparse, etc, aren’t used. They don’t make
    sense.
¤  These are objects being passed into other cmdlets, and
    methods are being called on those objects.
IronPython PowerShell Module Hello
World
Visual Studio   import	
  clr	
  
Project:        clr.AddReference('System.Management.Automation')	
  
                print	
  'Hello	
  World'	
  
Step 1
IronPython PowerShell Module Hello World
Visual Studio   ¨  Build the project to create a .dll
Project:
                ¨  In PowerShell Import Module
Step 2
                ¨  Import-Module MyModule.dll

                ¨  You can know interact with it from inside

                    of .Net. Is this a commandline tool???
Setting Up A PowerShell Profile For IronPython
¨  Just like in Bash or
    ZSH, aliases are your
    friend.
¨  Edit your $profile with
    the ISE, and add
    interactive IronPython
    to it.
Creating Standalone IronPython executables
¨  Make sure you can
    pass objects in and out
    of them.
¨  Use the IronPython on

    codeplex: Pyc-Python
    Command-line compiler
F#: The Elephant in the Room
                ¤  Type   inference
                ¤  Immutable data structures
                ¤  Run as script or compiled

                ¤  Tail recursion

                ¤  Fully integrated with Visual
                    Studio
                ¤  Sexier then Python?
F# and Python: A Sexy Beast
                ¤  Mixing   .dll files written in F#
                    into IronPython modules,
                    loaded into Powershell.
                ¤  Calling IronPython/CPython
                    from inside of F#
                ¤  “A statically typed
                    Python…” (Note, this will come
                    up..just preparing you…)
Credit Some Excellent Books That
Reference PowerShell
                   ¤  PowerShell   in Action,
                       Manning (The Bible)
                   ¤  PowerShell Cookbook, O’Reilly

                   ¤  IronPython in Action, Manning
Conclusion
             ¤  PowerShell isn’t a competing
                 language, it IS THE ECOSYSTEM.
             ¤  Windows Systems Admins are
                 using PowerShell for everything
             ¤  Get your head wrapped around
                 object based pipelines.
             ¤  Why doesn’t Linux have this?
Questions?
             Code:
             https://bitbucket.org/noahgift/pycon2011-
             ironpython-cli

More Related Content

What's hot

Introduction to Docker, December 2014 "Tour de France" Bordeaux Special Edition
Introduction to Docker, December 2014 "Tour de France" Bordeaux Special EditionIntroduction to Docker, December 2014 "Tour de France" Bordeaux Special Edition
Introduction to Docker, December 2014 "Tour de France" Bordeaux Special EditionJérôme Petazzoni
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015ice799
 
Docker: automation for the rest of us
Docker: automation for the rest of usDocker: automation for the rest of us
Docker: automation for the rest of usJérôme Petazzoni
 
Aucklug slides - desktop tips and tricks
Aucklug slides - desktop tips and tricksAucklug slides - desktop tips and tricks
Aucklug slides - desktop tips and tricksGlen Ogilvie
 
Puppet Camp LA 2/19/2015
Puppet Camp LA 2/19/2015Puppet Camp LA 2/19/2015
Puppet Camp LA 2/19/2015ice799
 
Hacking - high school intro
Hacking - high school introHacking - high school intro
Hacking - high school introPeter Hlavaty
 
Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017Daniel Bohannon
 
Pwning with powershell
Pwning with powershellPwning with powershell
Pwning with powershelljaredhaight
 
Defcon 22-colby-moore-patrick-wardle-synack-drop cam
Defcon 22-colby-moore-patrick-wardle-synack-drop camDefcon 22-colby-moore-patrick-wardle-synack-drop cam
Defcon 22-colby-moore-patrick-wardle-synack-drop camPriyanka Aash
 
Puppet for SysAdmins
Puppet for SysAdminsPuppet for SysAdmins
Puppet for SysAdminsPuppet
 
Teensy Programming for Everyone
Teensy Programming for EveryoneTeensy Programming for Everyone
Teensy Programming for EveryoneNikhil Mittal
 
Chef Conf 2015: Package Management & Chef
Chef Conf 2015: Package Management & ChefChef Conf 2015: Package Management & Chef
Chef Conf 2015: Package Management & Chefice799
 
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)Rob Fuller
 
Puppet getting started by Dirk Götz
Puppet getting started by Dirk GötzPuppet getting started by Dirk Götz
Puppet getting started by Dirk GötzNETWAYS
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric WarfareWill Schroeder
 
Get-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for EvilGet-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for Eviljaredhaight
 
Catch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueCatch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueWill Schroeder
 
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attacDefcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attacPriyanka Aash
 
Introducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkitIntroducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkitjaredhaight
 

What's hot (20)

Introduction to Docker, December 2014 "Tour de France" Bordeaux Special Edition
Introduction to Docker, December 2014 "Tour de France" Bordeaux Special EditionIntroduction to Docker, December 2014 "Tour de France" Bordeaux Special Edition
Introduction to Docker, December 2014 "Tour de France" Bordeaux Special Edition
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015
 
Docker: automation for the rest of us
Docker: automation for the rest of usDocker: automation for the rest of us
Docker: automation for the rest of us
 
Aucklug slides - desktop tips and tricks
Aucklug slides - desktop tips and tricksAucklug slides - desktop tips and tricks
Aucklug slides - desktop tips and tricks
 
THE BASIC TOOLS
THE BASIC TOOLSTHE BASIC TOOLS
THE BASIC TOOLS
 
Puppet Camp LA 2/19/2015
Puppet Camp LA 2/19/2015Puppet Camp LA 2/19/2015
Puppet Camp LA 2/19/2015
 
Hacking - high school intro
Hacking - high school introHacking - high school intro
Hacking - high school intro
 
Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017
 
Pwning with powershell
Pwning with powershellPwning with powershell
Pwning with powershell
 
Defcon 22-colby-moore-patrick-wardle-synack-drop cam
Defcon 22-colby-moore-patrick-wardle-synack-drop camDefcon 22-colby-moore-patrick-wardle-synack-drop cam
Defcon 22-colby-moore-patrick-wardle-synack-drop cam
 
Puppet for SysAdmins
Puppet for SysAdminsPuppet for SysAdmins
Puppet for SysAdmins
 
Teensy Programming for Everyone
Teensy Programming for EveryoneTeensy Programming for Everyone
Teensy Programming for Everyone
 
Chef Conf 2015: Package Management & Chef
Chef Conf 2015: Package Management & ChefChef Conf 2015: Package Management & Chef
Chef Conf 2015: Package Management & Chef
 
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
 
Puppet getting started by Dirk Götz
Puppet getting started by Dirk GötzPuppet getting started by Dirk Götz
Puppet getting started by Dirk Götz
 
Adventures in Asymmetric Warfare
Adventures in Asymmetric WarfareAdventures in Asymmetric Warfare
Adventures in Asymmetric Warfare
 
Get-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for EvilGet-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for Evil
 
Catch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs BlueCatch Me If You Can: PowerShell Red vs Blue
Catch Me If You Can: PowerShell Red vs Blue
 
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attacDefcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
 
Introducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkitIntroducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkit
 

Viewers also liked

Python with dot net and vs2010
Python with dot net and vs2010Python with dot net and vs2010
Python with dot net and vs2010Wei Sun
 
IronPython and Dynamic Languages on .NET by Mahesh Prakriya
 IronPython and Dynamic Languages on .NET by Mahesh Prakriya IronPython and Dynamic Languages on .NET by Mahesh Prakriya
IronPython and Dynamic Languages on .NET by Mahesh Prakriyacodebits
 
Open Source .NET
Open Source .NETOpen Source .NET
Open Source .NETOnyxfish
 
Python 101 For The Net Developer
Python 101 For The Net DeveloperPython 101 For The Net Developer
Python 101 For The Net DeveloperSarah Dutkiewicz
 
Dynamic programming on .net
Dynamic programming on .netDynamic programming on .net
Dynamic programming on .netMohammad Tayseer
 
The .NET developer's introduction to IronPython
The .NET developer's introduction to IronPythonThe .NET developer's introduction to IronPython
The .NET developer's introduction to IronPythonDror Helper
 
SyPy IronPython
SyPy IronPythonSyPy IronPython
SyPy IronPythonNick Hodge
 
Python Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-uPython Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-uNikola Plejic
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

Viewers also liked (9)

Python with dot net and vs2010
Python with dot net and vs2010Python with dot net and vs2010
Python with dot net and vs2010
 
IronPython and Dynamic Languages on .NET by Mahesh Prakriya
 IronPython and Dynamic Languages on .NET by Mahesh Prakriya IronPython and Dynamic Languages on .NET by Mahesh Prakriya
IronPython and Dynamic Languages on .NET by Mahesh Prakriya
 
Open Source .NET
Open Source .NETOpen Source .NET
Open Source .NET
 
Python 101 For The Net Developer
Python 101 For The Net DeveloperPython 101 For The Net Developer
Python 101 For The Net Developer
 
Dynamic programming on .net
Dynamic programming on .netDynamic programming on .net
Dynamic programming on .net
 
The .NET developer's introduction to IronPython
The .NET developer's introduction to IronPythonThe .NET developer's introduction to IronPython
The .NET developer's introduction to IronPython
 
SyPy IronPython
SyPy IronPythonSyPy IronPython
SyPy IronPython
 
Python Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-uPython Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-u
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to PyCon 2011: IronPython Command Line

the productive programer: mechanics
the productive programer: mechanicsthe productive programer: mechanics
the productive programer: mechanicselliando dias
 
Puppet for Sys Admins
Puppet for Sys AdminsPuppet for Sys Admins
Puppet for Sys AdminsPuppet
 
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
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementLaurent Leturgez
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackDavid Sanchez
 
Getting started with puppet and vagrant (1)
Getting started with puppet and vagrant (1)Getting started with puppet and vagrant (1)
Getting started with puppet and vagrant (1)Puppet
 
Introduction to Docker and deployment and Azure
Introduction to Docker and deployment and AzureIntroduction to Docker and deployment and Azure
Introduction to Docker and deployment and AzureJérôme Petazzoni
 
DevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and dockerDevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and dockerMark Stillwell
 
DevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and dockerDevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and dockerMark Stillwell
 
Bash shell programming in linux
Bash shell programming in linuxBash shell programming in linux
Bash shell programming in linuxNorberto Angulo
 
Porting your favourite cmdline tool to Android
Porting your favourite cmdline tool to AndroidPorting your favourite cmdline tool to Android
Porting your favourite cmdline tool to AndroidVlatko Kosturjak
 
Part 4 Scripting and Virtualization (due Week 7)Objectives1. .docx
Part 4 Scripting and Virtualization (due Week 7)Objectives1. .docxPart 4 Scripting and Virtualization (due Week 7)Objectives1. .docx
Part 4 Scripting and Virtualization (due Week 7)Objectives1. .docxkarlhennesey
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administrationvceder
 
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, PuppetPuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, PuppetPuppet
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionProf. Wim Van Criekinge
 
Power shell training
Power shell trainingPower shell training
Power shell trainingDavid Brabant
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java ProgrammingKaty Allen
 

Similar to PyCon 2011: IronPython Command Line (20)

the productive programer: mechanics
the productive programer: mechanicsthe productive programer: mechanics
the productive programer: mechanics
 
Puppet for Sys Admins
Puppet for Sys AdminsPuppet for Sys Admins
Puppet for Sys Admins
 
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)
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
 
Getting started with puppet and vagrant (1)
Getting started with puppet and vagrant (1)Getting started with puppet and vagrant (1)
Getting started with puppet and vagrant (1)
 
Introduction to Docker and deployment and Azure
Introduction to Docker and deployment and AzureIntroduction to Docker and deployment and Azure
Introduction to Docker and deployment and Azure
 
DevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and dockerDevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and docker
 
DevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and dockerDevOps introduction with ansible, vagrant, and docker
DevOps introduction with ansible, vagrant, and docker
 
Bash shell programming in linux
Bash shell programming in linuxBash shell programming in linux
Bash shell programming in linux
 
Porting your favourite cmdline tool to Android
Porting your favourite cmdline tool to AndroidPorting your favourite cmdline tool to Android
Porting your favourite cmdline tool to Android
 
Part 4 Scripting and Virtualization (due Week 7)Objectives1. .docx
Part 4 Scripting and Virtualization (due Week 7)Objectives1. .docxPart 4 Scripting and Virtualization (due Week 7)Objectives1. .docx
Part 4 Scripting and Virtualization (due Week 7)Objectives1. .docx
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
 
Os Wilhelm
Os WilhelmOs Wilhelm
Os Wilhelm
 
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, PuppetPuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
 
Power shell training
Power shell trainingPower shell training
Power shell training
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
 

More from Lecturer UC Davis & Northwestern (8)

Sentiment analysis for Business Analytics
Sentiment analysis for Business AnalyticsSentiment analysis for Business Analytics
Sentiment analysis for Business Analytics
 
Social power and_influence_in_the_nba_gitpro
Social power and_influence_in_the_nba_gitproSocial power and_influence_in_the_nba_gitpro
Social power and_influence_in_the_nba_gitpro
 
Erlang factory slides
Erlang factory slidesErlang factory slides
Erlang factory slides
 
iphone and Google App Engine
iphone and Google App Engineiphone and Google App Engine
iphone and Google App Engine
 
Favorite X Code4 Features
Favorite X Code4 FeaturesFavorite X Code4 Features
Favorite X Code4 Features
 
RabbitMQ Plugins Talk
RabbitMQ Plugins TalkRabbitMQ Plugins Talk
RabbitMQ Plugins Talk
 
Pycon 2008: Python Command-line Tools *Nix
Pycon 2008:  Python Command-line Tools *NixPycon 2008:  Python Command-line Tools *Nix
Pycon 2008: Python Command-line Tools *Nix
 
iphonedevcon 2010: Cooking with iAd
iphonedevcon 2010:  Cooking with iAd iphonedevcon 2010:  Cooking with iAd
iphonedevcon 2010: Cooking with iAd
 

PyCon 2011: IronPython Command Line

  • 1. WRITING COMMAND-LINE TOOLS WITH IRONPYTHON AND VISUAL STUDIO Noah Gift Including PowerShell, and F#
  • 2. Talk Objectives ¤  Freak you out a bit. ¤  Teach you something you didn’t know. (Not covered in any book). ¤  Be controversial. ¤  Entertain you.
  • 3. Monty Hall Problem ¤  You are invited to a game show. ¤  Game show host shows you three doors. ¤  Behind two doors there is a goat, and behind one door is a $50,000 dollar sports car.
  • 4. Monty Hall Problem ¤  You choose a door. ¤  Instead of opening your door. The game show host then opens up another door, to reveal a goat. ¤  Do you switch your choice?
  • 5. Monty Hall Problem ¤  You always switch doors: 2/3 probability versus ½ probability. ¤  Bayes Rule shows us this: (Think Spam classification).
  • 6. Monty Hall Takeaway ¤  This isn’t intuitive to most people ¤  The human brain’s intuition is often broken. ¤  What else is your brain wrong about?
  • 7. Windows Is The Great Satan? ¤  Command-line is feeble ¤  People on twitter say it sucks ¤  Nothing COOL ever happens on Windows ¤  This isn’t “their” conference. ¤  What if your brain’s intuition is wrong about this too?
  • 8. I Used To Hate Windows ¨  I Grew Up ¨  New Philosophy: Write Code in any language, in any environment. ¨  If it is innovative, I don’t care who made it. ¨  Sorry Stallman, we disagree.
  • 9. What do most developers and admins think of when they hear Linux? ¨  Power ¨  The Shell ¨  Flexibility ¨  Command-tools ¨  Bash ¨  Man Pages ¨  SSH ¨  Awk/Sed
  • 10. What Is The Unifying Theme Around This? ¨  String Output is King ¨  Tim O’Reilly in Unix ¨  Small Tools Power Tools, “A new ¨  Flexibility user by stringing together simple ¨  Geek Power. pipelines….”
  • 11. The Hardest Part of Writing a *Nix Command-line tool in Python ¨  Remote Administration: ¨  Religious war in your Pyro vs SSH vs ??? company over using ¨  Dealing with *Nix tools optparse, getargs, that pass you back or argparse unstructured text.
  • 12. Python/Unix Command-line Tools: The End Game ¨  Remote Object Invocation (Pyro, SSH, Fabric) ¨  Security (SSH, SSL) ¨  Automation ¨  Application API ¨  Event Management (Pyro) ¨  Transactions (Mercurial?)
  • 13. How To Write A Classic IronPython CLI ¨  I needed to upgrade 100’s of thousands of lines of C# to .NET 4.0. ¨  I wrote a quick and dirty Command-line tool in IronPython.
  • 14. Project Upgrader: Validate Version   Step 1 def  validate_vsver(slnfile):          """Validates  whether  a  .sln  file  has  already  been  upgraded  to  VS  2010"""          try:                  project_file  =  open(slnfile)                  for  project_version_line  in  project_file.readlines():                          if  "Visual  Studio  2010"  in  project_version_line:                                  log.debug("Found  VS  2010  project  line:  %s"  %  project_version_line)                                  log.debug("Project  file  already  upgraded....skipping:  %s"  %  slnfile)                                  return  False                  return  True          finally:                  project_file.close()  
  • 15. Project Upgrader: Walk A Tree Step 2 def  walk_tree(path,  extension="sln",   version_control_type=".svn",  exclude_path=None):          """Walks  a  tree,  if  there  is  a  match  to  an  extension,   it  returns  a  fullpath.                    Skips  version_control_type  directories,  which  by   default  is  set  to  .svn            """          for  dirpath,dirname,filename  in  os.walk(path):                  #The  walk  should  skip  version  control  directories                  for  dir  in  dirname:  
  • 16. Project Upgrader: Convert Project   Step 3 def  convert_project(filename):          """Converts  a  project  to  VS2010  using  deven  via  .NET  Process   Class"""          p  =  Process()          p.StartInfo.UseShellExecute  =  False          p.StartInfo.RedirectStandardOutput  =  True          p.StartInfo.RedirectStandardError  =  True          p.StartInfo.FileName  =  """C:Program  Files  (x86)Microsoft   Visual  Studio  10.0Common7IDEdevenv.exe"""   print  "Stdout:  %s|  Stderr:  %s"  %  (stdout,  stderr)          p.WaitForExit()          return  p.ExitCode  
  • 17. Project Upgrader: Convert Tree   Step 4 def  convert_tree(path,  exclude_path):          """Recursively  modifies  a  tree  of  sln  files,  if  they   haven't  been  upgraded  to  VS  2010"""                    for  file  in  walk_tree(path,  exclude_path=exclude_path):                  if  not  validate_vsver(file):                          #we  should  pass  upgrading  if  validate_vsver   returns  False                          continue                  exit_code  =  convert_project(file)                  log.info("%s,  %s"  %  (exit_code,  file))  
  • 18. Project Upgrader: Run method   Step 4  def  run(self):                  args,  parser  =  self.options()                  if  args.path:                          exclude  =  None                          if  args.exclude:                                  exclude  =  args.exclude                                  log.info("Exclude  set:  %s"  %  exclude)                          log.info("%s  Running  VS2010  upgrade  on  tree:  %s  |   excluding  dirs  named:  %s"  %  (time.ctime(),  args.path,  exclude))                          convert_tree(args.path,  exclude_path=exclude)                                  else:                          parser.print_help()
  • 19. Python is like Kudzu ¤  Itsstrength is that it can embed itself into any project, any operating system. ¤  Not always the best tool, but often good enough.
  • 20. Who Is The Target Audience For Command-line Tools? ¤  Systems Administrators ¤  Power Users ¤  Developers ¤  Systems Integrators/OEM ¤  Young Geeky Stallman
  • 21. What Does It Really Mean To Write A Command-line tool on Linux ¤  You have an executable that runs in the context of, most likely, Bash. ¤  You output a string, which you can then pipeline into our Unix tools, sed, awk, grep. ¤  If your nice you create –help
  • 22. What Does It Really Mean To Write A Command-line tool on Modern Windows ¤  Itis going to run inside of PowerShell. PowerShell is your bash. ¤  You have a unified interface to .NET and every possible high level automation API you can think of. ¤  PowerShell tools expect OBJECTS not strings.
  • 23. PowerShell is Secure By Default ¤  Default File Association is Notepad or ISE. ¤  Remoting is disabled. ¤  No execution of scripts. ¤  Script Signing
  • 24. Learning To Properly Write IronPython Command-Line Tools: “A two minute affair” ¤  Actually no, not even close. ¤  Forget “most” of what you know from linux. ¤  PowerShell changes everything.
  • 25. PowerShell Object Passing Changes How Shells Work ¤  Fundamental change to understand ¤  You need to understand this to write command-line tools on Windows ¤  Game changer
  • 26. We’re not in a flyover state anymore ¤  String output is lame! ¤  PowerShell wants objects ¤  What to do…what to do…
  • 27. Fight the ecosystem and you will die ¤  Command-line tools should run in PowerShell not cmd.exe. ¤  The bash/linux CPython way, won’t cut it here. ¤  You must think the way .NET thinks. ¤  Everything takes and returns an Object.
  • 28. PowerShell Endgame: We did EVERYTHING for you. ¤  Encrypted, paranoid secure, transactional, asynchronous remoting of serialized objects ¤  High level automation API to everything. ¤  Ignore at your own peril.
  • 29. Writing a PowerShell Module In IronPython: The “real” way to write Command-line tools? ¨  Create a New Visual Studio Project ¨  Thinks Objects ¨  Use PowerShell SDK ¨  Write a Binary Module
  • 30. Installing the PowerShell SDK ¤  Download the SDK ¤  Add a reference to the DLL in your Visual Studio Project ¤ C:ProgramFiles (x86)Reference AssembliesMicrosoftWindowsPowerShell v1.0System.Management.Automation
  • 31. Finding and Loading PowerShell Modules ¨  Get-Module –all ¨  When you create a .dll in IronPython, could then simply integrate it into the PowerShell workflow.
  • 32. What is a Binary Module? ¤  A .NET assembly compiled against PowerShell libraries. ¨  For IronPython folks, this is one way to integrate into PowerShell ¨  In a lot of documentation it will refer to C# code. ¨  You can also write a PowerShell, non-compiled, module.
  • 33. Creating a Binary Module For Powershell in IronPython ¤  http://stackoverflow.com/questions/2094694/launch- powershell-under-net-4 ¤  You need to tweak some registry settings to support .NET 4.0 in PowerShell.
  • 34. Creating a Binary Module For Powershell in IronPython: Continued ¤  Should follow C# example code for best implementation advice. ¤  Note, Argparse, Optparse, etc, aren’t used. They don’t make sense. ¤  These are objects being passed into other cmdlets, and methods are being called on those objects.
  • 35. IronPython PowerShell Module Hello World Visual Studio import  clr   Project: clr.AddReference('System.Management.Automation')   print  'Hello  World'   Step 1
  • 36. IronPython PowerShell Module Hello World Visual Studio ¨  Build the project to create a .dll Project: ¨  In PowerShell Import Module Step 2 ¨  Import-Module MyModule.dll ¨  You can know interact with it from inside of .Net. Is this a commandline tool???
  • 37. Setting Up A PowerShell Profile For IronPython ¨  Just like in Bash or ZSH, aliases are your friend. ¨  Edit your $profile with the ISE, and add interactive IronPython to it.
  • 38. Creating Standalone IronPython executables ¨  Make sure you can pass objects in and out of them. ¨  Use the IronPython on codeplex: Pyc-Python Command-line compiler
  • 39. F#: The Elephant in the Room ¤  Type inference ¤  Immutable data structures ¤  Run as script or compiled ¤  Tail recursion ¤  Fully integrated with Visual Studio ¤  Sexier then Python?
  • 40. F# and Python: A Sexy Beast ¤  Mixing .dll files written in F# into IronPython modules, loaded into Powershell. ¤  Calling IronPython/CPython from inside of F# ¤  “A statically typed Python…” (Note, this will come up..just preparing you…)
  • 41. Credit Some Excellent Books That Reference PowerShell ¤  PowerShell in Action, Manning (The Bible) ¤  PowerShell Cookbook, O’Reilly ¤  IronPython in Action, Manning
  • 42. Conclusion ¤  PowerShell isn’t a competing language, it IS THE ECOSYSTEM. ¤  Windows Systems Admins are using PowerShell for everything ¤  Get your head wrapped around object based pipelines. ¤  Why doesn’t Linux have this?
  • 43. Questions? Code: https://bitbucket.org/noahgift/pycon2011- ironpython-cli