This commit is contained in:
Clemens Vasters 2018-07-08 22:51:58 +02:00
Родитель 8796403dc3
Коммит 3416ac19e1
10 изменённых файлов: 355 добавлений и 64 удалений

Просмотреть файл

@ -41,15 +41,6 @@ the configured relay entity.
Arguments:
**--addhosts** / **--cleanhosts**
When `azbridge` is run with the `--addhosts` option, which
requires running with administrative privileges, all hostname values from the
configuration files' `LocalForward` section are added to the local machine's "hosts"
file. The `--cleanhosts` option removes all entries added by `--addhosts`.
These options cannot be combined with use of the -L or -R options below.
**-b bind_address**
Use bind_address on the local machine as the source address of
@ -281,11 +272,9 @@ omitted, the default is for the listener to bind to all interfaces.
The `RelayName` option is always required.
The `HostName` is property optional and used by the `--addhosts` command
line option of `azbridge`. When `azbridge` is run with that option, which
requires running with administrative privileges, the hostname value is added
to the local machine's "hosts" file. The `--cleanhosts` option removes all
entries added by `--addhosts`.
The `HostName` is property optional and used for documentation. Host
names that shall resolve to the -L local forwarder address need to
be added to the local hosts file.
The `ConnectionString` property is optional and overrides the global settings
if supplied.

Просмотреть файл

@ -19,10 +19,6 @@ namespace Microsoft.Azure.Relay.Bridge.Configuration
[Option(CommandOptionType.NoValue, LongName = "svc", ShortName = "svc", Description = "Reserved for Windows service control manager")]
public bool? ServiceRun { get; set; }
#endif
[Option(CommandOptionType.NoValue, LongName = "addhosts")]
public bool? AddHosts { get; set; }
[Option(CommandOptionType.NoValue, LongName = "cleanhosts")]
public bool? CleanHosts { get; set; }
[Option(CommandOptionType.SingleValue, ShortName = "b", Description = "Source address of forwarding connections.")]
public string BindAddress { get; set; }
[Option(CommandOptionType.NoValue, ShortName = "C", Description = "Enable compression")]

Просмотреть файл

@ -282,10 +282,6 @@ namespace Microsoft.Azure.Relay.Bridge.Configuration
{
config.BindAddress = commandLineSettings.BindAddress;
}
if (commandLineSettings.CleanHosts.HasValue)
{
config.ClearAllForwardings = commandLineSettings.CleanHosts;
}
if (commandLineSettings.Compression.HasValue)
{
config.Compression = commandLineSettings.Compression;

Просмотреть файл

@ -5,38 +5,6 @@ namespace Microsoft.Azure.Relay.Bridge
{
static class Constants
{
public const string ConfigFileName = "Microsoft.HybridConnectionManager.Listener.exe.config";
public const string HybridConnectionManagerConfigurationNounName = "HybridConnectionManagerConfiguration";
public const string HybridConnectionManagerDefaultParameterSetName = "HybridConnectionManagerDefaultParamSet";
public const string HybridConnectionNounName = "HybridConnection";
public const string TcpClientConfigName = "tcpClients";
public const string TcpListenerConfigName = "tcpListeners";
public const string HybridConnectionsConfigName = "hybridConnection";
public const string HybridConnectionsRegistryPath = @"SOFTWARE\Microsoft\HybridConnectionManager\0.7.5";
public const string HybridConnectionsSectionConfigName = "hybridConnections";
public const string InstallDir = "installDir";
public const string ManagementPort = "managementPort";
public const string AddHostNameScriptFile = "add-hostnames.ps1";
public const string ConfigSetting = ConfigSettingPrefix + "ConnectionStrings";
public const string ConfigSettingPrefix = "Microsoft.WindowsAzure.Plugins.HybridConnectionClient.";
public const string ConnectionString = "ConnectionString";
public const string GetHostNamesScriptFile = "get-hostnames.ps1";
public const string RemoveHostNameScriptFile = "remove-hostnames.ps1";
}
}

Просмотреть файл

@ -349,13 +349,6 @@ confer sufficient permissions for the desired operation(s) to be executed, e.g.
Arguments:
--addhosts / --cleanhosts
When azbridge is run with the --addhosts option, which
requires running with administrative privileges, all hostname values from the configuration files' LocalForward section are added to the local machine's "hosts" file. The --cleanhosts option removes all entries added by --addhosts.
These options cannot be combined with use of the -L or -R options below.
-b bind_address
Use bind_address on the local machine as the source address of forwarding connections. Only useful on systems with more than one address.

Просмотреть файл

@ -24,6 +24,10 @@
<Content Include="azbridge_config.machine.yml" CopyToOutputDirectory="PreserveNewest">
<LinuxPath>/etc/azbridge/azbridge_config.yml</LinuxPath>
</Content>
<Content Include="../tools/Powershell/add-hostname.ps1" CopyToOutputDirectory="PreserveNewest" Condition="$(RuntimeIdentifier.StartsWith('win'))"/>
<Content Include="../tools/Powershell/remove-hostname.ps1" CopyToOutputDirectory="PreserveNewest" Condition="$(RuntimeIdentifier.StartsWith('win'))"/>
<Content Include="../tools/Powershell/get-hostname.ps1" CopyToOutputDirectory="PreserveNewest" Condition="$(RuntimeIdentifier.StartsWith('win'))"/>
<Content Include="../tools/bash/hostnames.sh" CopyToOutputDirectory="PreserveNewest" Condition="! $(RuntimeIdentifier.StartsWith('win'))"/>
</ItemGroup>
<Choose>
@ -124,6 +128,7 @@
<PostInstallScript>
sudo /bin/echo #!/bin/sh > /etc/profile.d/azbridge.sh;
sudo /bin/echo export PATH="\$PATH:/usr/share/azbridge" >> /etc/profile.d/azbridge.sh;
sudo /bin/echo source /usr/share/hostnames.sh >> /etc/profile.d/azbridge.sh;
sudo chmod a+x /etc/profile.d/azbridge.sh;
if [ ! -d "/etc/azbridge" ]; then sudo mkdir /etc/azbridge; fi
if [ ! -a "/etc/azbridge/azbridge_config.machine.yml" ]; then

Просмотреть файл

@ -1,7 +1,4 @@
<#
.SYNOPSIS
Adds one or more hostnames to the hosts file.
.DESCRIPTION
The hosts file is used to map hostnames to IP addresses.

Просмотреть файл

@ -0,0 +1,295 @@
<#
.SYNOPSIS
Removes one or more hostnames from the hosts file.
.DESCRIPTION
The hosts file is used to map hostnames to IP addresses.
.PARAMETER Hostnames
One or more hostnames to remove from the hosts file.
.EXAMPLE
.\Remove-Hostnames.ps1 foobar
Description
-----------
Assume the following line was previously added to the hosts file:
127.0.0.1 foobar
After running "Remove-Hostnames.ps1 foobar" the hosts file no longer contains this
line.
.EXAMPLE
.\Remove-Hostnames.ps1 foo
Description
-----------
Assume the following line was previously added to the hosts file:
127.0.0.1 foobar foo bar
After running "Remove-Hostnames.ps1 foo" the line in the hosts file is updated
to remove the specified hostname ("foo"):
127.0.0.1 foobar bar
.EXAMPLE
.\Remove-Hostnames.ps1 foo, bar
Description
-----------
Assume the following line was previously added to the hosts file:
127.0.0.1 foobar foo bar
After running "Remove-Hostnames.ps1 foo, bar" the line in the hosts file is updated to
remove the specified hostnames ("foo" and "bar"):
127.0.0.1 foobar
.NOTES
This script must be run with administrator privileges.
#>
param(
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string[]] $Hostnames
)
begin
{
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
function CreateHostsEntryObject(
[string] $ipAddress,
[string[]] $hostnames,
<# [string] #> $comment) #HACK: never $null if type is specified
{
$hostsEntry = New-Object PSObject
$hostsEntry | Add-Member NoteProperty -Name "IpAddress" `
-Value $ipAddress
[System.Collections.ArrayList] $hostnamesList =
New-Object System.Collections.ArrayList
$hostsEntry | Add-Member NoteProperty -Name "Hostnames" `
-Value $hostnamesList
If ($hostnames -ne $null)
{
$hostnames | foreach {
$hostsEntry.Hostnames.Add($_) | Out-Null
}
}
$hostsEntry | Add-Member NoteProperty -Name "Comment" -Value $comment
return $hostsEntry
}
function ParseHostsEntry(
[string] $line)
{
$hostsEntry = CreateHostsEntryObject
Write-Debug "Parsing hosts entry: $line"
If ($line.Contains("#") -eq $true)
{
If ($line -eq "#")
{
$hostsEntry.Comment = [string]::Empty
}
Else
{
$hostsEntry.Comment = $line.Substring($line.IndexOf("#") + 1)
}
$line = $line.Substring(0, $line.IndexOf("#"))
}
$line = $line.Trim()
If ($line.Length -gt 0)
{
$hostsEntry.IpAddress = ($line -Split "\s+")[0]
Write-Debug "Parsed address: $($hostsEntry.IpAddress)"
[string[]] $parsedHostnames = $line.Substring(
$hostsEntry.IpAddress.Length + 1).Trim() -Split "\s+"
Write-Debug ("Parsed hostnames ($($parsedHostnames.Length)):" `
+ " $parsedHostnames")
$parsedHostnames | foreach {
$hostsEntry.Hostnames.Add($_) | Out-Null
}
}
return $hostsEntry
}
function ParseHostsFile
{
$hostsEntries = New-Object System.Collections.ArrayList
[string] $hostsFile = $env:WINDIR + "\System32\drivers\etc\hosts"
If ((Test-Path $hostsFile) -eq $false)
{
Write-Verbose "Hosts file does not exist."
}
Else
{
[string[]] $hostsContent = Get-Content $hostsFile
$hostsContent | foreach {
$hostsEntry = ParseHostsEntry $_
$hostsEntries.Add($hostsEntry) | Out-Null
}
}
# HACK: Return an array (containing the ArrayList) to avoid issue with
# PowerShell returning $null (when hosts file does not exist)
return ,$hostsEntries
}
function UpdateHostsFile(
$hostsEntries = $(Throw "Value cannot be null: hostsEntries"))
{
Write-Verbose "Updatings hosts file..."
[string] $hostsFile = $env:WINDIR + "\System32\drivers\etc\hosts"
$buffer = New-Object System.Text.StringBuilder
$hostsEntries | foreach {
If ([string]::IsNullOrEmpty($_.IpAddress) -eq $false)
{
$buffer.Append($_.IpAddress) | Out-Null
$buffer.Append("`t") | Out-Null
}
If ($_.Hostnames -ne $null)
{
[bool] $firstHostname = $true
$_.Hostnames | foreach {
If ($firstHostname -eq $false)
{
$buffer.Append(" ") | Out-Null
}
Else
{
$firstHostname = $false
}
$buffer.Append($_) | Out-Null
}
}
If ($_.Comment -ne $null)
{
If ([string]::IsNullOrEmpty($_.IpAddress) -eq $false)
{
$buffer.Append(" ") | Out-Null
}
$buffer.Append("#") | Out-Null
$buffer.Append($_.Comment) | Out-Null
}
$buffer.Append([System.Environment]::NewLine) | Out-Null
}
[string] $hostsContent = $buffer.ToString()
$hostsContent = $hostsContent.Trim()
Set-Content -Path $hostsFile -Value $hostsContent -Force -Encoding ASCII
Write-Verbose "Successfully updated hosts file."
}
[bool] $isInputFromPipeline =
($PSBoundParameters.ContainsKey("Hostnames") -eq $false)
[int] $pendingUpdates = 0
[Collections.ArrayList] $hostsEntries = ParseHostsFile
}
process
{
If ($isInputFromPipeline -eq $true)
{
$items = $_
}
Else
{
$items = $Hostnames
}
$items | foreach {
[string] $hostname = $_
for ([int] $i = 0; $i -lt $hostsEntries.Count; $i++)
{
$hostsEntry = $hostsEntries[$i]
Write-Debug "Hosts entry: $hostsEntry"
If ($hostsEntry.Hostnames.Count -eq 0)
{
continue
}
for ([int] $j = 0; $j -lt $hostsEntry.Hostnames.Count; $j++)
{
[string] $parsedHostname = $hostsEntry.Hostnames[$j]
Write-Debug ("Comparing specified hostname" `
+ " ($hostname) to existing hostname" `
+ " ($parsedHostname)...")
If ([string]::Compare($hostname, $parsedHostname, $true) -eq 0)
{
Write-Debug "Removing hostname ($hostname) from host entry ($hostsEntry)..."
$hostsEntry.Hostnames.RemoveAt($j)
$j--
$pendingUpdates++
}
}
If ($hostsEntry.Hostnames.Count -eq 0)
{
Write-Debug ("Removing host entry (because it no longer specifies" `
+ " any hostnames)...")
$hostsEntries.RemoveAt($i)
$i--
}
}
}
}
end
{
If ($pendingUpdates -eq 0)
{
Write-Verbose "No changes to the hosts file are necessary."
return
}
Write-Verbose ("There are $pendingUpdates pending update(s) to the hosts" `
+ " file.")
UpdateHostsFile $hostsEntries
}

Просмотреть файл

@ -0,0 +1,52 @@
#!/bin/bash
# remove specified host from /etc/hosts
function removehost() {
if [[ "$1" ]]
then
HOSTNAME=$1
if [ -n "$(grep "\b$HOSTNAME\b" /etc/hosts)" ]
then
echo "$HOSTNAME Found in your /etc/hosts, Removing now...";
sudo sed -i".bak" "/\b$HOSTNAME\b/d" /etc/hosts
else
echo "$HOSTNAME was not found in your /etc/hosts";
fi
else
echo "Error: missing required parameters."
echo "Usage: "
echo " removehost domain"
fi
}
#add new ip host pair to /etc/hosts
function addhost() {
if [[ "$1" && "$2" ]]
then
IP=$1
HOSTNAME=$2
if [ -n "$(grep "\b$HOSTNAME\b" /etc/hosts)" ]
then
echo "$HOSTNAME already exists:";
echo $(grep "\b$HOSTNAME\b" /etc/hosts);
else
echo "Adding $HOSTNAME to your /etc/hosts";
printf "%s\t%s\n" "$IP" "$HOSTNAME" | sudo tee -a /etc/hosts > /dev/null;
if [ -n "$(grep "\b$HOSTNAME\b" /etc/hosts)" ]
then
echo "$HOSTNAME was added succesfully:";
echo $(grep "\b$HOSTNAME\b" /etc/hosts);
else
echo "Failed to Add $HOSTNAME, Try again!";
fi
fi
else
echo "Error: missing required parameters."
echo "Usage: "
echo " addhost ip domain"
fi
}