如果可以在Python中执行此操作,则pexpect的示例几乎可以完全满足您的要求:
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before # Print the result of the ls command.
child.interact() # Give control of the child to the user.
要使用ssh而不是ftp来执行此操作,您需要类似于以下代码(pexpect中的示例文件具有更多详细信息和信息,但这里是基础知识):
import pexpect
child = pexpect.spawn ('ssh root@marlboro')
child.expect ('Password:')
child.sendline ('password')
child.expect ('prompt# ')
child.sendline ('cd /tmp')
child.expect ('prompt# ')
child.sendline ('ls -altr | tail')
child.expect ('prompt# ')
print child.before, child.after # Print the result of the ls command.
child.interact() # Give control of the child to the user.
不要误会我的意思,我很期待(尤其是自动预期),但是python实在让我更容易理解。