python - 如何使用 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 命令。
解决方案
Pexpect 搜索并不贪心,所以它会在第一次匹配时停止。before
当我用, match.groups()
,after
和测试你的代码时buffer
,我没有得到EOF
or 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
推荐阅读
- scala - 你如何处理一系列 Akka 流源?
- python - 将日期转换为时间戳 python
- javascript - Meteor.users.find() 没有检索服务器端的所有用户(在客户端运行良好)
- typescript - 如何从接口中使用的所有类型中引用任何类型?
- angular - Bootstrap 切换复选框在 Bootstrap 轮播中不起作用
- css - 如何解决导航块的 CSS 问题?
- c++ - 在 ubuntu 上安装 node js pulsar 客户端
- java - mvn test 第一次编译失败
- javascript - Hotkeys-js - 如何取消绑定我的热键?
- asynchronous - F#:async{} 块内的正确“try”块?