[英]How to write a login script in python via an interactive CLI
I am writing a python script to log into (not ssh/telnet) a remote system (not a Linux) and run commands. 我正在编写一个python脚本来登录(而不是ssh / telnet)远程系统(不是Linux)并运行命令。 Below is an example that does the things manually.
下面是一个手动执行操作的示例。
root@centos (Centos 7.3) ➜ ~ shell_tool --cmd "<cmd1>;<cmd2>"
//interactive shell
System address: 10.0.0.1
Username: admin
Password: 123456
<output>
Besides to login and run commands, I also want to save the output. 除了登录和运行命令,我还想保存输出。 shell_tool --cmd ";"
shell_tool --cmd“;” >>output.txt does not work here because there is interactive shell after the command.
>> output.txt在这里不起作用,因为命令后有交互式shell。
Can someone help with the script? 有人可以帮助编写脚本吗?
We can create mockup.py
that will be a stand-in for whatever program you are trying to control: 我们可以创建
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
Sample Interaction 样本互动
$python mockup.py
System address: bogus
Username: nobody
Password:
mockup> fake command
mockup> quit
We can write a Python program that will control mockup.py
and log all interaction to a file named session.log
: 我们可以编写一个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)
Sample Interaction 样本互动
$ python3 use_pexpect.py
hostname: bogus
username: nobody
password:
Contents of session.log session.log的内容
mockup> fake command
mockup> quit
This should be enough information to get you started. 这应该足以让您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.