1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

踏み台サーバーを経由してプライベートなサーバーにアクセスする

Last updated at Posted at 2024-03-06

※自分用の備忘録です。

IPアドレス制限されているサーバーにアクセスしたい

開発案件で使っているサーバーがIPアドレス制限しているので、固定IP経由でないとアクセスできない、という状態です。
困ったことに5Gインターネットを使っているので、固定IPというものが取れない。
そこで自分のサーバー経由でアクセスすることにしました。

not HTTP(s) Proxy Server

なんか昔、こんな記事を書いてました(書いたことすら忘れてた)

このときは Squid3 使ってたんですねー。

調べたら、今どきは socks5 を使うのが良さそう。

超簡単! Socks5

sshコマンドに -D を付ければ良い。

ssh -D 8080 me@myserver.com

このままだとサーバーにログインしてしまうので、-f -N を付けておく。

ssh -f -N -D 8080 me@myserver.com

使い方はこんな感じ。

# 何も付けない場合、モバイルルーターのIPアドレス
curl http://ifconfig.me
172.58.xxx.xxx

# --proxy で指定すれば、サーバーのIPアドレス
curl --proxy socks5://localhost:8080 ifconfig.me
35.194.xxx.xxx

おー、IPアドレスが変わった!

ブラウザで Proxyを経由してアクセスする

Proxy用のChrome拡張「Proxy SwitchyOmega」
https://chromewebstore.google.com/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif

こんな感じにしてっと、、、
スクリーンショット 2024-03-06 午前1.14.12.png

auto switch として、このURLのときだけ proxy するようにしてあげればアクセスできる!
スクリーンショット 2024-03-06 午前1.15.46.png

Before / After のスクショを載せれないのが残念!

(おまけ) node.js の undici での使い方

おっしゃー。これでコードから呼び出せる!とか思ったら、そこからが長かった。

undici という(個人的には使いにくい)HTTPライブラリを使っているのですが、そのままだとProxyを経由してくれない。

試行錯誤の結果、fetch-socks を使って解決!

import { socksDispatcher } from 'fetch-socks';
import { Dispatcher, request } from 'undici';

export type getRequestParams = {
  url: string;
  userAgent: string;
  headers?: { [key: string]: string | undefined };
};

export const getRequest = async ({
  url,
  userAgent,
  headers,
}: getRequestParams): Promise<Dispatcher.ResponseData> => {
  const dispatcher = socksDispatcher({
    type: 5,
    host: "localhost",
    port: 8080,
  
    //userId: "username",
    //password: "password",
  });
  
  return await request(url, {
    headers: {
      'user-agent': userAgent,
      ...headers,
    },
    dispatcher,
  });
};

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?