0

I am trying to use telnet to check service connections to a server. This is the code I used:

p = subprocess.run("telnet localhost 80", shell=True, universal_newlines=True, stdout=subprocess.PIPE)
print(p.stdout)

if I run this there is a blank response and it seems telnet is waiting to timeout in the background until I press ctrl+c.

If I run the following code:

p = subprocess.run("telnet localhost 80", shell=True, universal_newlines=True)

there is a response as below:

Trying ::1...
Connected to localhost.
Escape character is '^]'.

If I want to use this script to test connections to servers, how do pass ctrl+] and 'quit' to get out of the telnet prompt? Also, if I want to test responses using "GET/" to telnet, how do I do it ?

meuh
  • 11,500
  • 2
  • 29
  • 45

2 Answers2

1

You'd need to use subprocess.Popen() and communicate with the telnet process using the resulting popen object's stdin/stdout streams.

But – do you actually need to shell out to telnet? If you only need to know whether something is connectable,

import socket
s = socket.socket()
s.connect(('localhost', 80))
s.close()

will raise an exception if connecting fails; if you need to do a simple ping/pong,

import socket
s = socket.socket()
s.connect(('localhost', 80))
s.sendall(b'Hello? Are you there?\n')
print(s.recv(8192))
s.close()

might suffice.

(You may need to look into adding timeouts and such, though.)

AKX
  • 152,115
  • 15
  • 115
  • 172
0

Try:

proc = subprocess.Popen(['lsof', '-iTCP', -'sTCP:LISTEN', '-n' ,'-P'], stdout=subprocess.PIPE)
tmp = proc.stdout.read()
Mahsa Hassankashi
  • 2,086
  • 1
  • 15
  • 25