How to execute a script remotely in Python using SSH?

Posted on

Question :

How to execute a script remotely in Python using SSH?
def execute(self,command):
            to_exec = self.transport.open_session()
            print 'Command executed'

When I check the remote system, I found the script didn’t run. Any clue?

Asked By: Jack


Answer #1:

The code below will do what you want and you can adapt it to your execute function:

from paramiko import SSHClient
client = SSHClient()
client.connect(host, username=user)
stdin, stdout, stderr = client.exec_command('./')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()

Note, though, that commands will default to your $HOME directory, so you’ll either need to have in your $PATH or (most likely) you’ll need to cd to the directory that contains the script.

You can check your default path with:

stdin, stdout, stderr = client.exec_command('getconf PATH')
print "PATH: ", stdout.readlines()

However, if it is not in your path you can cd and execute the script like this:

stdin, stdout, stderr = client.exec_command('(cd /path/to/files; ./')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()

If the script is not in your$PATH you’ll need to use ./ instead of, just like you would if you were on the command line.

If you are still having problems after everything above it might also be good to check the permissions of the file, too:

stdin, stdout, stderr = client.exec_command('ls -la')
print "permissions: ", stdout.readlines()
Answered By: aculich

Answer #2:

ssh = paramiko.client.SSHClient()
ssh.connect(hostname=host, username=username, password = password)
chan = ssh.invoke_shell()

def run_cmd(cmd):    
    print('[CMD]', cmd)
    chan.send(cmd + 'n')
    buff = ''
    while chan.recv_ready():
        print('Reading buffer')
        resp = chan.recv(9999)
        buff = resp.decode()

        if 'password' in buff:
            chan.send(password + 'n')        

    print('Command was successful: ' + cmd)
Answered By: tnusraddinov

Answer #3:

subprocess.Popen('ssh thehost')

See the subprocess module.

Answered By: Matt Joiner

Leave a Reply

Your email address will not be published. Required fields are marked *