Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python script to ssh to server and run command

#!/usr/bin/python

import os
import sys
import select
import paramiko
import time


class Commands:
    def __init__(self, retry_time=0):
        self.retry_time = retry_time
        pass

    def run_cmd(self, host_ip, cmd_list):
        i = 0
        while True:
        # print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time))
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host_ip)
            break
        except paramiko.AuthenticationException:
            print("Authentication failed when connecting to %s" % host_ip)
            sys.exit(1)
        except:
            print("Could not SSH to %s, waiting for it to start" % host_ip)
            i += 1
            time.sleep(2)

        # If we could not connect within time limit
        if i >= self.retry_time:
            print("Could not connect to %s. Giving up" % host_ip)
            sys.exit(1)
        # After connection is successful
        # Send the command
        for command in cmd_list:
            # print command
            print "> " + command
            # execute commands
            stdin, stdout, stderr = ssh.exec_command(command)
            # TODO() : if an error is thrown, stop further rules and revert back changes
            # Wait for the command to terminate
            while not stdout.channel.exit_status_ready():
                # Only print data if there is data to read in the channel
                if stdout.channel.recv_ready():
                    rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0)
                    if len(rl) > 0:
                        tmp = stdout.channel.recv(1024)
                        output = tmp.decode()
                        print output

        # Close SSH connection
        ssh.close()
        return

def main(args=None):
    if args is None:
        print "arguments expected"
    else:
        # args = {'<ip_address>', <list_of_commands>}
        mytest = Commands()
        mytest.run_cmd(host_ip=args[0], cmd_list=args[1])
    return


if __name__ == "__main__":
    main(sys.argv[1:])
Comment

python how to run code in ssh

stdout = client.exec_command('python -c "exec("' + open('hello.py','r').read().encode('base64').strip('
') + '".decode("base64"))"' )[1]
Comment

PREVIOUS NEXT
Code Example
Python :: why is c faster than python 
Python :: how to run other python files in python 
Python :: path in python 
Python :: print variable python 
Python :: perfect numbers python 
Python :: how to test that an exception was raise using pytest 
Python :: NaN stand for python 
Python :: generator expression 
Python :: string pythhon 
Python :: instance of object 
Python :: sum python 
Python :: python 3.8 release date 
Python :: linked list python 
Python :: add column to dataframe pandas 
Python :: python sort based on multiple keys 
Python :: how to create multiple columns after applying a function in pandas column python 
Python :: python3 -m venv venv 
Python :: get element by index in list python 
Python :: django cache framework 
Python :: python program to find sum of array elements 
Python :: buble short 
Python :: display list 
Python :: reverse sublist of linklist 
Python :: pandas math operation from string 
Python :: Fifth step Creating Advance app in python django 
Python :: d2h recharge plan list 2022 telugu 
Python :: tz convert python 
Python :: decompress_pickle 
Python :: multiple channel creating command in discord.py 
Python :: python how to be able to use any python file you made on all projects 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =