首页 > 解决方案 > 如何使用 Python pexpect 执行操作系统命令?

问题描述

我想执行一个python脚本,通过自动写入用户密码切换到另一个用户。两个用户都没有 root 权限。登录后我想执行操作系统命令“whoami”来检查登录是否成功。这是代码:

child = pexpect.spawn('su - otheruser)
child.expect_exact('Password:')
child.sendline('password')
print("logged in...")
child.expect('')
child.sendline('whoami')
print(child.before)

我想将命令的输出打印到控制台(仅用于调试),但输出类似于“b272”(随机字母的组合)而不是实际的 whoami 用户。我该如何解决这个问题?

稍后我想从切换的用户创建一些文件等等。所以基本上,我想在另一个用户登录的 python 脚本中执行 OS 命令。

标签: pythonlinuxshelloperating-systemcommand

解决方案


Pexpect 搜索并不贪心,所以它会在第一次匹配时停止。before当我用, match.groups(),after和测试你的代码时buffer,我没有得到EOFor TIMEOUT,所以它一定在读取开始时就匹配并且什么也没返回(我很惊讶你得到任何结果)。

我建议始终在 a 后面sendline加上expect,提示符 ( ]$) 的结尾是一件好事,而不是空字符串。

这是我对您的代码的看法,包括创建文件:

注意- 在 Centos 7.9 上测试,使用 Python 2.7。

import pexpect

child = pexpect.spawn("su - orcam")
child.expect_exact("Password:")
child.sendline("**********")
child.expect_exact("]$")
print("Logged in...\n")
child.sendline("whoami")
child.expect_exact("]$")
print(child.before + "\n")
child.sendline("echo -e 'Hello, world.' >> hello.txt")
child.expect_exact("]$")
child.sendline("cat hello.txt")
child.expect_exact("]$")
print(child.before + "\n")
child.sendline("exit")
index = child.expect_exact(["logout", pexpect.EOF, ])
print("Logged out: {0}".format(index))

输出:

Logged in...

 whoami
orcam
[orcam@localhost ~

 cat hello.txt
Hello, world.
[orcam@localhost ~

Logged out: 0

推荐阅读