9
8

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 5 years have passed since last update.

リモートデスクトップの接続元コンピュータのIPアドレスを取得

Posted at

Windowsサーバーに接続している端末のIPアドレスをログオン時点で取得したいが、
下記のリンクにあるように、ログオンスククリプトを使っている時は%CLIENTNAME%などの環境変数が使えないようだ。

リモートデスクトップの接続元コンピュータのIPアドレスを取得する方法

と言うわけで、

【初心者向け】各OSのTCPポート番号からプロセス/サービス調査コマンド入門
にあるようにnetstat コマンドを使ってIPアドレス情報を取得することができる。


netstat -n -p tcp | find ":3389"

IPアドレスだけを変数に代入したい場合は、下記のコマンドを打てば取得できる。

for /f "tokens=2 delims=:" %i in ('netstat -n -p tcp ^| find ":3389"') do set a=%i
set b=%a:~4%
set c=%b: =%
echo %c% 

BATファイルで使用したい場合は、%はエスケープする必要があるので、%%に変換して、下記のようにする

for /f "tokens=2 delims=:" %%i in ('netstat -n -p tcp ^| find ":3389"') do set a=%%i
set b=%a:~4%
set c=%b: =%

これ、パッと見ただけだと何やっているかわかり難い。

一つずつ分解して説明すると

まず、下記のnetstatコマンドを使って、取得した接続一覧からRDPの3389ポートを持つ行をfindコマンドで抽出する。

netstat -n -p tcp | find ":3389"

次にforコマンドで、
()の中の出力結果を「:」で区切った結果の2番目を変数aにセットする。「|」はエスケープするため「^」を前に入れる。

for /f "tokens=2 delims=:" %i in ('netstat -n -p tcp ^| find ":3389"') do set a=%i

変数aから4文字目以降を取得する。
BATファイルで文字列の切り出し

set b=%a:~4%

変数bから空白を削除する。%V:c1=c2%  文字c1を文字c2に置換する。

set c=%b: =%
9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?