首页 > 解决方案 > 如何通过交互式 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。

有人可以帮忙写剧本吗?

标签: python

解决方案


我们可以创建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

这应该足以让您入门。


推荐阅读