2016-12-20 38 views
1

哎第一次的問題提問者希望這是正確的格式蟒蛇流程腳本不返回相同的答案直接bash命令

我有試圖基本上在這種情況下的Telnet 使用bash命令蟒蛇scirpt這是腳本

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

您可以使用socket — Low-level networking interfac

看到一週的Python模塊約socket

的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)