Hosts ファイルを変更したい場合は、手動で Hosts ファイルを見つけてエディタで編集するだけでなく、バッチ コマンドを使用して編集することもできます。今日紹介したいのは、プログラムのインストール時に Inno Setup インストール パッケージを使用してホストを変更し、特定のアプリケーションが検証のために特定のサーバーにアクセスするのをブロックする効果を実現することです。
Windows Hosts ファイルには、コンピュータをインターネットまたはローカル ネットワーク上のサイトに誘導するのに役立つ IP アドレスとドメイン名が保存されます。通常、Web を閲覧する場合に Hosts ファイルを編集する必要はありませんが、これは有害なサイトをブロックするための必須の方法であり、開発中のサイトに Web アドレスをバインドするためのツールです。Hosts ファイルの設定が正しくないと、Web サイトの読み込みが停止する可能性があるため、オンラインで特定のサイトに接続できない場合は、ファイルに間違ったエントリがないか確認するか、ファイルの変更をクリアしてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 4 4 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#ifdef Unicode #define A "W" #else #define A "A" #endif
[code] const myMark = '由 gnatix 编写'; // 関数として
GetFileAttributes(lpFileName: String): Cardinal; 外部 'GetFileAttributes{#A}@kernel32.dll stdcall';
関数 SetFileAttributes(lpFileName: String; dwFileAttributes: Cardinal): ブール値; 外部 'SetFileAttributes{#A}@kernel32.dll stdcall';
関数 LineInFile(sLine, fPath: string): ブール値; var aos: TArrayOfString; n: 整数。 開始 結果:= false; if LoadStringsFromFile(fPath, aos) then for n:= 0 to GetArrayLength(aos)-1 do if aos[n] = sLine then 開始 結果 := true; 出口; 終わり; 終わり;
プロシージャ AddHosts(newItem, コメント: 文字列); var OldFileAttribute: カーディナル; hfPath、newLine: 文字列; begin hfPath := ExpandConstant('{sys}\drivers\etc\hosts'); If not LineInFile(newItem, hfPath) then // ホストを追加中还没有の项目 begin OldFileAttribute:= GetFileAttributes(hfPath); SetFileAttributes(hfPath, FILE_ATTRIBUTE_NORMAL); newLine := newItem + ' # ' + myMark; コメント > ' ' の場合、 newLine := newLine + ' / ' + コメント; SaveStringToFile(hfPath, #13#10 + newLine, True); SetFileAttributes(hfPath, 終わり; 終わり;
プロシージャ RemoveHosts(sItem: string); var OldFileAttribute: カーディナル; hfPath、newLine: 文字列; stl: TStringList; n: 整数。 begin hfPath := ExpandConstant('{sys}\drivers\etc\hosts'); newLine := sItem + ' # ' + myMark; stl:= TStringList.Create; stl.LoadFromFile(hfPath); for n:= stl.Count-1 downto 0 do if Pos(newLine, stl.Strings[n]) = 1 then stl.Delete(n); OldFileAttribute:= GetFileAttributes(hfPath); SetFileAttributes(hfPath, FILE_ATTRIBUTE_NORMAL); stl.SaveToFile(hfPath); stl.無料。 SetFileAttributes(hfPath, OldFileAttribute); 終わり;
procedure Initializewizard; begin AddHosts('0.0.0.0 www.xxx.com', 'This is a comment'); // Hosts にコメント付きの新しい項目を追加 AddHosts('0.0.0.0 www.111.com', '' ); // コメントなしで新しい項目をホストに追加します end;
procedure DeinitializeUninstall; begin RemoveHosts('0.0.0.0 www.xxx.com'); // ホストから項目を削除します RemoveHosts('0.0.0.0 www.111 .com') ; // ホスト 側から項目を削除します。 |
上記のコードを Inno Setup スクリプトにコピーして保存するか、必要に応じて変更します。
Windows ホスト ファイルは DNS サーバーのローカル コピーのように機能するため、カスタム ドメイン リダイレクトを実行したり、Web サイトをブロックしたり、マルウェアによって設定された悪意のあるエントリを削除したりする場合に、その編集方法を知っておくと便利です。ただし、Windows の一部のバージョンでこのファイルに変更を加えると、アクセス許可エラーやその他の問題が発生する可能性があります。