使用python脚本从本地linux主机验证用户



我想使用子进程从本地linux主机验证用户。我使用过这段代码,我怀疑login是一个完美的命令,因为登录命令会提示输入密码,我想提前提供密码。登录人员

如果不是login,那么我是否可以通过任何其他linux命令对本地用户进行身份验证?

#!/usr/bin/python3
import subprocess
import cgi
print()
cred = cgi.FieldStorage()
username = cred.getvalue("user")
password = cred.getvalue("password")
# print(username)
# print(password)
cmd = f"echo {password} | sudo /usr/bin/login {username}"
# cmd = "ls -la"
print(cmd)
output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
print(output)

这是我现在得到的输出。

CompletedProcess(args='echo ashu234 | sudo /usr/bin/login ashu', returncode=1, stdout='')

您可以使用pexpect。除非您以root用户身份运行脚本,否则您将需要为sudo提供密码(对于任何使用sudo的答案,您都必须这样做(。为了使脚本更具可移植性,还提供了一个sudo用户名,但如果使用root,则可以对其进行硬编码。这段代码是为Ubuntu 21.10编写的,可能需要为其他发行版更新字符串。我认为代码是不言自明的,你生成一个进程,与它交互,并期望在执行过程中得到某些响应。

import pexpect
sudo_user = 'whatever your sudo user name is'
sudo_password = "whatever your sudo user password is"
user_name = "whatever local user name is"
password = "whatever local user password is"
child = pexpect.spawn(f'/usr/bin/sudo /usr/bin/login {user_name}', encoding='utf-8')
child.expect_exact(f'[sudo] password for {sudo_user}: ')
child.sendline(sudo_password)
return_code = child.expect(['Sorry, try again', 'Password: '])
if return_code == 0:
print('Can't sudo')
print(child.after)  # debug
child.kill(0)
else:
child.sendline(password)
return_code = child.expect(['Login incorrect', '[#\$] '])
if return_code == 0:
print('Can't login')
print(child.after)  # debug
child.kill(0)
elif return_code == 1:
print('Login OK.')
print('Shell command prompt', child.after)

有关更多详细信息,请参阅文档https://pexpect.readthedocs.io/en/stable/overview.html

最新更新