【问题标题】:authenticate a user from local linux host using python script使用 python 脚本从本地 linux 主机验证用户
【发布时间】:2022-01-17 20:40:04
【问题描述】:

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

如果不是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='')

【问题讨论】:

标签: python-3.x linux subprocess cgi


【解决方案1】:

您可以使用 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

【讨论】:

  • @DanDev 感谢您提供的信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
相关资源
最近更新 更多