BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

ssh remote run of a local file

python_logo




Bookmark and Share





bogotobogo.com site search:

Remote run

There are cases when we want to test our local code if it runs on remotely. Note that we run a local code not run a remote code after loading it at remote place. Also, we want to monitor the output from the remote run. So, in this chapter, we'll see how we can run our code remotely and get the outputs from it.

In this chapter, I used my server at http://www.bogotobogo.com/ as a remote location, and the virtual CentOS (Hypervisor: VMWare Workstation 10 ) is used as my local.

In summary, we have list of commands to be executed remotely and get the output file with log.


Shell script remote run

Here is our simple shell script:

# s.sh
uname -r
uptime

As a humble start, let's try a local run first:

$ ./s.sh
2.6.32-358.el6.x86_64
 14:25:38 up 4 days, 15:59,  2 users,  load average: 0.00, 0.00, 0.00

Then, remote run:

$ ssh bogotob1@bogotobogo.com < ./s.sh
Pseudo-terminal will not be allocated because stdin is not a terminal.
bogotob1@bogotobogo.com's password:
3.12.26.1407184750
 23:14:59 up 67 days, 14 min,  1 user,  load average: 42.36, 30.37, 28.13



A python sample I - remote run

Our python code:

# s.py
#!/usr/bin/python
import subprocess

cmd_list = ['uname -r', 'uptime']

out = []
err = []

for cmd in cmd_list:
    args = cmd.split()
    proc = subprocess.Popen(args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    (stdoutdata, stderrdata) = proc.communicate()
    out.append(stdoutdata)
    err.append(stderrdata)

print 'out=',out
print 'err=',err

The following way of remote run won't work:

$ ssh bogotob1@bogotobogo.com python s.py
bogotob1@bogotobogo.com's password:
python: can't open file 's.py': [Errno 2] No such file or directory

However, if we run it this way, we can do remote run:

$ cat s.py  | ssh bogotob1@bogotobogo.com python -
bogotob1@bogotobogo.com's password:
out= ['3.12.26.1407184750\n', ' 16:01:11 up 67 days, 17:00,  1 user,  load average: 19.17, 22.79, 22.32\n']
err= ['', '']

Or another remote run will work if we run it this way:

$ ssh bogotob1@bogotobogo.com python < ./s.py
bogotob1@bogotobogo.com's password:
out= ['3.12.26.1407184750\n', ' 16:48:29 up 67 days, 17:47,  1 user,  load average: 28.73, 23.32, 20.98\n']
err= ['', '']




A python sample II - remote run

This time, we run a list of three scripts in a python (s.py):

['python uname.py', 'sh uptime.sh', 'perl hello.perl']

The s.py code looks like this:

# s.py 
#!/usr/bin/python
import subprocess

cmd_list = ['python uname.py', 'sh uptime.sh', 'perl hello.perl']

out = []
err = []

for cmd in cmd_list:
    args = cmd.split()
    print 'args=',args
    proc = subprocess.Popen(args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    (stdoutdata, stderrdata) = proc.communicate()
    out.append(stdoutdata)
    err.append(stderrdata)

print 'out=',out
print 'err=',err

If we try to run this remotely, we get an error like this:

$ cat s.py  | ssh bogotob1@bogotobogo.com python -
bogotob1@bogotobogo.com's password:
args= ['python', 'uname.py']
args= ['sh', 'uptime.sh']
args= ['perl', 'hello.perl']
out= ['', '', '']
err= ["python: can't open file 'uname.py': [Errno 2] No such file or directory\n", 'sh: uptime.sh: No such file or directory\n', 'Can\'t open perl script "hello.perl": No such file or directory\n']

The error occurred because the code thinks the scripts reside locally. So, we need to run each one remotely using ssh.





A python sample III - remote run using os.system

So, each command should be run like this:

$ ssh bogotob1@bogotobogo.com python < uname.py
bogotob1@bogotobogo.com's password:
3.12.26.1407184750

However, still the following program does not work. It remote shell still thinks the three codes (['uname.py', 'uptime.sh', 'hello.pl']) are local to it (meaning, they reside at remote location):

# s2.py
#!/usr/bin/python
import subprocess, sys, argparse

def check_arg(args=None):
    parser = argparse.ArgumentParser(description='Script to learn basic argparse')
    parser.add_argument('-H', '--host',
                        help='host ip',
                        required='True',
                        default='localhost')
    parser.add_argument('-u', '--user',
                        help='user name',
                        default='root')

    return parser.parse_args(args)

def remote_run(arguments):
    host = arguments.host
    user = arguments.user

    cmd_list = ['uname.py', 'uptime.sh', 'hello.pl']
    exe = {'py':'python', 'sh':'sh', 'pl':'perl'}

    out = []
    err = []

    ssh = ''.join(['ssh ', user, '@',  host, ' '])
    for cmd in cmd_list:
        type = exe[cmd.split('.')[1]]
        cmd = ssh + type + ' < ' + cmd
        args = cmd.split()
        print 'args=',args
        proc = subprocess.Popen(args,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        (stdoutdata, stderrdata) = proc.communicate()
        out.append(stdoutdata)
        err.append(stderrdata)

    print 'out=',out
    print 'err=',err

if __name__ == '__main__':
    args = check_arg(sys.argv[1:])
    remote_run(args)

Output:

$ python s2.py -H 173.254.28.78 -u bogotob1
args= ['ssh', 'bogotob1@173.254.28.78', 'python', '<', 'uname.py']
bogotob1@173.254.28.78's password:
args= ['ssh', 'bogotob1@173.254.28.78', 'sh', '<', 'uptime.sh']
bogotob1@173.254.28.78's password:
args= ['ssh', 'bogotob1@173.254.28.78', 'perl', '<', 'hello.pl']
bogotob1@173.254.28.78's password:
out= ['', '', '']
err= ['bash: uname.py: No such file or directory\n', 'bash: uptime.sh: No such file or directory\n', 'bash: hello.pl: No such file or directory\n']

But this simple code using os.system() instead of subproccee.Popen() seems to be working:

# s3.py
#!/usr/bin/python
import os

os.system('ssh bogotob1@bogotobogo.com python < uname.py')
os.system('ssh bogotob1@bogotobogo.com sh < uptime.sh')
os.system('ssh bogotob1@bogotobogo.com perl < hello.pl')
$ python s3.py
bogotob1@bogotobogo.com's password:
3.12.26.1407184750
bogotob1@bogotobogo.com's password:
 22:40:06 up 67 days, 23:39,  1 user,  load average: 21.00, 23.46, 22.55
bogotob1@bogotobogo.com's password:
Hello world from perl




A python sample IV : remote run with output redirection

If we want to get std output and error as a file from the run, the following code will do that for us ($ python s4.py):

# s4.py
#!/usr/bin/python
import os

os.system('ssh bogotob1@bogotobogo.com python < uname.py >> mylog.txt 2>&1')
os.system('ssh bogotob1@bogotobogo.com sh < uptime.sh >> mylog.txt 2>&1')
os.system('ssh bogotob1@bogotobogo.com perl < hello.pl >> mylog.txt 2>&1')

'mylog.txt' looks like this:

3.12.26.1407184750
 13:51:37 up 68 days, 14:50,  0 users,  load average: 12.23, 18.70, 19.22
Hello world from perl

# s5.py
#!/usr/bin/python
import os, subprocess, sys, argparse

def check_arg(args=None):
    parser = argparse.ArgumentParser(description='Script to learn basic argparse')
    parser.add_argument('-H', '--host',
                        help='host ip',
                        required='True',
                        default='localhost')
    parser.add_argument('-u', '--user',
                        help='user name',
                        default='root')

    return parser.parse_args(args)

def remote_run(arguments):
    host = arguments.host
    user = arguments.user

    cmd_list = ['uname.py', 'uptime.sh', 'hello.pl']
    exe = {'py':'python', 'sh':'sh', 'pl':'perl'}

    ssh = ''.join(['ssh ', user, '@',  host, ' '])
    for cmd in cmd_list:
        type = exe[cmd.split('.')[1]]
        cmd = ssh + type + ' < ' + cmd + '>> mylog.txt 2>&1'
        '''
        args = cmd.split()
        print 'args=',args
        proc = subprocess.Popen(args,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        (stdoutdata, stderrdata) = proc.communicate()
        out.append(stdoutdata)
        err.append(stderrdata)
        '''
        os.system(cmd)

if __name__ == '__main__':
    args = check_arg(sys.argv[1:])
    remote_run(args)

Output:

$ python s5.py -H 173.254.28.78 -u bogotob1
cmd= ssh bogotob1@173.254.28.78 python < uname.py>> mylog.txt 2>&1
bogotob1@173.254.28.78's password:
cmd= ssh bogotob1@173.254.28.78 sh < uptime.sh>> mylog.txt 2>&1
bogotob1@173.254.28.78's password:
cmd= ssh bogotob1@173.254.28.78 perl < hello.pl>> mylog.txt 2>&1
bogotob1@173.254.28.78's password:




A python sample V : remote running commands after reading in those commands
# s6.py
#!/usr/bin/python
import os, subprocess, sys, argparse

def check_arg(args=None):
    parser = argparse.ArgumentParser(description='Script to learn basic argparse')
    parser.add_argument('-H', '--host',
                        help='host ip',
                        required='True',
                        default='localhost')
    parser.add_argument('-u', '--user',
                        help='user name',
                        default='root')

    return parser.parse_args(args)

def remote_run(arguments):
    host = arguments.host
    user = arguments.user

    cmd_list = []
    with open('commands.txt', 'rb') as f:
        for c in f:
            cmd_list.append(c.replace('\n','').replace('\r','').rstrip())

    exe = {'py':'python', 'sh':'sh', 'pl':'perl'}

    ssh = ''.join(['ssh ', user, '@',  host, ' '])
    for cmd in cmd_list:
        type = exe[cmd.split('.')[1]]
        cmd = ssh + type + ' < ' + cmd + '>> mylog.txt 2>&1'
        os.system(cmd)

if __name__ == '__main__':
    args = check_arg(sys.argv[1:])
    remote_run(args)

Output:

]$ python s6.py -H 173.254.28.78 -u bogotob1
bogotob1@173.254.28.78's password:
bogotob1@173.254.28.78's password:
bogotob1@173.254.28.78's password:

And the file output, 'mylog.txt':

3.12.26.1407184750
 16:16:23 up 68 days, 17:15,  0 users,  load average: 10.43, 12.55, 15.23
Hello world from perl








Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...








Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm




Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master