Paramiko SSH

November 4, 2017

Some times you need to do a routine process such as connecting to your server execute a series of command but that would suck everytime you do it manually.

I have use written the following snippet to make life less miserable, maybe that work for you too.

#!/usr/bin/env python
from sys import stdout
import paramiko
import sys

def {Function_Name}():
    trans = paramiko.Transport('{SERVER_IP}')
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    conn = ssh.connect('{SERVER_IP}',username='{USERNAME}',password='{PASSWORD}')
    trans.connect(conn)
    ''' Enter your desire command'''
    cmd = 'source ~/.profile ;cd //path/to/folder ; pkexec shutdown , lsblk, etc'   ### in here you can execute a series of commands
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print stdout.read()

Sometimes you need to upload some files into your server and below is the simple fucntion to do so.

#!/usr/bin/env python
import pysftp

def uploader():
    with pysftp.Connection('{SERVER_IP}', username='{USERNAME}', password='#{PASSWORD}') as sftp:
        sftp.cwd('/PATH/TO/THE/FOLDER')
        sftp.put(raw_input("Please Select Your file :\n"))
        sftp.close()