Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python ssh connection

import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
    print "SSH session failed on login."
    print str(s)
else:
    print "SSH session login successful"
    s.sendline ('mycommand')
    s.prompt()         # match the prompt
    print s.before     # print everything before the prompt.
    s.logout()
    
#We can also execute multiple command like this:
s.sendline ('uptime;df -h')
Comment

python ssh into server

import paramiko

host = "YOUR_IP_ADDRESS"
username = "YOUR_LIMITED_USER_ACCOUNT"
password = "YOUR_PASSWORD"

client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
_stdin, _stdout,_stderr = client.exec_command("df")
print(stdout.read().decode())
client.close()
Comment

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

PREVIOUS NEXT
Code Example
Python :: django create new project 
Python :: float to string python 
Python :: os.chdir python 
Python :: program count the number of occurrences of a letter in a string python 
Python :: how to add rows to empty dataframe 
Python :: remove keys from dict python 
Python :: df to csv 
Python :: set value based on column 
Python :: python make a dictionary 
Python :: repeat array along new axis 
Python :: shuffle list 
Python :: joining pandas dataframes 
Python :: skip element in list comprehension 
Python :: pandas select a row 
Python :: iterate through characters in a string python 
Python :: python add to file 
Python :: django error table already exists 
Python :: beautiful soup get class name 
Python :: python list prime numbers 
Python :: how to fix Crypto.Cipher could not be resolved in python 
Python :: how to use if else in lambda python 
Python :: Select rows in pandas MultiIndex DataFrame 
Python :: ImportError: dynamic module does not define module export function 
Python :: user input python 
Python :: radix sort in python 
Python :: flask port 
Python :: python dict to dataclass 
Python :: how to use global variable in python 
Python :: ssl django nginx 
Python :: remove item from list python 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =