I am trying to create a program for a project of mine where I needed to copy some files from my local machine to some remote desktop pc's desktop directory. It is a part of automating the whole connecting and copying files to all the remote PCs. I have used subprocess to connect to a remote desktop. As I am a beginner of using subprocess or cmd commands, I am unable to find a way to do this. This is the code:
from pynput.keyboard import Key,Controller
import time
import subprocess
def process_exists(process_name):
call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
output = subprocess.check_output(call)
last_line = output.decode("utf-8").strip().split('\r\n')[-1]
return last_line.lower().startswith(process_name.lower())
#os.system('cmd /k "mstsc /v:192.168.0.107"')
#os.system('cmd /c "notepad"')
from subprocess import Popen
p = Popen('mstsc /v:192.168.0.107')
time.sleep(1)
keyboard = Controller()
# Password is given here
for i in range(10):
if process_exists('mstsc.exe'):
time.sleep(1)
keyboard.type("**********")
keyboard.press(Key.enter)
time.sleep(0.12)
break
time.sleep(3)
Here I used subprocess just to connect to that remote PC. I tried
Popen(r'copy /Y "E:\test.jar" "\\192.168.0.107\c\"')
But it didn't help. Though I didn't know the basic of this line. The error it showed was:
FileNotFoundError: [WinError 2] The system cannot find the file specified
This code is only for test, that's why I used only time delay, didn't check whether it ran correctly.
The remote desktop started successfully. But unable to start the copying process.
Sorry for my bad English. Thanks in advance
Related
The principle of the script is that it should connect from one virtual machine to another via an SSH connection and generate a certain number of folders.
The script runs, but when executed, generates folders on the host machine.
import os
from paramiko import SSHClient, AutoAddPolicy
from sys import argv
address = argv[1]
port = int(argv[2])
name = argv[3]
path = argv[4]
prefix = argv[5]
counts = int(argv[6])
mode = int(argv[7])
def generateFolders(path, prefix, counts, mode):
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
os.mkdir(pth, mode)
command = generateFolders(path, prefix, counts, mode)
print(address)
client1 = SSHClient()
client1.set_missing_host_key_policy(AutoAddPolicy())
client1.connect(address, username=name, password='1')
stdin, stdout, stderr = client1.exec_command(command)
print(stdout.read())
client1.close()
The command in the terminal
But without a script, I can connect to another virtual machine
Jane, its making dirs on your local box because that is where the python script is running.
I suggest you look at this question and answer.
In that QandA, they show how to use ssh on the local box to execute commands on a remote box. You could use your existing code as the code which is run on the remote box using the above as your guide.
Specifically this this one
The os.mkdir creates folders on the local machine. It won't magically start working on a remote machine only because you have previous opened SSH connection to that machine (and you actually even did not, as you open it only after calling os.mkdir).
To create a folder on a remote machine via Paramiko module, use SFTPClient.mkdir.
sftp = client1.open_sftp()
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
sftp.mkdir(pth, mode)
Though you should not use os.path on SFTP paths as your code will break, if run on Windows and other platforms, that does not use / as a path separator. And os.path.expanduser will of course expand ~ to local user home. I do not think you want that.
Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
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,....
I have a boot controller which runs a boot.py file contained in each folder of each tool i am trying to deploy. I want my boot controller to run all of these boot files simultaneously. The config file has the tool names and the versions desired, which help to generate the path to the boot.py.
def run_boot():
config_file = get_config_file()
parse_config_file.init(config_file)
tools = parse_config_file.get_tools_to_deploy()
#tools is now a list of tool names
top_dir = os.getcwd()
for tool in tools:
ver = parse_config_file.get_tool_version(tool).strip()
boot_file_path = "{0}\\Deploy\\{1}\\{2}".format(os.getcwd(),tool,ver)
try:
subprocess.Popen('boot.py', shell=True, cwd=boot_file_path)
except:
print ("{0} failed to open".format(tool))
print(tool, boot_file_path)
os.chdir(top_dir)
The first time i run this, the print(tool, boot_file_path) executes but the processes do not. the second time it is run the processes do open. I cannot find a reason for this.
Objective:
I am using Ubuntu 16.04 and am using WMI-CLient-Wrapper module to connect to a remote Windows Machine and send an executable to it(eg. Process Explorer) and further execute it and collect the logs it creates and fetch them back to my Linux Machine for further processing. Using WMI CLient Wrapper is the only option available as WMI Module doesn't work with Linux.
Problem:
I am able to send the file to the remote Windows machine, by establishing a connection using WMI-Client-Wrapper and SMB File Transfer Mechanism. After that when I try to create a Process for the same and try to execute that process it gives me an error stating that some of the attributes that WMI actually has, are not supported by WMI client Wrapper.
What I tried
Python Code:
import os
import wmi_client_wrapper as wmic
from socket import *
import time
wmic = wmic.WmiClientWrapper(
host ="192.168.115.128",
username = "LegalWrongDoer",
password = "sasuke14"
)
SW_SHOWNORMAL = 1
str = "smbclient //192.168.115.128/C$ -U LegalWrongDoer%sasuke14 -c \'put \"procexp64.exe\"\'"
os.system(str)
print("Folder sent")
process_startup = wmic.Win32_ProcessStartup.new()
process_startup.ShowWindow = SW_SHOWNORMAL
process_id, result = wmic.Win32_Process.Create(CommandLine="C:/procexp64.exe", ProcessStartupInformation=process_startup)
process_startup.ShowWindow = SW_SHOWNORMAL
if result == 0:
print("Process started successfully")
else:
print("Sorry, but can't execute Process!")
When I run this python file, it gives me the output to the initial query I make. But the Process_StartUp fails.
Further Traceback Calls:
Traceback (most recent call last):
File "WMIClient.py", line 22, in <module>
process_startup = wmic.Win32_ProcessStartup.new()
AttributeError: 'WmiClientWrapper' object has no attribute 'Win32_ProcessStartup'
I'd be extremely grateful if anyone of you can be able to help me through this. Thanks in advance :)
Well I finally managed to get a work-around for this whole scenario, and it might look a little messy but it sure does work for me.
Firstly I use smbclient to transfer the executable to the end-point where I want to execute it. Inside my code I use os.system() calls to make this happen.
import os
str1 = "smbclient //'<HostMachineIP>'/admin$ -U '<domain>\\<username>%<password>' -c \'lcd /usr/local/acpl/bin/endPoint/; put \"EndPointForeignsics.exe\"\'"
os.system(str1)
This helps me put the executable in desired shared folder that the user has access(Admin in my case) to and then use WMI-query through a tool called Winexe to get access to the console/command prompt of the end-point. I use another os.system() call to execute this again.
str2 = r'/usr/local/bin/winexe -U "<domain>\\<username>%<password>" //<HostMachineIP> "cmd /c c:\windows\EndPointForeignsics.exe '
os.system(str2)
P.S:-- Winexe is a tool that you'll have to download off the internet and compile it. It may take some time and effort to do that, but is quite achievable. You'll get a lot of help on the same from StackOverflow and Documentation of the tool.
I am writing a program in python on Ubuntu, to remove a file from remote machine(raspberrypi) by accessing it, connected with network.
For file selection I am using a command called askopenfilename.
But I am struggling in specifying the Path of RaspberryPi correctly.
Can you please guide me on how do I specify Raspberrypi path correctly?
IP = "192.168.2.34"
Username = "pi"
Password ="raspberry"
Path="/home/pi/python"
Below is my code
from tkFileDialog import askopenfilename
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')
checkdir = "/home/pi/python"
name1= askopenfilename(title = "Select File For Removal", initialdir = checkdir)
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
print '... ' + line.strip('\n')
client.close()
I am fairly sure the tk file dialog is only able to browse the Ubuntu machine (which it seems to run on) filesystem - not the RPi filesystem over SSH, so you will never see RPi directories.
if You can read the RPi directory listing there, so you could create your own file browser component or try to find an existing one that works over SSH.
Then again it looks like you are 'inventing the wheel again' (which of course is ok for learning purposes) - gFTP, FileZilla, many of the Linux desktop file browsers etc. (or WinSCP if you were using a Windows box) are ready made tools for this.