Run local python script on remote server Run local python script on remote server python python

Run local python script on remote server


It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

cat hello.py | ssh user@192.168.1.101 python -

Run python --help for more info.


Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

import sysimport osdef main():    print os.nameif __name__ == '__main__':    try:        if sys.argv[1] == 'deploy':            import paramiko            # Connect to remote host            client = paramiko.SSHClient()            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())            client.connect('remote_hostname_or_IP', username='john', password='secret')            # Setup sftp connection and transmit this script            sftp = client.open_sftp()            sftp.put(__file__, '/tmp/myscript.py')            sftp.close()            # Run the transmitted script remotely without args and show its output.            # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)            stdout = client.exec_command('python /tmp/myscript.py')[1]            for line in stdout:                # Process each line in the remote output                print line            client.close()            sys.exit(0)    except IndexError:        pass    # No cmd-line args provided, run script normally    main()

Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.


ssh user@machine python < script.py - arg1 arg2

Because cat | is usually not necessary