Python paramiko在用户名“后面输入“yes”,然后输入密码

yshpjwxd  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(383)

我知道我的问题可能已经张贴在堆栈溢出的地方,但我找不到答案。
我正在尝试自动SSH登录到服务器。当我输入用户名时,服务器会发送一个提示“Do you accept and acknowledge the statement above?(yes/no):“,我必须键入“yes”,然后键入密码。x1c 0d1x
我不知道如何在Python中发送yes和password。下面是我的代码。:

import paramiko
ip_address = "1.1.1.1"
username = "abc"
password = "1234" 
# Define the list of show commands to execute
show_commands = ["show interfaces", "show routing table", "show system info"]
# Create an SSH client object
ssh = paramiko.SSHClient()
# Automatically add the Palo Alto firewall's SSH key to the local key store
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the Palo Alto firewall using SSH
ssh.connect(hostname=ip_address, username=username, password=password)
# Execute each show command and print its output
for command in show_commands:
     stdin, stdout, stderr = ssh.exec_command(command)
     output = stdout.read().decode()
print(f"Output of '{command})':")
print(output)
print("-" * 50)
# Close the SSH connection
ssh.close()
5t7ly7z5

5t7ly7z51#

为了自动化发送“yes”到提示符然后发送密码的过程,您可以尝试使用paramiko库沿着pexpect库. pip install pexpect提供的expect方法。至于您的代码,您可以尝试以下更改。

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_session = pexpect.spawn(f"ssh {username}@{ip_address}")

# Wait for the prompt and send 'yes'
ssh_session.expect("Do you accept and acknowledge the statement above ? (yes/no) :")
ssh_session.sendline("yes")

# Wait for the password prompt and send the password
ssh_session.expect("password:")
ssh_session.sendline(password)

# Wait for the shell prompt
ssh_session.expect("#")

# Execute each show command and print its output
for command in show_commands:
    ssh_session.sendline(command)
    ssh_session.expect("#")
    output = ssh_session.before.decode()
    print(output)
ssh_session.sendline("exit")
ssh_session.close()

相关问题