[英]Executing passwd command in Python Paramiko to change a password on a Linux server
我正在嘗試編寫一個 Python 3 腳本以實用地 ssh 進入 Linux 服務器並更改密碼。 我已經使用 Paramiko 模塊將腳本放在一起。
我在嘗試運行多個 shell 命令時遇到問題。 我的腳本嘗試執行命令,但 Paramiko 在執行一個 shell 命令后超時。
這是我目前正在處理的腳本。 任何見解將不勝感激。
import paramiko
def change_pw():
hostname = "IP" #IP Address of Linux Server
username = "root" #username
password = "oldpw!" #password for Linux Server
#NOTE - This variable is suppose to define 3 shell commands. I do not believe the script is sending these commands as listed because the password does not update.
commands = [
"passwd",
"newpw!",
"newpw!"
]
#NOTE - Attempted to utilize '\n' to execute multiple commands and failed
# commands = [
# "passwd \n newpw! \n newpw!"
# ]
# initialize the SSH clientp0-
client = paramiko.SSHClient()
# add to known hosts
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname, username=username, password=password)
except:
print("[!] Cannot connect to the SSH Server")
exit()
# execute the commands
for command in commands:
print("="*50, command, "="*50)
stdin, stdout, stderr = client.exec_command(command)
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print(err)
change_pw()
您沒有三個命令。 您有一個命令passwd
,它需要兩行輸入。
這兩個問題展示了如何使用 Paramiko 為命令提供輸入:
因此,專門針對passwd
,您需要使用:
stdin, stdout, stderr = client.exec_command('passwd')
# answer the new password prompts
stdin.write('newpw\n')
stdin.write('newpw\n')
stdin.flush()
# wait for the command to complete a print the output
stdout.channel.set_combine_stderr(True)
print(stdout.read().decode())
對於Channel.set_combine_stderr
,請參閱Paramiko ssh die/hang with big output 。
強制性警告:不要使用AutoAddPolicy
這樣做會失去對MITM 攻擊的保護。 有關正確的解決方案,請參閱Paramiko "Unknown Server" 。
問題是我試圖使用 3 個輸入命令來更改 root 的密碼。 我只需要調用 passwd 命令,然后為“輸入新密碼”和“確認新密碼”傳遞兩個輸入變量
import paramiko
import time
hostname = 'IP'
username = 'root'
password = 'oldpw'
commands = ['passwd']
# initialize the SSH clientp
client = paramiko.SSHClient()
# add to known hosts
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname, username=username, password=password)
except:
print("[!] Cannot connect to the SSH Server")
exit()
# execute the commands
for command in commands:
print("="*50, 'PW change executed', "="*50)
stdin, stdout, stderr = client.exec_command(command)
stdin.write('newpw' '\n' 'newpw' '\n') #input varuables for "Enter new PW" and "re-enter new PW"
stdin.flush()
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print(err)
嘗試相同但使用 sudo 命令。 沒有任何成功
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.