我想使用子行程對來自本地 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='')
uj5u.com熱心網友回復:
您可以使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382642.html
下一篇:nodejs如何找到行程ID
