这时候有人要说了,执行shell用os.system()就行了嘛

需要返回值用subprocess.Popen().communicate()嘛

但是如果需要多次交互,就需要使用下面这种方法

import subprocess
import os
ssh = subprocess.Popen('ssh [email protected]', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True)
os.read(ssh.stdout.fileno(), 10240)
ssh.stdin.write('ls\n')
ssh.stdin.flush()
print(os.read(ssh.stdout.fileno(), 10240))
ssh.stdin.write('pwd\n')
ssh.stdin.flush()
print(os.read(ssh.stdout.fileno(), 10240))
ssh.stdin.write('whoami\n')
ssh.stdin.flush()
print(os.read(ssh.stdout.fileno(), 10240))
ssh.stdin.write('exit\n')
ssh.stdin.flush()