我有一个python scirpt,它试图在这种情况下使用bash命令telnet 这是剧本
import subprocess
proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('telnet 192.168.1.67 5555')
print (stdout)
我的另一台机器上有一个脚本,在端口5555上侦听 并在bash中调用脚本返回
Connection closed by foreign host.
("Trying 192.168.1.67...\nConnected to 192.168.1.67.\nEscape character is '^]'.\n", None
我的另一台计算机识别出一个连接,但它会立即关闭连接 而当我运行命令
telnet 192.168.1.67 5555
它工作正常并保持连接打开
我的问题是如何编写一个与命令“telnet 192.168.1.67 5555”相同的脚本并保持连接打开?
答案 0 :(得分:0)
您可以使用socket — Low-level networking interfac
请参阅本周关于socket的Python模块。
Python 2示例:
import socket, select, string, sys
if(len(sys.argv) < 3) :
print 'Usage : python telnet.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host'
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print 'Connection closed'
sys.exit()
else :
#print data
sys.stdout.write(data)
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)