我找到了解決我的問題。 Paramiko模塊爲我工作。 =)
import sys
import time
import paramiko
host = '192.168.1.1'
user = 'admin'
pwd = 'admin'
i = 1
#def interactive_shell():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
transport = paramiko.Transport((host,22))
transport.connect(username=user, password=pwd)
time.sleep(0.2)
#chan = paramiko.transport.open_session()
chan = transport.open_session()
chan.setblocking(0)
chan.invoke_shell()
chan.send("command") # Send command to device
chan.send("\n") # Send Enter
time.sleep(1) #optional
while not chan.exit_status_ready():
time.sleep(0.1)
if chan.recv_ready() :
output = chan.recv(8192)
if len(output) > 0 :
outputLines = output.splitlines(True)
sys.stdout.write(output)
if "unit" in output:
sys.stdout.flush()
break
if chan.recv_stderr_ready() :
mystderr = chan.recv_stderr(8192)
if len(mystderr) > 0 :
print mystderr, ","
transport.close()