我有以下用 2.7 python 编写的代码:
#...import stuff
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
print "Please wait, scanning remote Host", remoteServerIP
try:
for port in xrange(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print "port {}: open".format(port)
sock.close
except KeyboardInterrupt:
print "\nexiting..."
sys.exit()
输出:
Enter a remote host to scan: www.myexamplesite.com
Please wait, scanning remote Host xxx.xxx.xx.xx
port 21: open
port 22: open
...
但问题是我也想知道使用了哪些端口以及它们的用途,就像:
但这只是打印从 1 到 1024 的端口
有没有功能/方法可以做到这一点?
最佳答案
socket.getservbyport()
会将端口号转换为预期在该端口上运行的服务(通过 /etc/services
),但实际上不会通过端口进行通信以找出真正在运行的内容。
关于python - 打印端口及其名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47003908/