import socket
import sys
def get_host_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.1', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def is_port_used(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.settimeout(1)
s.connect((ip, port))
return True
except socket.timeout:
return "timeout"
except socket.error:
return "Connection refused"
finally:
s.close()
if __name__ == '__main__':
host_ip = get_host_ip()
target_ip = sys.argv[1]
target_port = int(sys.argv[2])
connect_status=is_port_used(target_ip, target_port)
print "host_ip:%s target_ip:%s target_port:%s status:%s"%(host_ip,target_ip,target_port,connect_status)
使用脚本
python /tmp/port_test.py 10.xxx.xxx.100 9002