Run python script function in remote machine - python

I have script in remote device and I want to run specific function in python script in remote device
remote device has below script:
#connect.py
class ConnectDevice:
def __init__(self, ip):
connect.Device(ip)
def get_devicestate(self):
state = show.Device_State
return state
configured password less connection from source machine to remote machine
function get_devicestate return up or down.
How to get get_devicestate output from source machine. source machine has below script:
import os
import sys
import time
import getpass
import errno
import json
import subprocess
import threading
from subprocess import call
from subprocess import check_output
call(["ssh", "1.1.1.1", "\"python Connect.py\""])#This is just example how to run script from source to remote. Need help how to run function get_devicestate and get value.

At a first glance , it seems that connect.py has got more code than you have pasted in your question. Anyways, assuming connect.py does not require any input parameters to run, simply use subprocess's check_output method to get the stdout message and store it in a variable for further use.
from subprocess import check_output
out = check_output(["ssh", "1.1.1.1", "\"python Connect.py\""])

Related

How to run python program automatically even if system restarted

I want to run my python API continuously (means program API will all-time active if call then it work) even if a system restarts my python API automatically restart.
I have API URL: http://localhost:8002/city_id_pred?id=1,2 through this URL calling python API.
Program:
import web
import pyodbc
import re
import numpy as np
#from wordcloud import WordCloud, STOPWORDS
from collections import Counter
from sklearn.externals import joblib
import pandas as pd
cnxn = pyodbc.connect('')
cursor = cnxn.cursor()
urls = (
'/city_id_pred?', 'Predict'
#'/', 'MyApplication'
)
class Predict(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
print("Start class...")
def GET(self):
#here prediction model
if __name__ == "__main__":
app = Predict(urls, globals())
app.run(port=8002)
Please suggest
Actually, I want to run on window server but currently using in windows OS.
As #Mubarak said, you basically want to convert it to a .exe and then add that .exe to startup.
I would recommend that you do this by using PyInstaller and then following this tutorial on how to add that .exe to your startup.
Following step will help you:
Make your python code like example.py
Convert example.py to example.exe file by using auto-py-to-exe https://pypi.org/project/auto-py-to-exe/
Open Task Schedular in your window system
Create Task->Gentral Tab ->Give Name,Location
Trigger Tab->Bigin the Task->On Startup
Hope this helps
Following given steps,.
1.Convert your python file to .exe format(https://pypi.org/project/auto-py-to-exe/)
Make simple batch file to run the .exe file which your python file.
#echo off
cd "C:\Program Files\Google\Chrome\Application\"
Start chrome.exe
start – "C:\Program Files\Microsoft Office\Office15\WINWORD.EXE"
"C:\Work\MUO\How to Batch Rename.docx"
cd "C:\Program Files (x86)\VMware\VMware Player"
start vmplayer.exe
exit
Hope your understood,....

Sharing a path string between modules in python

I am trying to make a gui that displays a path to a file, and the user can change it anytime. I have my defaults which are in my first script.The following is a simplified version without any of the gui stuff. But then the user pushes a button and it runs a different script (script2). In this script, the information on the file is read.
script1:
import os
import multiprocessing as mp
import script2
specsfile = mp.Array('c',1000, lock=True)
path_save = mp.Array('c',1000, lock=True)
p = mp.Process(target=script2, args=(specsfile,path_save))
p.start()
specsfile = '//_an_excel_sheet_directory.xlsx'
path_save = '//path/to/my/directory/'
subprocess.call([sys.executable, 'script2.py'])
script2:
import multiprocessing as mp
from script1 import specsfile
from script1 import path_save
print(specsfile)
spec= pd.read_excel(specsfile)
When I run it, it gives me this error: PermissionError: [WinError 5] Access is denied
I'm not sure if I'm initializing this wrong or not. I've never used multiprocessing but I was reading about some recommendations for that when sharing data. so basically I want to initialize a specsfile string and a path_save string but when it changes,I want it to be reflected and sent to specs2 file.

Mounted PATH Dependent import works through CLI, not through script

I have a python module called user_module, which resides in a mounted network location.
In a script I'm using, I need to import that module - but due to NFS issues, sometimes this path isn't available until we actually change directory to the relevant one and\or restarting autofs service.
In order to reproduce the issue and try to WA it - I've manually stopped autofs service, and tried to run my script with my WA - (probably not the most elegant one though):
import os
import sys
from subprocess import call
PATH="/some/network/path"
sys.path.append(PATH)
try:
os.chdir(PATH)
import user_module
except:
print "Unable to load user_module, trying to restart autofs service"
call(['service', 'autofs', 'restart'])
os.chdir(PATH)
import user_module # Throws Import error!
But, I still get import error due to path unavabilable.
Now this is what I find weird - On the same machine, I've tried executing the same operations as in my script, with intentionally pre stopping autofs service, and it works perfect -
[root#machine]: service autofs stop # To reproduce the import error
[root#machine]: python
>>> import os
>>> import sys
>>> from subprocess import call
>>> PATH="/some/network/path"
>>> sys.path.append(PATH)
>>> os.chdir(PATH)
######################################################################
################## exception of no such file or directory ############
######################################################################
>>> call(['service', 'autofs', 'restart'])
>>> os.chdir(PATH) # No exception now after restarting the service
>>> import user_module # NO Import error here
Can someone shed some light on the situation
and explain to me why same methodology works through python CLI, but through a script?
What is it that I don't know or what is it that I'm missing here?
Also - How to overcome this?
Thanks

Paramiko recv() works in the interactive mode but doesn't work inside script

I am trying to read banner from one of the switch using paramiko module in python. This is the code which i am using for the same
import socket
import sys
import paramiko
import subprocess
a=paramiko.SSHClient()
a.set_missing_host_key_policy(paramiko.AutoAddPolicy())
a.connect('10.22.158.19',username='admin',password='airwave')
b=a.invoke_shell()
b.recv_ready()
b.recv(1000)
When I run above I am not getting any output , but when i comment last line in the script and when i execute last command in shell b.recv(1000) is giving actual output
>>>
>>> b.recv(1000)
'Last login: Tue Aug 22 23:10:25 2017 from 10.20.14.150\r\r\n(AirwaveMM-19) [mynode] #'
>>>
Does anyone of you have any clue what is wrong here ?
You should write like this:
while not b.recv_ready():
time.sleep(0.1)
print b.recv(1000)
The recv_ready() function checks if data is ready but it does not wait for the data to be ready.

Finding a free port with a python component in Redhawk

I'm currently working on a project that requires I edit a configure file to replace an old standard port number if the port is being used. The code I'm currently using is the following:
import os
import sys
import socket
import select
import tempfile
import subprocess
import threading
import Queue
import time
import fileinput
...
def find_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",0))
s.listen(1)
tempport = s.getsocketname()[1]
s.close()
return tempport
When I run it from my Ubuntu machine (Python 2.7.6) , it runs fine, but on my CentOS 6 VM running in my Redhawk Component I get the following:
AttributeError: '_socketobject' object has no attribute 'getsocketname'
Not exactly sure why I'm getting this error. Python in Redhawk is running 2.6 I want to say?
Any clue as to why this would happen and how to fix?
Your code calls the method getsockname but your error says getsocketname, you sure you copied it right when writing it to Redhawk?

Categories