python检测远程主机端口状态 python检测主机端口是否开放

发布时间:2020-11-02编辑:脚本学堂
本文介绍下,python实现的检测远程主机端口状态的代码,用于检测主机端口是否开放,用到了python的socket模块,有需要的朋友参考下。

本节主要内容:
python代码检测远程主机状态

1,首先,安装python2.7
 

复制代码 代码示例:
#wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
#tar xf Python-2.7.3.tgz
#cd Python-2.7.3
#./configure --prefix=/usr/local/python
#make
#make install
#mv /usr/bin/python /usr/bin/python.bak
#ln -s /usr/local/python/bin/python /usr/bin/python

检测下python的版本~  python -V

2,检测远程主机端口状态
 

复制代码 代码示例:
#!/usr/bin/env python
#-*- coding:utf-8-*-
import socket
def main():
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.settimeout(1000)
ip=raw_input('Please input ip(default:127.0.0.1)')
    if ip=='':
ip='127.0.0.1'
s=raw_input('Please input start port(default:80)')
    if s=='':
startport=80
    else:
startport=int(s)
s=raw_input('Please input end port(default:80)')
    if s=='':
endport=80
    else:
endport=int(s)
    for port in range(startport,endport+1):
        print('Port scaning:%d' % port)
        try:
            sk.connect((ip,port))
            print('Server %s port %d OK!' % (ip,port))
        except Exception:
            print('Server %s port %d is not connected!' % (ip,port))
    sk.close()
if __name__ == '__main__':
    main()

例2,检测端口的是否打开
 

复制代码 代码示例:
#!/usr/bin/env python
#
#site: www.jb200.com
import os
import socket
def IsOpen(ip,port):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((ip,int(port)))
s.shutdown(2)
print '%d is open' % port
return True
except:
print '%d is down' % port
return False
if __name__ == '__main__':
IsOpen('10.10.10.63',8888)