Share E-Book

Wicked cool Ruby scripts useful scripts that solve difficult problems (Steve Pugh) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Rating 3.5 AI initial rating

Log in to rate

Programming Language
Language English

Wicked Cool Ruby Scripts is a compendium of scripts that will make your life easier by saving you time and solving problems. If you find yourself wasting effort and time on a task a trained monkey could do, it's time for Ruby to come to the rescue. Wicked Cool Ruby Scripts provides carefully selected Ruby scripts that are immediately useful. Learn how to streamline administrative tasks like renaming files, disabling processes, and changing permissions. After you get your feet wet creating basic scripts, author Steve Pugh will show you how to create powerful Web crawlers, security scripts, full-fledged libraries and applications, and much more. With each script you'll get the raw code followed by an explanation of how it really works, as well as instructions for how to run the script and suggestions for customizing it. Wicked Cool Ruby Scripts will save you from the tedium of repetitive tasks and give you back the time it would take to write scripts from scratch.

Format PDF
Size 1.8 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
FOREWORD One of the great joys of using Ruby is that the language is engineered to make for easy and effective procedural, script-style programming. Wicked Cool Ruby Scripts, as its title suggests, shines the spotlight on the scripting side of Ruby. It's nice to see attention going in this direction. People often describe Ruby as a "scripting language," but that misses the point. Ruby is a general-purpose, object-oriented programming language that happens to offer a rich syntactic toolkit for scripting. I won't try to define the latter rigorously, but it has something to do with a procedural approach and with an acknowledgment of the fact that short programs that don't spin off library modules can be okay too. I believe that this kind of programming is one of Ruby's sweet spots, precisely because the value of allowing for it was not an afterthought in the design of the language. Steve Pugh has been on a journey through a varied, many-faceted landscape of scripting tasks and solutions, and he has parlayed that journey into an engaging, illustrative, instructive travelogue. He's got us encrypting files, parsing RSS feeds, adding users to our systems, developing network exploits (but on the side of the good guys), scraping images, making phone calls, quicksorting arrays, solving Sudoku puzzles, and plenty more. Steve's delight in Ruby's versatility is contagious; when I look at Wicked Cool Ruby Scripts, I'm reminded of the power of the "Wow!" factor in Ruby and of Matz's dictum that Ruby is optimized for programmer pleasure and fun. Writing scripts is, moreover, an extraordinarily useful form of fun. So enjoy this book. You'll learn a lot of Ruby, find lots of techniques to borrow and tweak, probably get a lesson in an algorithm or two that you're rusty on—and have a chance to delve into one of the strongest areas for this wonderful language. David A. Black Director, Ruby Power and Light, LLC North Brunswick, New Jersey November 2008 Page 1 s
Page 3
ACKNOWLEDGMENTS First and foremost, I would like to thank my family, who supported me during the authoring of this book. I definitely wouldn't have finished it if not for their patience and support. My wonderful wife, Shannon, who puts up with me being a nerd, gave valuable insight into the English language. It turns out that I'm better at writing code than English sentences…the spellcheckers can only take me so far. I would be remiss if I did not thank the man who introduced me to Ruby—Lim Vu. Without his guidance and friendship, I doubt I would be involved in Ruby today. I still remember our conversations about Ruby when I'd pick his brain to find out more about this new language. I also have to thank David Black for constantly answering my questions, giving solid advice, offering honest critiques, and challenging the syntactical slip-ups that are inherent to writing code in many different languages. Some of my scripts originally looked more like Perl than Ruby, so many thanks to David for keeping me accountable and giving wonderful guidance. The guy truly has the heart of a teacher. Finally, I would like to thank the entire team of people at No Starch Press for publishing this book on Ruby. Bill Pollock has put together a remarkable group of people who make authoring a book a wonderful experience. Thanks to Tyler Ortman, who put up with my random phone calls, questions, and ideas, while still managing to keep the book on point and readable. His gentle words of encouragement and motivation were great. Finally, I owe Megan Dunchak many thanks for putting the copyediting phase on auto-pilot. If it weren't for all of the people above, I wouldn't be writing these acknowledgments, and you wouldn't be reading them. Page 2 s
Page 4
INTRODUCTION So you've read a few introductory books about Ruby, you have a good feel for the syntax, and you've written "Hello, world!" about 20 different optimized ways—now what? This book is intended to give your mind an exercise in Ruby as a scripting language. Scripting—that is, automating repetitive tasks you're not prepared to do yourself—is one of those things that a good language must be able to do. Perl and Python are two of the most widely known scripting languages, and their popularity has a direct correlation to their usefulness for scripting. Writing utilities should not be a cryptic task, nor should scripts take an inordinate amount of time to create. It is in that spirit that Ruby was born. The designer of Ruby, Yukihiro "Matz" Matsumoto, had an overall vision to create a language that would be easy to use in everyday tasks. He felt the language should be fun to write so that more energy could be put toward creative processes with less stress. When they aren't distracted by the peculiarities of a language, programmers can focus on writing better programs. When you need to write a script, the last thing you want to worry about is weird syntax and compilers interpreting your code. Ruby is written in such a way that the syntax and programming flow is natural. I have found Ruby to be comfortable to work with because of its natural syntax, wonderful community, and simplistic view of how programming should be. As you will see throughout this book, Ruby makes scripting a breeze! A command of scripting in Ruby is an invaluable skill to have. You will find that by automating repetitive tasks, you will free up much of your time to do more important things… like writing other wicked cool Ruby scripts. I hope this book helps you see the many uses of Ruby and makes you a better programmer. Page 3 s
Page 5
Wicked Cool Ruby Scripts What differentiates a wicked cool Ruby script from an ordinary script? A wicked cool script is something that is useful, challenging, and, above all, educational. Not educational in the schoolmarm sense of the word, but rather as a stimulus to use Ruby to its full potential—to push the language to its limits. Page 4 s
Page 6
You Need Ruby Basics I won't be focusing my energy on teaching you the basics of Ruby—this book is not intended for someone looking to learn Ruby 101. Sure, you can use the scripts and see potential applications of Ruby without being proficient in it. But to get the full benefit from the information presented, I assume you are familiar with Ruby and do not need the simpler features of the language explained. I will briefly walk through each script and highlight only the most important parts. Page 5 s
Page 7
Documentation You will notice slight differences between the code in the book and the source code available for download at http://www.nostarch.com/wcruby.htm/. Most of the comments and documentation have been taken out of the source code in the book for brevity's sake. Some of the scripts have more detailed explanations if I felt clarity was needed. I highly encourage commenting your own code so you and other people can understand how it works. Note When I began programming, I spent several hours reviewing code I had previously written to figure out how it worked. After a few rounds of studying code without comments, I learned an important lesson—comment your code while it's fresh in your mind. The amount of commenting is up to you, but it is definitely a good coding habit to get into. Page 6 s
Page 8
Organization and Approach For each of the scripts, I'll walk you through the logic and usage, then through the underlying principles involved in writing the script. Finally, I'll put you in the driver's seat and suggest some ways you can hack the script to make it your own and more versatile. These scripts are not going to solve every need you have, but my hope is that they will help you think about how you can write your own scripts—learning through example. Feel free to download the scripts and use them however you want to. Chapter 1: General Purpose Utilities Ruby is an ideal language for creating small, everyday scripts. This chapter includes helpful utilities for simple tasks like encrypting and decrypting files, splitting and joining files, compressing and decompressing files, tracking file changes, viewing a complete list of running processes, and calculating your mortgage payments. Chapter 2: Website Scripting Ruby and the Web go together like a horse and carriage. If you're familiar with Ruby, then you have probably heard of Rails, the web framework that drives much of Ruby's adoption. This chapter contains scripts that make website administration, RSS parsing, and web form generation easier. You can also use the scripts in this chapter for quality assurance testing, since they'll test for broken hyperlinks and orphan files. Chapter 3: Li(U)nix System Administration Systems administration can be made much easier through the use of scripting, and Ruby is an ideal language for automating mundane system administration tasks. This chapter includes scripts for administering users as well as detecting and killing process hogs on your devices. Automation of system administration tasks is one of the major uses of scripting, and it's also an area with the most room for creativity. Chapter 4: Picture Utilities Digital photography has become the new way to capture and share memories, whether it's through the Web, email, or physical media. One problem I've run into, though, is that the amount of photographs I take becomes overwhelming. I can't do the things I used to enjoy, like organizing, touching-up, or sharing photos with people, because there are too many images, and I don't have enough time to go through them all. This chapter will show you ways to automate the tedious task of resizing, renaming, and organizing your digital photographs. I will also show you how to protect your creative works by watermarking your photos. For readers who like to analyze picture information, this chapter also demonstrates how to extract the information stored in the metadata. Chapter 5: Games and Learning Tools This chapter shows some simple games that can be developed using Ruby. Have you caught on to the Sudoku craze? The Sudoku solver will solve a puzzle in less time than it will take for you to enter the numbers. What about an interactive Rock, Paper, Scissors opponent? I will show you several other entertaining scripts and explain them so you can make your own games and entertain your friends. Chapter 6: String Utilities Ruby's text manipulation and processing utilities are powerful. This chapter will dive into parsing comma-separated value (CSV) files, generating and manipulating documents, and searching for a specific string within documents. Chapter 7: Servers and Scrapers There is a lot of information floating around the ether of the Internet. This chapter shows you ways to extract that information and put it into easy-to-use formats. For example, you can grab all the pictures off of a website and save them to a specified folder with a specific naming convention. You'll learn how to automate your web browser to navigate websites, complete Page 7 s
Page 9
forms, and otherwise act like a typical user. And I'll show you how to automatically send SMS messages to your friends using a Ruby script. Chapter 8: Arguments and Documentation After reading through this book, you'll have a good understanding of using Ruby in the wild. This chapter will show you how to polish and put the finishing touches on your wicked cool scripts. You'll be able to write your own professional scripts in no time! Chapter 9: Sorting Algorithms This chapter is a collection of sorting algorithms that are popular in academia and are otherwise nice to know about. The algorithms are analyzed and tested using the Unit:Test library to show differences in performance and efficiency. Since any given problem has a myriad of solutions, having multiple options available will increase your chances of choosing the most fitting answer. You can use the Unit:Test library to discover which methods are the most efficient and effective. Chapter 10: Writing a Metasploit 3.1 Module with Ruby Computer security is a rapidly growing field, and Metasploit is one tool available for security research. This chapter combines two of my favorite subjects and shows you how to write an exploit using Ruby and Metasploit. We will walk through how to write a custom exploit, step by step. Page 8 s
Page 10
The Website The official website for the book is http://www.nostarch.com/wcruby.htm/. Here, you will be able to download every script from this book as well as get current information about changes and updates. You'll also find the errata page, which will contain any needed corrections (be sure to check this page if you get stuck). Page 9 s
Page 11
Chapter 1. GENERAL PURPOSE UTILITIES In any programming language, scripting is the solution to frequently performed tasks. If you find yourself asking Couldn't a robot or well-trained monkey do this job?, then scripting with Ruby just might be the next best solution. Writing scripts for frequently performed tasks makes your job and computing experience as efficient as it can be. Who wouldn't want to get the job done in less time with less effort? As you work through these examples, I encourage you to write down ideas for your own scripts. Once you've finished this book, you will probably have a list of scripts you want to write, or at the very least, some useful revisions of mine. Are you ready? Let's get started! Page 10 s
Page 12
Check for Changed Files Page 11 s
Page 13
Check for Changed Files changedFiles.rb The purpose of this script is to validate a file's integrity. While it sounds like a humble end use, its applications are broad: If you can't trust the contents of files on your computer, you can't trust your computer. Would you know if a malicious worm or virus modified a file on your system? If you think your antivirus has you covered, think again—most only go as far as checking for known viruses and their signatures. File integrity validation is used every day for real-world tasks such as digital forensics and tracking the behavior of malicious logic. One method of tracking file integrity is shown below. Page 12 s
Page 14
The Code require 'find' require 'digest/md5' unless ARGV[0] and File.directory?(ARGV[0]) puts "\n\n\nYou need to specify a root directory: changedFiles.rb <directory>\n\n\n" exit end root = ARGV[0] oldfile_hash = Hash.new newfile_hash = Hash.new file_report = "#{root}/analysis_report.txt" file_output = "#{root}/file_list.txt" oldfile_output = "#{root}/file_list.old" if File.exists?(file_output) File.rename(file_output, oldfile_output) File.open(oldfile_output, 'rb') do |infile| while (temp = infile.gets) line = /(.+)\s{5,5}(\w{32,32})/.match(temp) puts "#{line[1]} ---> #{line[2]}" oldfile_hash[line[1]] = line[2] end end end Find.find(root) do |file| next if /^\./.match(file) next unless File.file?(file) begin newfile_hash[file] = Digest::MD5.hexdigest(File.read(file)) rescue puts "Error reading #{file} --- MD5 hash not computed." end end report = File.new(file_report, 'wb') changed_files = File.new(file_output, 'wb') newfile_hash.each do |file, md5| changed_files.puts "#{file} #{md5}" end newfile_hash.keys.select { |file| newfile_hash[file] == oldfile_hash[file] }.each do |file| newfile_hash.delete(file) oldfile_hash.delete(file) end newfile_hash.each do |file, md5| report.puts "#{oldfile_hash[file] ? "Changed" : "Added"} file: #{file} #{md5}" oldfile_hash.delete(file) end Page 13 s
Page 15
oldfile_hash.each do |file, md5| report.puts "Deleted/Moved file: #{file} #{md5}" end report.close changed_files.close Page 14 s
Page 16
Running the Code Execute this script by typing: ruby changedFiles.rb /path/to/check/ You can add more than one directory to crawl, but subdirectories will automatically be verified. The script will automatically determine if a directory exists and then add it to the crawler's queue. Page 15 s
Page 17
The Results The script will initially produce two separate files (changed.files and file_report.txt). Both will contain a list of the names and MD5 hashes for all of the files scanned by the script: Added file: fileSplit.rb d79c592af618266188a9a49f91fe0453 Added file: fileJoin.rb 5aedfe682e300dcc164ebbdebdcd8875 Added file: win32RegCheck.rb c0d26b249709cd91a0c8c14b65304aa7 Added file: changedFiles.rb c2760bfe406a6d88e04f8969b4287b4c Added file: encrypt.rb 08caf04913b4a6d1f8a671ea28b86ed2 Added file: decrypt.rb 90f68b4f65bb9e9a279cd78b182949d4 Added file: file_report.txt d41d8cd98f00b204e9800998ecf8427e Added file: changed.files d41d8cd98f00b204e9800998ecf8427e Added file: test.txt a0cbe4bbf691bbb2a943f8d898c1b242 Added file: test.txt.rsplit1 35d5b2e522160ce3b3b98d2d4ad2a86e Added file: test.txt.rsplit2 a65dde64f16a4441ff1619e734207528 Added file: test.txt.rsplit3 264b40b40103a4a3d82a40f82201a186 Added file: test.txt.rsplit4 943600762a52864780b9b9f0614a470a Added file: test.txt.rsplit5 131c8aa7155483e7d7a999bf6e2e21c0 Added file: test.txt.rsplit6 1ce31f6fbeb01cbed6c579be2608e56c After the script is run a second time, three files will appear in the root directory. Two of the files, changed.files and old_changed.files, are where the MD5 hashes are stored; the third, file_report.txt , is a text file showing the results. The script will compare the MD5 hashes for all of the files listed in changed.files with those in old_changed.files and return any differences found. Here is an example: Changed file: old_changed.files 45de547aef9366eeaeb1b565dff1e1a3 Deleted/Moved file: test.txt.rsplit4 943600762a52864780b9b9f0614a470a Deleted/Moved file: test.txt.rsplit5 131c8aa7155483e7d7a999bf6e2e21c0 Deleted/Moved file: test.txt.rsplit6 1ce31f6fbeb01cbed6c579be2608e56c Deleted/Moved file: test.txt.rsplit1 35d5b2e522160ce3b3b98d2d4ad2a86e Deleted/Moved file: test.txt.rsplit2 a65dde64f16a4441ff1619e734207528 Deleted/Moved file: test.txt.rsplit3 264b40b40103a4a3d82a40f82201a186 Page 16 s
Page 18
How It Works This script is great for verifying the contents of your hard drive and ensuring they haven't been manipulated. The script starts by confirming that the user-supplied arguments were included and that a valid directory was given. Next is the initialization of variables used in the script. The root variable contains the root directory to scan, two hashes are created that will be used for comparing the files and their MD5 hashes, and, finally, the names of the files to be used are specified . The script output is saved in two or three files, depending on whether the script has been run before. The main file, file_report.txt, is used for reading the output, and the other two files are used to store the list of MD5 hashes. Next, the script checks to see if it's been run before by looking for file_list.txt . If the file is not found, the script moves on. If it finds file_list.txt, the script immediately renames the file. The renamed file is then opened and the contents are read. For every line in the file, the script reads a filename and MD5 hash and stores these in the oldfile_hash for later comparison. Once the oldfile_hash has been populated, the script is ready to begin computing new MD5 hashes and comparing results. As the script works its way through the directory tree, it will iterate through each object . The Find.find method is a powerful recursive way to retrieve files in a directory and subdirectories. The code block will be run on every file found. The first statement is looking for the "." and ".."—which are skipped for obvious reasons. If the object is a directory, the script will give it the skip treatment and press on. If the item is a file, the hash is generated and stored for later use. The hashing process is surrounded by a begin/rescue block to save us if something goes terribly wrong. The bulk of the information gathering is now complete. All that is left is to determine the status of each file. If a file has the same name and MD5 hash, it is unchanged and the script will remove the filename from the output hash. There are three categories that a file can fit into aside from Unchanged. The first is Deleted or Moved, which is determined by a file's presence in the past scan but not the current one . Next is the Changed category. If the filename exists and the MD5 hash is not the same as in the previous scans, the file has been changed . At this point, for the sake of readability in the code, I used the ternary operator, which is an abbreviation of the if/then/else statement. So, this says if the file exists in oldfile_hash, then label it Changed, else label it Added; since the filename doesn't exist previously, it has been added since the last scan . All of the data is saved, and a report is generated so the user is aware of each file's status. If anything is out of the ordinary, further analysis is required. There are several software packages that perform similar computations for security purposes, but the method above is a nice alternative, and the price is right, too. For enhanced security, you can store the output files on a separate medium, but I generally leave them in the top-level directory for simplicity's sake. Page 17 s
Page 19
Hacking the Script This script can be modified to use any number of hashing algorithms. I chose MD5 because it is the most popular for checking a file's integrity (even though its hashes are vulnerable to a collision attack). This script works on both Microsoft Windows and Unix-like systems. Cross platform scripts are always a plus! Other potential changes to the script include encrypting the hashed files for added protection or interfacing the results into a database. The script has many potential uses, and I'll leave it to you to investigate further. If you are curious about encryption, check out the next script. Page 18 s
Page 20
Encrypt a File Page 19 s
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List