SSH (Secure Shell) is a commonly used network protocol that securely passes communication between two computers. If a third party source were to intercept the transferred information, it would appear encrypted and unreadable. Automated server provisioning through the use of SSH is a common practice in an IT environment. I’ll be covering a simple Python script designed to connect and run a command on remote machines in Python using Paramiko.
Paramiko is a Python module that implements the SSH network protocol for secure connections to remote machines. It’s a great tool for those who prefer a more pythonic approach.
Paramiko Script
- Create a new file a name it
paramiko-script.py
. Then, start by importing the paramiko module.
import sys import paramiko
- Just for the purpose of the demo, create variables with arguments that will be passed to the script.
Note If you would like to authenticate using an RSA key (Pem key), please dokey = path_to_key.pem
.
user = sys.argv[1] hostname = sys.argv[2] password = sys.argv[3] command = sys.argv[4]
- Continue on with the script by writing code that establishes connection between the local and remote machines.
try: ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh_client.connect(user, hostname, password, pkey = key) stdin, stdout, stderr = ssh_client.exec_command(command) print stdout.read() ssh_client.close()
- Add any additional classes or functions, then save the script.
- Run
chmod +x paramiko-script.py
to make it executable. Finally, run the script with the necessary arguments.
Done! Paramiko opens the floor to a variety of commands that can be easily converted into the Python language.