我正在尝试编写一个 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()
您没有三命令。您有 one 命令,即
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 因大输出而死亡/挂起。
强制性警告:请勿使用
AutoAddPolicy
– 这样做您将失去针对 MITM 攻击的保护。正确的解决方案请参阅Paramiko“未知服务器”。
问题是我试图使用 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)