Python Classroom Series – 11/Sept/2020

Using Standard Python to Automate Administrative Activities

  • Lets create a linux vm in AWS Refer Here
  • Ensure python3 is installed
sudo apt-get update
sudo apt-get install python3 -y
sudo apt install python3-pip -y

Python Programs which accept input by pipe in linux

  • Create a python program to calculate the square of the number
 echo 15 | python3 square.py
225
  • The input by pipe is another form of redirection, To accept this use sys module as shown below
#!/usr/bin/env python3

import sys

if __name__ == "__main__":
    for number in sys.stdin:
        value = int(number.strip())
        print(value*value)

Write a python script to verify ssh connection

  • To connect using ssh lets use Parmiko library over here
  • The code developed is
#!/usr/bin/env python3
![Preview](https://learningthoughts.academy/wp-content/uploads/2020/09/python1.png)
from paramiko import SSHClient, AutoAddPolicy


def check_ssh_connection(ipaddress, username, password):
    """
    This function will accept host details
    :param ipaddress: ipaddress of the host
    :param username: username of the host
    :param password: password of the host
    :return: True if connected false otherwise
    """
    ssh_client = SSHClient()
    ssh_client.set_missing_host_key_policy(AutoAddPolicy())
    ssh_client.load_system_host_keys()
    ssh_client.connect(hostname=ipaddress, username=username, password=password)
    ssh_client.close()
    return True


if __name__ == "__main__":
    if check_ssh_connection(ipaddress='54.212.181.50', username='testuser', password='testuser'):
        print("success")
    else:
        print("failed to connect")

  • Will it not be good if our program is some thing like
python check_ssh.py --username "testuser" --password "testuser"
  • Note: Code is available at Here

Next Steps

  • How to create a python program which accepts arguments from command line
  • How to write a python program which executes external tools in os

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin