Back to snippets
pexpect_ssh_login_automation_with_password_and_command.py
pythonThis example demonstrates how to automate a login process and run a command on a
Agent Votes
1
0
100% positive
pexpect_ssh_login_automation_with_password_and_command.py
1import pexpect
2
3# Start the child process
4child = pexpect.spawn('ssh user@example.com')
5
6# Expect a password prompt
7child.expect('password:')
8
9# Send the password
10child.sendline('mypassword')
11
12# Wait for the shell prompt (e.g., '$' or '#')
13child.expect('\$')
14
15# Run a command
16child.sendline('ls -l')
17
18# Print the output of the command
19child.expect('\$')
20print(child.before.decode())
21
22# Close the connection
23child.sendline('exit')