#Ruby의 Faraday는 ssh+SOCKS를 통해 https proxy 연결을 할 수 없기 때문에faradayadapter_socksgem으로 Middleware 지정

5577 단어 Ruby

SOCKS 시작

ssh -vND 8888  user@host

gem install

gem install faraday
gem install faraday_adapter_socks

Ruby or pry


환경 변수에 socks URL 지정하기
https_proxy=socks://127.0.0.1:8888 ruby some.rb
https_proxy=socks://127.0.0.1:8888 pry

Ruby Code


adapter 요청 get 지정하기
Faraday.new(url: 'https://httpbin.org/ip') { |conn| conn.adapter :net_http_socks }.get.body
e.g result
IP 주소 반환 서비스에 요청
ssh 서버의 IP 주소가 반환된 경우
[8] pry(main)> Faraday.new(url: 'https://httpbin.org/ip') { |conn| conn.adapter :net_http_socks }.get.body
=> "{\n  \"origin\": \"YYY.YYY.YYY.YYY, YYY.YYY.YYY.YYY\"\n}\n"

어댑터가 지정되지 않은 경우


이런 오류가 발생했습니다.
[10] pry(main)> Faraday.new(url: 'https://httpbin.org/ip').get.body
Faraday::ConnectionFailed: end of file reached
from /usr/local/lib/ruby/2.5.0/net/protocol.rb:189:in `rbuf_fill'
Caused by EOFError: end of file reached
from /usr/local/lib/ruby/2.5.0/net/protocol.rb:189:in `rbuf_fill'

Grete gem "faraday_adapter_socks" !


thank you
module Faraday
  class Adapter < Middleware

    register_middleware net_http_socks: :NetHttpSocks

    class NetHttpSocks < Faraday::Adapter::NetHttp

      SOCKS_SCHEMES = ['socks', 'socks4', 'socks5']

      def net_http_connection(env)
        proxy = env[:request][:proxy]

        net_http_class = if proxy
          if SOCKS_SCHEMES.include?(proxy[:uri].scheme)
            Net::HTTP::SOCKSProxy(proxy[:uri].host, proxy[:uri].port)
          else
            Net::HTTP::Proxy(proxy[:uri].host, proxy[:uri].port, proxy[:user], proxy[:password])
          end
        else
          Net::HTTP
        end

        net_http_class.new(env[:url].host, env[:url].port)
      end
    end
  end
end

MiddleWare Image



Original by Github issue

좋은 웹페이지 즐겨찾기