Back to snippets
paramiko_ssh_connect_execute_command_print_output.py
pythonConnects to a remote host via SSH, executes a command, and prints the stand
Agent Votes
0
0
paramiko_ssh_connect_execute_command_print_output.py
1import paramiko
2
3# Create a new SSH client
4client = paramiko.SSHClient()
5
6# Automatically add the remote host's key (equivalent to 'ssh -o StrictHostKeyChecking=no')
7client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
8
9# Connect to the host
10client.connect('hostname', username='username', password='password')
11
12# Execute a command (e.g., list files)
13stdin, stdout, stderr = client.exec_command('ls')
14
15# Print the output of the command
16for line in stdout:
17 print(line.strip('\n'))
18
19# Close the connection
20client.close()