简体   繁体   English

如何使用Python的pexpect库执行root命令?

[英]How to execute a root command using Python's pexpect library?

I am trying to mount a drives shared folder on my system (Centos). 我正在尝试在系统(Centos)上安装驱动器共享文件夹。

Since the mount command needs to be executed as a root user, I am first logging in as sudo user using the su command. 由于需要以root用户身份执行mount命令,因此我首先使用su命令以sudo用户身份登录。 After the login is successful, I want to execute my mount command. 登录成功后,我要执行我的安装命令。

import pexpect

cmd1 = "su"
cmd2 = "mount -t cifs -o username=abc,password=def //101.101.101.214/Volume1 /home/Juna/Drive"
pwd = "my_password"
child = pexpect.spawn(cmd1)
child.expect('Password:')
child.sendline(pwd)
child.expect('#')
child.sendline(cmd2)

I am not getting the desired results from my script. 我无法从脚本中获得所需的结果。 Can you please share what needs to be done or modified in my script to get the desired result. 您能否在我的脚本中分享需要完成或修改的内容以获得所需的结果。

与其交互地发送命令,不如使用-c选项给su提供要运行的命令:

child = pexpect.spawn(['su', 'root', '-c', cmd2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM