Differences
This shows you the differences between two versions of the page.
python_wiki:test_port [2014/11/24 22:43] billdozor |
python_wiki:test_port [2019/05/25 23:50] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Test Port ====== | ||
- | Function to check a network port to see if it is open on a host. | ||
- | <code python> | ||
- | import socket | ||
- | |||
- | def test_port(host, | ||
- | # Test a host and port pair to see if a connection can be made. | ||
- | host_port = (host,port) | ||
- | try: | ||
- | socket_test = socket.create_connection(host_port, | ||
- | socket_test.close() | ||
- | # Port is open, return 1 (true) | ||
- | return 1 | ||
- | except Exception: | ||
- | # Port is not open, return 0 (false) | ||
- | return 0 | ||
- | </ | ||
- | |||
- | Call this function, checking server1 for tcp/22 (ssh): | ||
- | <code python> | ||
- | if test_port(server1, | ||
- | do ssh stuff | ||
- | else: | ||
- | print(" | ||
- | </ |