我必须自动执行各种OS任务,下面是序列:
1) change user to "access"
2) cd <location>
3) execute command to create debian pkg
4) export the debian pkg to 3 different servers
5) install the debian pkg on all the 3 servers.
我已经编写了一个python程序来测试我的前2个步骤,但我失败了。我正在使用“ getpass”和“ OS”模块来完成任务。下面是示例代码:
import os
import getpass
# os.popen('sudo root', 'r', 1)
def login():
user = input("Username [%s]: " % getpass.getuser())
if not user:
user = getpass.getuser()
pprompt = lambda: (getpass.getpass(), getpass.getpass('Retype password: '))
p1, p2 = pprompt()
while p1 != p2:
print('Passwords do not match. Try again')
p1, p2 = pprompt()
return user, p1
psswd = login()
print("CHANGED THE USER")
print(" ")
print("the id of the user is:", os.system('whoami'))
print(" ")
print("The current working directory is:", os.getcwd())
print(" ")
os.chdir('/var/tmp')
print("The new working directory is:", os.getcwd())
要测试代码是否在本地计算机上执行,执行代码时,我会在IDE控制台中看到一个控制台提示,要求输入用户名和密码,如下所示:
Username [amitesh]:
然后我输入"sudo su -"
和用户“ amitesh”的密码。所以,现在我在IDE控制台上得到以下输出
CHANGED THE USER
amitesh
the id of the user is: 0
The current working directory is: /Users/amitesh/PycharmProjects/Automation/Databases
The new working directory is: /private/var/tmp
Process finished with exit code 0
从上面的输出中可以很明显地看出,该程序无法将用户更改为“ root”。
请帮助我找到我的错误。
谢谢