像老板一样使用 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

# 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

相关内容