python_wiki:test_port

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python_wiki:test_port [2015/03/09 23:27]
billdozor
python_wiki:test_port [2019/05/25 23:50]
Line 1: Line 1:
-====== Test Port ====== 
  
-**General Information** 
- 
-Function to check a network port to see if it is open on a host. 
- 
-**Checklist** 
-  * import socket 
- 
----- 
- 
-===== The Code ===== 
-<code python> 
-import socket 
- 
-def test_port(host,port): 
- # 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,timeout=5) 
- socket_test.close() 
- # Port is open, return 1 (true) 
- return 1 
- except Exception: 
- # Port is not open, return 0 (false) 
- return 0 
-</code> 
- 
-==== Usage ==== 
-Call this function, checking server1 for tcp/22 (ssh): 
-<code python> 
-if test_port(server1,22): 
-  do ssh stuff 
-else: 
-  print("Server not listening on tcp/22!") 
-</code> 
  • python_wiki/test_port.txt
  • Last modified: 2019/05/25 23:50
  • (external edit)