Skip to content

Ruby cheatsheet

Scan ports

[80, 443, 8080].each {|p| TCPSocket.new('127.0.0.1', p).close.nil? && puts("open") rescue puts 'closed' }

Example Sinatra application

require 'sinatra'

set :port, 8899
set :bind, '0.0.0.0'

get '/' do
  'Hello world!'
end

Send HTTP request

#!/usr/bin/ruby
require "openssl"
require "cgi"
require "net/http"
require "uri"

unless ARGV[0]
  puts "Usage: ./script.rb <hostname>"
  puts ""
  puts "Example: ./script.rb example.org"
  exit 1
end

hostname = ARGV[0]

http = Net::HTTP.new(hostname, 4567)
  http.use_ssl = false
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new("/")

while res = http.request(request)
  case res
  when Net::HTTPRedirection then
    puts "  => Following redirect to #{res["location"]}..."
    request = Net::HTTP::Get.new(res["location"])
  else
    break
  end
end

if res.code == "200"
  puts "  => Request executed."
  else
  puts "  => Something went wrong."
end

Send email

#!/usr/bin/env ruby

require 'net/smtp'

to = ""
from = ""
smtp_host = ""
smtp_user = ""
smtp_pass = ""

msg = <<MESSAGE_END
From: <#{from}>
To: <#{to}>
Subject: email test

Test email

MESSAGE_END

smtp = Net::SMTP.new smtp_host, 587
smtp.enable_starttls
smtp.start(smtp_host, smtp_user, smtp_pass, :login) do
  smtp.send_message(msg, from, to)
end