I am trying to access a test text file on a server with the command os.startfile but I can't seem to make it work. I know it only fails because the text file is on the server and not on the computer but I have no idea how to access it.
Here's my code :
from os import startfile
path = "//10.2.30.61/c$/Qlikview_Tropal/Raport/test1.txt"
startfile("//10.00.00.00/c$/test/test1/test1.txt")
And I get this error : FileNotFoundError: [WinError 2]. I am on windows by the way.
Update_1 : I tried the enter os.startfile(os.path.normpath()) and i get this error : "filenotfounderror winerror 53 the network path was not found"
Thank you !!
You can do
from os import start file
#put two \\ to get one \
path = "\\\\10.2.30.61\\c$\\Qlikview_Tropal\\Raport\\test1.txt"
startfile(r"\\10.00.00.00\c$\test\test1\test1.txt")
https://stackoverflow.com/a/43205543/14579156
Related
My python progam is creating wrong file path.
The file path formed is wrong : '/autocameratest2\data\TestImages/7_vw_test.png'
The correct file path should be: '/autocameratest2/data/TestImages/7_vw_test.png'
The file path is fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '/autocameratest2\\data\\TestImages/7_vw_test.png'
172.17.0.1 - - [05/Feb/2022 17:34:22] "POST /places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png HTTP/1.1" 500 -
In the python api program, the below URL
http://127.0.0.1:5000/places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png
returns a json file. The code works fine in VisualStudio code or outside docker. It python code give a path problem inside docker.
image1test_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2\data\TestImages',image1test)
image2perfect_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2\data\TestImages',image2perfect)
test_results = generate_report(camid, image1test_path, image2perfect_path)
test_names = ['CamId','Blur','check_scale','noise','scrolled','allign','mirror','blackspots','ssim_score','staticlines','rotation_deg']
Use pathlib, python's path parsing library, it has linux, windows type paths. You can freely manipulate between them.
Your problem is that docker runs on linux unless told otherwise, linux uses / for path and windows \, thus the issue.
pathlib.Path will help you.
>>> import pathlib
>>> pathlib.Path("xxx/yyy\iii.z")
WindowsPath('xxx/yyy/iii.z')
The following approach helped my create a file path that I wanted. like this "/autocameratest2/data/TestImages"
image1test_path = os.path.join('data','TestImages',image1test)
image2perfect_path = os.path.join('data','TestImages',image2perfect)
Other techniques which I tried for building the path is below. These are good though it did not solve my problme.
import pathlib
#image1test_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image2perfect)
#image1test_path = pathlib.Path('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path('data', 'TestImages', args.image2perfect)
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 trying to write a python script which can block websites based on the time of the day but i am not able to edit the hosts file in windows even running the cmd as an administrator.
Here's the Code:
import time
from datetime import datetime as dt
hosts_location=r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp="hosts"
blocked_websites=['www.facebook.com','facebook.com']
redirect="127.0.0.1"
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,8) < dt.now() <
dt(dt.now().year,dt.now().month,dt.now().day,17):
with open(hosts_location,"r+") as file:
content=file.read()
for website in blocked_websites:
if website in content:
pass
else:
file.write(redirect+"\t"+website+"\n")
print("Working Hours....")
else:
with open(hosts_location,"r+") as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in blocked_websites):
file.write(line)
file.truncate()
print("Fun Time...")
time.sleep(5)
Update:The code is working fine for a local hosts file but when i try it for the real hosts file even as administrator the script just flashes and with cmd shows message "[Errno 13]:Permission Denied".
Also i am not able to edit hosts even with notepad even as adminstrator my os is windows 10 home edition 64-bit.
First of all,
If you are not an administrator, change permissions of the hosts file by right clicking--> Properties --> Security and allow Read/Write/Execute Permissions for Users.
Then open Command Prompt as administrator and run the script. It will work!
try to save the python file as a .pyw extension
This will work for you.
Go to the hosts file and uncheck "read only" then go to security tab and give the permissions to user to read and write. Hope it'll work.
You should change access to file from users.
Go to C:\Windows\System32\drivers\etc and click right on properties, choose security and edit access to file.
Just change the path to be:
hosts_location = "C:\\Windows\\System32\\drivers\\etc\\hosts"
without r", and it will work
Recently I found a program that cleans your folders. This is the coding.
import os
import shutil
lis=[]
destinationDir='C:\Users\Owner\All in two'
os.makedirs(destinationDir)
lis=os.listdir('C:\Users\Owner\My Documents')
for x in lis:
if x==__file__:
continue
shutil.move(x,destinationDir)
When I try to run it though, it gives an error saying:
Traceback (most recent call last):
File "C:\Users\Owner\Desktop\Cleaner.py", line 6, in <module>
lis=os.listdir('C:\Users\Owner\My Documents')
WindowsError: [Error 5] Access is denied: 'C:\\Users\\Owner\\My Documents/*.*'
I tried using cmd in admin but it failed.
All advice is appreciated.
Make sure you have the appropriate permissions on your computer!
Right click on the folder (My documents or a folder inside) and look in security, if you have all the permissions with a tick box in, then this error shouldn't occur!
Basically, if you're not admin or can't access my documents, then you can't run it!
Hope this helps XD
Good afternoon,
I am getting the following error whenever I am trying to copy a test file from one directory to another on a remote server:
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\lib\site-packages\paramiko-1.12.0-py2.7.egg\paramiko\sftp_client.py", line 612, in put
file_size = os.stat(localpath).st_size
WindowsError: [Error 3] The system cannot find the path specified: '/brass/prod/bin/chris/test1/km_cust'
The file I am looking to copy is called km_cust.
I am executing these commands in python 2.7.
Please note that the hostname, uid, and password were changed to generic versions and the real hostname, uid, and password can be used to ssh to the box in question and preform all functionality.
Here is my code:
import paramiko
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect('hostname',username='test',password='pw')
filepath = '/brass/prod/bin/chris/test1/km_cust'
localpath = 'brass/prod/bin/chris/test2'
sftp = s.open_sftp()
sftp.put(filepath, localpath)
Any help will be apprecaited. Let me know if any other information is needed.
The problem is that put copies a local file—that is, a file n your Windows box—to the server. As the documentation says:
put(self, localpath, remotepath, callback=None, confirm=True)
Copy a local file (localpath) to the SFTP server as remotepath.
Note that you're also specifying (or at least naming) the paths backward… but that doesn't really matter here, because neither one is actually a local path. So when you do this:
sftp.put(filepath, localpath)
… it's looking for a file named '/brass/prod/bin/chris/test1/km_cust' on your Windows box, and of course it can't find such a file.
If you want to copy a remote file to a different remote file, you need to do something like this:
f = sftp.open(filepath)
sftp.putfo(f, localpath)
Or:
f = sftp.open(localpath, 'wx')
sftp.getfo(filepath, f)
Also, I'm guessing your filepath is supposed to start with a /.
However, this probably isn't what you wanted to do in the first place. Copying a file from the remote server to the remote server via sftp involves downloading all of the bytes to your Windows machine and then uploading them back to the remote machine. A better solution would be to just tell the machine to do the copy itself:
s.exec_command("cp '{}' '{}'".format(filepath, localfile))
s.close()
Note that in anything but the most trivial of cases, you're going to have to deal with the Channel and its in/out/err and wait on its exit status. But I believe that for this case, you should be fine.