python - 如何通过交互式 CLI 在 python 中编写登录脚本
问题描述
我正在编写一个 python 脚本来登录(不是 ssh/telnet)远程系统(不是 Linux)并运行命令。下面是一个手动执行操作的示例。
root@centos (Centos 7.3) ➜ ~ shell_tool --cmd "<cmd1>;<cmd2>"
//interactive shell
System address: 10.0.0.1
Username: admin
Password: 123456
<output>
除了登录和运行命令,我还想保存输出。shell_tool --cmd ";" >>output.txt 在这里不起作用,因为命令后面有交互式 shell。
有人可以帮忙写剧本吗?
解决方案
我们可以创建mockup.py
它将作为您尝试控制的任何程序的替身:
import getpass
hostname = input('System address: ')
username = input('Username: ')
password = getpass.getpass('Password: ')
if password == 'good_guess':
while True:
line = input('mockup> ')
if line == 'quit':
break
示例交互
$python mockup.py
System address: bogus
Username: nobody
Password:
mockup> fake command
mockup> quit
我们可以编写一个 Python 程序来控制mockup.py
所有交互并将所有交互记录到一个名为的文件中session.log
:
import pexpect
import getpass
hostname = input('hostname: ')
username = input('username: ')
password = getpass.getpass('password: ')
prompt = 'mockup> '
with open('session.log', 'wb') as log_file:
session = pexpect.spawn('python3 mockup.py')
session.expect_exact('System address: ')
session.sendline(hostname)
session.expect_exact('Username: ')
session.sendline(username)
session.expect_exact('Password: ')
session.sendline(password)
# Start logging to a file here
session.logfile_read = log_file
session.expect_exact(prompt)
session.sendline('fake command')
session.expect_exact(prompt)
session.sendline('quit')
session.expect_exact(pexpect.EOF)
示例交互
$ python3 use_pexpect.py
hostname: bogus
username: nobody
password:
session.log 的内容
mockup> fake command
mockup> quit
这应该足以让您入门。
推荐阅读
- terraform - 调试 terraform 时如何查看对象值
- flutter - 列内的自定义导航器
- wso2 - wso2 IS 5.9 的 authenticationendpoint cookie/标头中缺少反 csrf 令牌
- node.js - Heroku 应用程序崩溃:at=error code=H10 desc=“App crashed” method=GET path=“/”
- java - java.lang.NoClassDefFoundError: org/quartz/SchedulerFactory
- python - 在Django中获取对象作为输出而不是List
- postgresql - CTE中的Postgres SELECT或INSERT?
- c# - 将一个表行动态映射到另一个表列
- sql - 如何遍历 SQL 表并选择数据中的峰值?
- javascript - 访问 asyncData 中的数据对象 - Nuxt