Playbooks

Python Script to SSH and Run Commands

Here’s an example of how you can use Python to SSH into a remote server and run commands.

import paramiko

# create an SSH client object
ssh = paramiko.SSHClient()

# automatically add the remote server's SSH key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect to the remote server
ssh.connect(hostname='hostname', username='username', password='password')

# run a command on the remote server
stdin, stdout, stderr = ssh.exec_command('ls')

# print the output of the command
print(stdout.read().decode())

# close the SSH connection
ssh.close()

This code uses the paramiko library to handle the SSH connection. The paramiko.SSHClient object is created to handle the connection, and the set_missing_host_key_policy method is used to automatically add the remote server’s SSH key to the client’s known_hosts file. The connect method is used to connect to the remote server, and the exec_command method is used to run a command on the remote server. The output of the command is printed using the stdout.read().decode() method. Finally, the close method is used to close the SSH connection.

PyJoy

Recent Posts

Python Script to Monitor Network Traffic

Here is a simple Python script to monitor network traffic. import psutil def monitor_network(): #…

2 years ago

Python Script for Web Scraping

Here's a basic example of web scraping in Python using the requests and BeautifulSoup libraries:…

2 years ago

Python Code Example with Classes

Here's an example of a Python class that represents a rectangle: class Rectangle: def __init__(self,…

2 years ago

Python Script Example with Main Method in Active Directory

Here is a simple Python script that interacts with Active Directory (AD) using the pyad…

2 years ago

Python Script Example for System Administrators

Here's a Python script to monitor disk usage on a system and send an email…

2 years ago

How to Run a Python Script on Mac

Running a Python script on a Mac is a relatively straightforward process that can be…

2 years ago