像老闆一樣使用 Powershell

像老闆一樣使用 Powershell

當未安裝 Telnet 時,人們使用什麼來檢查連接埠是否開啟且可存取?例如,我曾經使用過的技術telnet <destination>並且知道它在那裡,即使 telnet 無法與另一端的系統互動。

Windows 2008 沒有安裝telnet,所以我有點迷失了。那我可以用什麼來代替呢。如果 Linux 或 Solaris 中沒有該功能,也請提供。

我是在不同網站工作的顧問。由於多種原因(存取權限、更改控制時間、如果我安裝它,明年有人使用它,我們需要承擔一些責任等),我無法在其他人的伺服器上安裝。但是 USB 或其他獨立的、未安裝的工具會很棒...

答案1

像老闆一樣使用 Powershell


基本程式碼

$ipaddress = "4.2.2.1"
$port = 53
$connection = New-Object System.Net.Sockets.TcpClient($ipaddress, $port)

if ($connection.Connected) {
    Write-Host "Success"
}
else {
    Write-Host "Failed"
}

一班輪

PS C:\> test-netconnection -ComputerName 4.2.2.1 -Port 53

將其轉換為 cmdlet

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$ip,
    
   [Parameter(Mandatory=$True,Position=2)]
   [int]$port
)

$connection = New-Object System.Net.Sockets.TcpClient($ip, $port)
if ($connection.Connected) {
    Return "Connection Success"
}
else {
    Return "Connection Failed"
}

儲存為腳本並一直使用

然後,您可以在 powershell 或 cmd 提示字元中使用該命令,如下所示:

PS C:\> telnet.ps1 -ip 8.8.8.8 -port 53

或者

PS C:\> telnet.ps1 8.8.8.8 53

答案2

以下是在不使用 telnet 的情況下測試 TCP 連接埠的幾種不同方法。

巴什手冊頁

# cat < /dev/tcp/127.0.0.1/22
SSH-2.0-OpenSSH_5.3
^C

# cat < /dev/tcp/127.0.0.1/23
bash: connect: Connection refused
bash: /dev/tcp/127.0.0.1/23: Connection refused


捲曲

# curl -v telnet://127.0.0.1:22
* About to connect() to 127.0.0.1 port 22 (#0)
*   Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 22 (#0)
SSH-2.0-OpenSSH_5.3
^C

# curl -v telnet://127.0.0.1:23
* About to connect() to 127.0.0.1 port 23 (#0)
*   Trying 127.0.0.1... Connection refused
* couldn't connect to host
* Closing connection #0
curl: (7) couldn't connect to host


Python

# python
Python 2.6.6 (r266:84292, Oct 12 2012, 14:23:48)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> clientsocket.connect(('127.0.0.1', 22))
>>> clientsocket.send('\n')
1
>>> clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> clientsocket.connect(('127.0.0.1', 23))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused


珀爾

# perl
use IO::Socket::INET;
$| = 1;
my $socket = new IO::Socket::INET(
  PeerHost => '127.0.0.1',
  PeerPort => '22',
  Proto => 'tcp',
);
die "cannot connect to the server $!\n" unless $socket;
print "connected to the server\n";
^D
connected to the server

相關內容