SlideShare una empresa de Scribd logo
1 de 16
Scripting with Ruby
Stuart Palmer
RubyJax
13 June 2013
6/13/2013Scripting with Ruby
Why scripting?
 Perform regular tasks automatically
 Create daily reports, publish information, back up files, clear history
 Perform background tasks
 Send emails, share information with other systems
 Easily use operating system programs/utilities
 FTP, scp, mail, file storage
6/13/2013Scripting with Ruby
Traditional Scripting
 Shell scripts
 sh, bash, csh, ksh
 DOS batch files
 .bat
 SQL Jobs
 SQL scripts in database
6/13/2013Scripting with Ruby
Sample shell script
#!/bin/tcsh
#
# Expects one parameter in mm/dd/yyyy format
#
setenv TOP /opt/sp
setenv SBIN ${TOP}/sbin
setenv LOG ${TOP}/log
set logDir=${LOG}/trade­totals
#
# Convert mm/dd/yyyy to yyyymmdd
#
set yyyy=`echo $1 | cut ­c7­10`
set mm=`echo $1 | cut ­c1­2`
set dd=`echo $1 | cut ­c4­5`
set tradeDate=${yyyy}${mm}${dd}
set saveDir=${logDir}/${yyyy}
#
# Run the totals
#
fisql ­Uxxx ­Pxxx ­Ssss ­w140 > /tmp/total.out <<EOF
exec getTotals '$1'
go
quit
EOF
#
# See if there was any output
#
if ( ­z /tmp/total.out ) then
   rm ­f /tmp/total.out
   exit 0
endif
#
# Nice formatting
#
echo "" > /tmp/total.fax
echo "Totals for $1" >> /tmp/total.fax
echo "" >> /tmp/total.fax
#
# Get rid of isql junk
#
cat /tmp/total.out | grep ­v line1 | grep ­v '­­­' | grep ­v  
 "return stat" | egrep ­v ­e '^$' > /tmp/total.out1
#
# Get rid of tabs
#
sed ­e "s///" /tmp/total.out1 >> /tmp/total.fax
rm ­f /tmp/total.out /tmp/total.out1
#
# Send the file to the mail server for emailing
#
${SBIN}/email­to­finop.csh "Trade Totals for $1" /tmp/total.fax
#
# Save the file for prosperity
#
if ( ! ­d ${saveDir} ) then
    mkdir ${saveDir}
endif
mv ­f /tmp/total.fax ${saveDir}/total.${tradeDate}
6/13/2013Scripting with Ruby
What can Ruby do?
Ruby Standard Library
✔ Numbers and Math
✔ Strings
✔ Regular expressions
✔ Collections
✔ Dates and Times
✔ Files and Directories
✔ Networking
✔ Threads
6/13/2013Scripting with Ruby
My First Exposure to Ruby
require 'rubygems'
require 'roo'
require 'fileutils'
ss = Excel.new( "business_plan_cmbs.xls" )
ss.default_sheet = "Recommended"
puts ss.cell('B', 8)
'C'.upto('BJ') do |column|
  date      = ss.cell(2, column)
  monthnum  = ss.cell(3, column)
  yearnum   = ss.cell(4, column)
  
  interest  = ss.cell(8, column)
  amort     = ss.cell(9, column)
  other     = ss.cell(10, column)
  sum       = interest + amort + other
  puts "#{date} (#{monthnum}/#{yearnum})t#{sum}" 
end
6/13/2013Scripting with Ruby
Sending email
require 'net/smtp'
# Send email
Net::SMTP.start('mail.silveradosw.com', 25, 'www.silveradosw.com') do |smtp|
  smtp.open_message_stream('stuart@silveradosw.com', 'rubyjax@meetup.com') do |f|
    f.puts 'From: Stuart Palmer <stuart@silveradosw.com>'
    f.puts 'To: Ruby Jax <rubyjax@meetup.com>'
    f.puts "Date: #{DateTime.now.rfc2822}"
    f.puts 'Subject: Your Report for today'
    f.puts 'Message­ID: <ruby­1234@silveradosw.com>'
    lines.each do |line|
      f.puts line
    end
  end
end
6/13/2013Scripting with Ruby
File functions and FTP
require 'file'
require 'fileutils'
# Write to a file
report_file = File.new('/tmp/report­new', 'w')
lines.each do |line|
  report_file.puts line
end
report_file.close
FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report')
# FTP the file
ftp = Net::FTP.new('ftp.silveradosw.com')
ftp.login('stuart@silveradosw.com', 'xxx')
ftp.passive = true
ftp.chdir('Reports')
ftp.puttextfile('/tmp/report­new', 'todays_report')
ftp.close
6/13/2013Scripting with Ruby
File functions and FTP
require 'file'
require 'fileutils'
require 'net/ftp'
# Write to a file
report_file = File.new('/tmp/report­new', 'w')
lines.each do |line|
  report_file.puts line
end
report_file.close
FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report')
# FTP the file
ftp = Net::FTP.new('ftp.silveradosw.com')
ftp.login('stuart@silveradosw.com', 'xxx')
ftp.passive = true
ftp.chdir('Reports')
ftp.puttextfile('/tmp/report­new', 'todays_report')
ftp.close
6/13/2013Scripting with Ruby
Client / Server
require 'socket'
socket = TCPSocket.open('localhost', 3333)
socket.puts('hello')
socket.puts('what?')
socket.puts('done')
socket = TCPSocket.open('localhost', 3333)
socket.puts('quit')
require 'socket'
socket = TCPSocket.new('localhost', 3333)
done_listening = false
while !done_listening
  done_reading = false
  while !done_reading
    message = socket.read
    if message =~ /^quit$|^stop$/i
      puts "Received shutdown message."
      done_listening = true
      done_reading = true
    elsif message =~ /^done$/i
      puts "Received client end message."
      done_reading = true
    else
      puts "Read message: [#{message}]"
      socket.puts "OKn"
    end
  end
  socket.close
end
6/13/2013Scripting with Ruby
Threading
require 'thread'
done        = false
socket      = TCPServer.open(3333)
connections = Queue.new
processor   = Thread.new { process(connections, cfg) }
while !done
  # Block, waiting for a request
  client, client_sock_adr = socket.accept
  port, host, ipno = client.peeraddr[1..3]
  # Process the request
  begin
    message = client.readline
  rescue => ex
    client.close
    next
  end
  # Pass off the message and go wait for another one
  connections << OpenStruct.new(client: client, msg: message)
end
processor.join
socket.close
def process(connections, cfg)
  while !connections.empty?
    connection = connections.pop
    client = connection.get_client
    port, host, ipno = client.peeraddr[1..3]
    # Do stuff
  end
end
6/13/2013Scripting with Ruby
Database Access
require 'date'
require 'rubygems'
require 'dbi'
# Call database for data
dbhandle = DBI.connect("dbi:#{sss}", 'xxx', 'xxx')
rows = dbhandle.select_all("EXEC getTotals ?", 
ARGV[0])
if rows.nil? or rows.empty?
  puts "Nothing to report"
  exit
end
lines  = ['']
lines << "Your report for #{Date.today.to_s}"
lines << ''
rows.each do |row|
  lines << row['column_name']
end
6/13/2013Scripting with Ruby
Other Useful Modules
● Log files
require 'logger'
log = Logger.new(STDOUT)
log.level = Logger::WARN
log.debug( 'Created logger' )
log.info( 'Program started' )
log.warn( 'Nothing to do!' )
● Configuration files
config = File.open( 'report.yaml' ) { |yf| YAML::load( yf ) }
config = JSON.parse( IO.read( 'report.json' ) )
6/13/2013Scripting with Ruby
Gems
● XML Generation
✔ nokogiri
● PDF Generation
✔ prawn
● Events / Timers
✔ eventmachine
6/13/2013Scripting with Ruby
Test First
● The usual test frameworks can be used
➢ rspec, test::unit, minitest
C:UsersStuartClientswhbbiwhbbireports> rspec ­c ­fs trade­totals­email­spec.rb
TradeTotalsEmail
  initialize
    should call BaseEmail::new
    should call BaseEmail#from with name and email when set in config
  set_sender
    should call BaseEmail#from with name and email
  set_recipients
    should call add_recipients with passed­in name/email array
    should call add_recipients with config name/email
  set_default_recipients
    should call add_to with config name and email
  add_recipients
    should call add_to with each passed­in name and email
  add_to
    should call BaseEmail:to when non­null name and email passed in
Finished in 0.018 seconds
8 examples, 0 failures
6/13/2013Scripting with Ruby
exit(0)
Stuart Palmer
Silverado Consulting, Inc.
stuart@silveradosw.com
(408)529-6891

Más contenido relacionado

Destacado

oGIP national products
oGIP national productsoGIP national products
oGIP national productsAIESECGreece
 
עמותת והדרת
עמותת והדרתעמותת והדרת
עמותת והדרתAlfred Cohen
 
הסמכות מטפל
הסמכות מטפלהסמכות מטפל
הסמכות מטפלAlfred Cohen
 
DIABETIC FOOT. Dr.Ajit Kumar Varma
DIABETIC FOOT.   Dr.Ajit Kumar VarmaDIABETIC FOOT.   Dr.Ajit Kumar Varma
DIABETIC FOOT. Dr.Ajit Kumar VarmaDr.Ajit Kumar Varma
 
Prepare to Preach (Session 1)
Prepare to Preach (Session 1)Prepare to Preach (Session 1)
Prepare to Preach (Session 1)Bong Baylon
 
Sales Presentation
Sales PresentationSales Presentation
Sales PresentationAIESECGreece
 
Business leadership: How to be a good leader?
Business leadership: How to be a good leader?Business leadership: How to be a good leader?
Business leadership: How to be a good leader?David Kiger
 
Solutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer ExpectationsSolutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer ExpectationsAndrew Vidor
 
Prepare to preach (ses 1)
Prepare to preach (ses 1)Prepare to preach (ses 1)
Prepare to preach (ses 1)Bong Baylon
 
Automatic water level controller
Automatic water level controllerAutomatic water level controller
Automatic water level controllerGeetha Smiley
 
Corporate Etiquette
Corporate EtiquetteCorporate Etiquette
Corporate EtiquetteAshit Jain
 
How to Create Engaging Data-driven stories
How to Create Engaging Data-driven storiesHow to Create Engaging Data-driven stories
How to Create Engaging Data-driven storiesBuzzSumo
 

Destacado (13)

oGIP national products
oGIP national productsoGIP national products
oGIP national products
 
עמותת והדרת
עמותת והדרתעמותת והדרת
עמותת והדרת
 
הסמכות מטפל
הסמכות מטפלהסמכות מטפל
הסמכות מטפל
 
DIABETIC FOOT. Dr.Ajit Kumar Varma
DIABETIC FOOT.   Dr.Ajit Kumar VarmaDIABETIC FOOT.   Dr.Ajit Kumar Varma
DIABETIC FOOT. Dr.Ajit Kumar Varma
 
Prepare to Preach (Session 1)
Prepare to Preach (Session 1)Prepare to Preach (Session 1)
Prepare to Preach (Session 1)
 
Sales Presentation
Sales PresentationSales Presentation
Sales Presentation
 
9 Step Business Sales Process
9 Step Business Sales Process9 Step Business Sales Process
9 Step Business Sales Process
 
Business leadership: How to be a good leader?
Business leadership: How to be a good leader?Business leadership: How to be a good leader?
Business leadership: How to be a good leader?
 
Solutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer ExpectationsSolutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer Expectations
 
Prepare to preach (ses 1)
Prepare to preach (ses 1)Prepare to preach (ses 1)
Prepare to preach (ses 1)
 
Automatic water level controller
Automatic water level controllerAutomatic water level controller
Automatic water level controller
 
Corporate Etiquette
Corporate EtiquetteCorporate Etiquette
Corporate Etiquette
 
How to Create Engaging Data-driven stories
How to Create Engaging Data-driven storiesHow to Create Engaging Data-driven stories
How to Create Engaging Data-driven stories
 

Similar a Ruby Scripting

Leveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN PerformanceLeveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN Performancebrettallison
 
Chef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureChef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureMichaël Lopez
 
Logging in dockerized environment
Logging in dockerized environmentLogging in dockerized environment
Logging in dockerized environmentYury Bushmelev
 
Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!mold
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryMike Lively
 
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube GoldbergReplacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube GoldbergDanny Bryant
 
Towards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev MachineTowards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev MachineKrimson
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날Sukjoon Kim
 
Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4N Masahiro
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core ModuleKatie Gulley
 
Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Robert Treat
 
EG Reports - Delicious Data
EG Reports - Delicious DataEG Reports - Delicious Data
EG Reports - Delicious DataBenjamin Shum
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!cloudbring
 
Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)jimyhuang
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderSadayuki Furuhashi
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindSam Keen
 
2010 Smith Scripting101
2010 Smith Scripting1012010 Smith Scripting101
2010 Smith Scripting101bokonen
 

Similar a Ruby Scripting (20)

Leveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN PerformanceLeveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN Performance
 
Chef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureChef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructure
 
Logging in dockerized environment
Logging in dockerized environmentLogging in dockerized environment
Logging in dockerized environment
 
Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella Story
 
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube GoldbergReplacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
 
PHP 5 Sucks. PHP 5 Rocks.
PHP 5 Sucks. PHP 5 Rocks.PHP 5 Sucks. PHP 5 Rocks.
PHP 5 Sucks. PHP 5 Rocks.
 
Towards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev MachineTowards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev Machine
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
 
Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008
 
EG Reports - Delicious Data
EG Reports - Delicious DataEG Reports - Delicious Data
EG Reports - Delicious Data
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Project Automation
Project AutomationProject Automation
Project Automation
 
Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loader
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
2010 Smith Scripting101
2010 Smith Scripting1012010 Smith Scripting101
2010 Smith Scripting101
 

Último

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Ruby Scripting

  • 1. Scripting with Ruby Stuart Palmer RubyJax 13 June 2013
  • 2. 6/13/2013Scripting with Ruby Why scripting?  Perform regular tasks automatically  Create daily reports, publish information, back up files, clear history  Perform background tasks  Send emails, share information with other systems  Easily use operating system programs/utilities  FTP, scp, mail, file storage
  • 3. 6/13/2013Scripting with Ruby Traditional Scripting  Shell scripts  sh, bash, csh, ksh  DOS batch files  .bat  SQL Jobs  SQL scripts in database
  • 4. 6/13/2013Scripting with Ruby Sample shell script #!/bin/tcsh # # Expects one parameter in mm/dd/yyyy format # setenv TOP /opt/sp setenv SBIN ${TOP}/sbin setenv LOG ${TOP}/log set logDir=${LOG}/trade­totals # # Convert mm/dd/yyyy to yyyymmdd # set yyyy=`echo $1 | cut ­c7­10` set mm=`echo $1 | cut ­c1­2` set dd=`echo $1 | cut ­c4­5` set tradeDate=${yyyy}${mm}${dd} set saveDir=${logDir}/${yyyy} # # Run the totals # fisql ­Uxxx ­Pxxx ­Ssss ­w140 > /tmp/total.out <<EOF exec getTotals '$1' go quit EOF # # See if there was any output # if ( ­z /tmp/total.out ) then    rm ­f /tmp/total.out    exit 0 endif # # Nice formatting # echo "" > /tmp/total.fax echo "Totals for $1" >> /tmp/total.fax echo "" >> /tmp/total.fax # # Get rid of isql junk # cat /tmp/total.out | grep ­v line1 | grep ­v '­­­' | grep ­v    "return stat" | egrep ­v ­e '^$' > /tmp/total.out1 # # Get rid of tabs # sed ­e "s///" /tmp/total.out1 >> /tmp/total.fax rm ­f /tmp/total.out /tmp/total.out1 # # Send the file to the mail server for emailing # ${SBIN}/email­to­finop.csh "Trade Totals for $1" /tmp/total.fax # # Save the file for prosperity # if ( ! ­d ${saveDir} ) then     mkdir ${saveDir} endif mv ­f /tmp/total.fax ${saveDir}/total.${tradeDate}
  • 5. 6/13/2013Scripting with Ruby What can Ruby do? Ruby Standard Library ✔ Numbers and Math ✔ Strings ✔ Regular expressions ✔ Collections ✔ Dates and Times ✔ Files and Directories ✔ Networking ✔ Threads
  • 6. 6/13/2013Scripting with Ruby My First Exposure to Ruby require 'rubygems' require 'roo' require 'fileutils' ss = Excel.new( "business_plan_cmbs.xls" ) ss.default_sheet = "Recommended" puts ss.cell('B', 8) 'C'.upto('BJ') do |column|   date      = ss.cell(2, column)   monthnum  = ss.cell(3, column)   yearnum   = ss.cell(4, column)      interest  = ss.cell(8, column)   amort     = ss.cell(9, column)   other     = ss.cell(10, column)   sum       = interest + amort + other   puts "#{date} (#{monthnum}/#{yearnum})t#{sum}"  end
  • 7. 6/13/2013Scripting with Ruby Sending email require 'net/smtp' # Send email Net::SMTP.start('mail.silveradosw.com', 25, 'www.silveradosw.com') do |smtp|   smtp.open_message_stream('stuart@silveradosw.com', 'rubyjax@meetup.com') do |f|     f.puts 'From: Stuart Palmer <stuart@silveradosw.com>'     f.puts 'To: Ruby Jax <rubyjax@meetup.com>'     f.puts "Date: #{DateTime.now.rfc2822}"     f.puts 'Subject: Your Report for today'     f.puts 'Message­ID: <ruby­1234@silveradosw.com>'     lines.each do |line|       f.puts line     end   end end
  • 8. 6/13/2013Scripting with Ruby File functions and FTP require 'file' require 'fileutils' # Write to a file report_file = File.new('/tmp/report­new', 'w') lines.each do |line|   report_file.puts line end report_file.close FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report') # FTP the file ftp = Net::FTP.new('ftp.silveradosw.com') ftp.login('stuart@silveradosw.com', 'xxx') ftp.passive = true ftp.chdir('Reports') ftp.puttextfile('/tmp/report­new', 'todays_report') ftp.close
  • 9. 6/13/2013Scripting with Ruby File functions and FTP require 'file' require 'fileutils' require 'net/ftp' # Write to a file report_file = File.new('/tmp/report­new', 'w') lines.each do |line|   report_file.puts line end report_file.close FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report') # FTP the file ftp = Net::FTP.new('ftp.silveradosw.com') ftp.login('stuart@silveradosw.com', 'xxx') ftp.passive = true ftp.chdir('Reports') ftp.puttextfile('/tmp/report­new', 'todays_report') ftp.close
  • 10. 6/13/2013Scripting with Ruby Client / Server require 'socket' socket = TCPSocket.open('localhost', 3333) socket.puts('hello') socket.puts('what?') socket.puts('done') socket = TCPSocket.open('localhost', 3333) socket.puts('quit') require 'socket' socket = TCPSocket.new('localhost', 3333) done_listening = false while !done_listening   done_reading = false   while !done_reading     message = socket.read     if message =~ /^quit$|^stop$/i       puts "Received shutdown message."       done_listening = true       done_reading = true     elsif message =~ /^done$/i       puts "Received client end message."       done_reading = true     else       puts "Read message: [#{message}]"       socket.puts "OKn"     end   end   socket.close end
  • 11. 6/13/2013Scripting with Ruby Threading require 'thread' done        = false socket      = TCPServer.open(3333) connections = Queue.new processor   = Thread.new { process(connections, cfg) } while !done   # Block, waiting for a request   client, client_sock_adr = socket.accept   port, host, ipno = client.peeraddr[1..3]   # Process the request   begin     message = client.readline   rescue => ex     client.close     next   end   # Pass off the message and go wait for another one   connections << OpenStruct.new(client: client, msg: message) end processor.join socket.close def process(connections, cfg)   while !connections.empty?     connection = connections.pop     client = connection.get_client     port, host, ipno = client.peeraddr[1..3]     # Do stuff   end end
  • 12. 6/13/2013Scripting with Ruby Database Access require 'date' require 'rubygems' require 'dbi' # Call database for data dbhandle = DBI.connect("dbi:#{sss}", 'xxx', 'xxx') rows = dbhandle.select_all("EXEC getTotals ?",  ARGV[0]) if rows.nil? or rows.empty?   puts "Nothing to report"   exit end lines  = [''] lines << "Your report for #{Date.today.to_s}" lines << '' rows.each do |row|   lines << row['column_name'] end
  • 13. 6/13/2013Scripting with Ruby Other Useful Modules ● Log files require 'logger' log = Logger.new(STDOUT) log.level = Logger::WARN log.debug( 'Created logger' ) log.info( 'Program started' ) log.warn( 'Nothing to do!' ) ● Configuration files config = File.open( 'report.yaml' ) { |yf| YAML::load( yf ) } config = JSON.parse( IO.read( 'report.json' ) )
  • 14. 6/13/2013Scripting with Ruby Gems ● XML Generation ✔ nokogiri ● PDF Generation ✔ prawn ● Events / Timers ✔ eventmachine
  • 15. 6/13/2013Scripting with Ruby Test First ● The usual test frameworks can be used ➢ rspec, test::unit, minitest C:UsersStuartClientswhbbiwhbbireports> rspec ­c ­fs trade­totals­email­spec.rb TradeTotalsEmail   initialize     should call BaseEmail::new     should call BaseEmail#from with name and email when set in config   set_sender     should call BaseEmail#from with name and email   set_recipients     should call add_recipients with passed­in name/email array     should call add_recipients with config name/email   set_default_recipients     should call add_to with config name and email   add_recipients     should call add_to with each passed­in name and email   add_to     should call BaseEmail:to when non­null name and email passed in Finished in 0.018 seconds 8 examples, 0 failures
  • 16. 6/13/2013Scripting with Ruby exit(0) Stuart Palmer Silverado Consulting, Inc. stuart@silveradosw.com (408)529-6891