2009年3月6日星期五

用脚本控制Tor更换IP

不多说,直接看代码吧,虽然我觉得用得上这个脚本的地方都很无聊。

require 'net/telnet'
require 'net/http'
require 'uri'
require 'time'

def torNewIP()
  tor_addr = '127.0.0.1'
  tor_ctrl = 9051
  
  host = Net::Telnet.new(
    'Host' => tor_addr,
    'Port' => tor_ctrl,
    'Prompt' => /\n/n)
  r = host.cmd('AUTHENTICATE')
  return false if r != "250 OK\n"
  r = host.cmd('signal NEWNYM')
  return false if r != "250 OK\n"
  return true
end

def doLoop(url, proxy_addr, proxy_port, sleeptime)
  n = 0
  uri = URI.parse(url)
  while true
    req = Net::HTTP::Get.new(uri.request_uri)
    req['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0)'
    req['Referer'] = 'http://otnth.blogspot.com'
    
    http = Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port)
    res = http.request(req)
    n += 1
    yield(n, res)
    torNewIP
    sleep(sleeptime)
  end
end

url = 'http://otnth.blogspot.com'

proxy_addr = '127.0.0.1'
proxy_port = 8118

sec = 10

doLoop(url, proxy_addr, proxy_port, sec) do |n, res|
  puts "#{Time.now.iso8601.to_s} #{n}: #{res.code} #{res.msg}"
end

没有评论 :