I am trying to use a script to open a file inside a network drive using python. The script is given below:
import os
import subprocess
file_path = r"O:\XXXX\test.xls"
subprocess.Popen(filepath, shell=True)
The network drive requires sign in but I always by default sign it the moment I on the computer. Also, using a os.listdir(folderpath) has no problem going into the network drive and listing all the files in the directory containing the file.
Tried some suggestions from similar posts but they don't work.
I am using Python 2.7, and Windows.
UPDATE:
No error was prompted after executing the script.
I am trying to open an Excel file. The script works to open Excel in other folders within the computer, but just not within the network drive.
Thanks to #J.F. Sebastian's suggestion. replacing subprocess.Popen(filepath, shell=True) with os.startfile(filepath) works.
I think this could help you
import subprocess
file_path = r"X:\dir\excelfile.xlsx"
#~ also this works
#~ file_path = r"\\server\dir\excelfile.xlsx"
subprocess.call(file_path,shell = True)
Related
I am writing a short script that will loop through the pdf files in a directory, open them iteratively and let me classify them. The code I've written almost does everything I want. It loops through the files and opens and closes them. Note I'm working on Linux.
However, the cursor is not always staying on the shell, and I don't want to have to keep pressing Alt-tab. Does anyone know a way to use subprocess to run system commands, but to never move away from the shell when Python is running?
A simplified version of what I've got so far:
import signal
import os
import subprocess
import glob
files = glob.glob("pdfs/*.pdf", recursive=True)
for ff in files:
# get the evince call
command = f"evince --fullscreen {ff}"
# open the pdf
process_cat = subprocess.Popen(command, stdout = subprocess.PIPE, shell = True)
next = input("Keep viewing files? Y/N")
# close the pdf
os.kill(process_cat.pid, signal.SIGKILL)
if next != "Y":
break
idea 1: use of browser
No idea if this will help, but are you wedded to a linux shell approach, would viewing in a web browser perhaps work better?
If so, I was wondering if this package might help?
import webbrowser
files = glob.glob("pdfs/*.pdf", recursive=True)
for ff in files:
webbrowser.open_new(ff)
# etc
idea 2: direct display of PNG
Would conversion to PNG and then direct display of the image file from python itself also be an alternative? This post may help in that case: View pdf image in an iPython Notebook
when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))
I am working on the listener portion of a backdoor program (for an ETHICAL hacking course) and I would like to be able to read files from any part of my linux system and not just from within the directory where my listener python script is located - however, this has not proven to be as simple as specifying a typical absolute path such as "~/Desktop/test.txt"
So far my code is able to read files and upload them to the virtual machine where my reverse backdoor script is actively running. But this is only when I read and upload files that are in the same directory as my listener script (aptly named listener.py). Code shown below.
def read_file(self, path):
with open(path, "rb") as file:
return base64.b64encode(file.read())
As I've mentioned previously, the above function only works if I try to open and read a file that is in the same directory as the script that the above code belongs to, meaning that path in the above content is a simple file name such as "picture.jpg"
I would like to be able to read a file from any part of my filesystem while maintaining the same functionality.
For example, I would love to be able to specify "~/Desktop/another_picture.jpg" as the path so that the contents of "another_picture.jpg" from my "~/Desktop" directory are base64 encoded for further processing and eventual upload.
Any and all help is much appreciated.
Edit 1:
My script where all the code is contained, "listener.py", is located in /root/PycharmProjects/virus_related/reverse_backdoor/. within this directory is a file that for simplicity's sake we can call "picture.jpg" The same file, "picture.jpg" is also located on my desktop, absolute path = "/root/Desktop/picture.jpg"
When I try read_file("picture.jpg"), there are no problems, the file is read.
When I try read_file("/root/Desktop/picture.jpg"), the file is not read and my terminal becomes stuck.
Edit 2:
I forgot to note that I am using the latest version of Kali Linux and Pycharm.
I have run "realpath picture.jpg" and it has yielded the path "/root/Desktop/picture.jpg"
Upon running read_file("/root/Desktop/picture.jpg"), I encounter the same problem where my terminal becomes stuck.
[FINAL EDIT aka Problem solved]:
Based on the answer suggesting trying to read a file like "../file", I realized that the code was fully functional because read_file("../file") worked without any flaws, indicating that my python script had no trouble locating the given path. Once the file was read, it was uploaded to the machine running my backdoor where, curiously, it uploaded the file to my target machine but in the parent directory of the script. It was then that I realized that problem lied in the handling of paths in the backdoor script rather than my listener.py
Credit is also due to the commentator who pointed out that "~" does not count as a valid path element. Once I reached the conclusion mentioned just above, I attempted read_file("~/Desktop/picture.jpg") which failed. But with a quick modification, read_file("/root/Desktop/picture.jpg") was successfully executed and the file was uploaded in the same directory as my backdoor script on my target machine once I implemented some quick-fix code.
My apologies for not being so specific; efforts to aid were certainly confounded by the unmentioned complexity of my situation and I would like to personally thank everyone who chipped in.
This was my first whole-hearted attempt to reach out to the stackoverflow community for help and I have not been disappointed. Cheers!
A solution I found is putting "../" before the filename if the path is right outside of the dictionary.
test.py (in some dictionary right inside dictionary "Desktop" (i.e. /Desktop/test):
with open("../test.txt", "r") as test:
print(test.readlines())
test.txt (in dictionary "/Desktop")
Hi!
Hello!
Result:
["Hi!", "Hello!"]
This is likely the simplest solution. I found this solution because I always use "cd ../" on the terminal.
This not only allows you to modify the current file, but all other files in the same directory as the one you are reading/writing to.
path = os.path.dirname(os.path.abspath(__file__))
dir_ = os.listdir(path)
for filename in dir_:
f = open(dir_ + '/' + filename)
content = f.read()
print filename, len(content)
try:
im = Image.open(filename)
im.show()
except IOError:
print('The following file is not an image type:', filename)
Well I searched a lot and found different ways to open program in python,
For example:-
import os
os.startfile(path) # I have to give a whole path that is not possible to give a full path for every program/software in my case.
The second one that I'm currently using
import os
os.system(fileName+'.exe')
In second example problem is:-
If I want to open calculator so its .exe file name is calc.exe and this happen for any other programs too (And i dont know about all the .exe file names of every program).
And assume If I wrote every program name hard coded so, what if user installed any new program. (my program wont able to open that program?)
If there is no other way to open programs in python so Is that possible to get the list of all install program in user's computer.
and there .exe file names (like:- calculator is calc.exe you got the point).
If you want to take a look at code
Note: I want generic solution.
There's always:
from subprocess import call
call(["calc.exe"])
This should allow you to use a dict or list or set to hold your program names and call them at will. This is covered also in this answer by David Cournapeau and chobok.
You can try with os.walk :
import os
exe_list=[]
for root, dirs, files in os.walk("."):
#print (dirs)
for j in dirs:
for i in files:
if i.endswith('.exe'):
#p=os.getcwd()+'/'+j+'/'+i
p=root+'/'+j+'/'+i
#print(p)
exe_list.append(p)
for i in exe_list :
print('index : {} file :{}'.format(exe_list.index(i),i.split('/')[-1]))
ip=int(input('Enter index of file :'))
print('executing {}...'.format(exe_list[ip]))
os.system(exe_list[ip])
os.getcwd()+'/'+i prepends the path of file to the exe file starting from root.
exe_list.index(i),i.split('/')[-1] fetches just the filename.exe
exe_list stores the whole path of an exe file at each index
Can be done with winapps
First install winapps by typing:
pip install winapps
After that use the library:
# This will give you list of installed applications along with some information
import winapps
for app in winapps.list_installed():
print(app)
If you want to search for an app you can simple do:
application = 'chrome'
for app in winapps.search_installed(application):
print(app)
I have a rather simple program that writes HTML code ready for use.
It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem.
Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)?
Extra cool-points if you know how to open a file browser window.
The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual.
import os
target_dir = r"C:\full\path\to\where\you\want\it"
fullname = os.path.join(target_dir,filename)
with open(fullname,"w") as f:
f.write("<html>....</html>")
import webbrowser
url = "file://"+fullname.replace("\\","/")
webbrowser.open(url,True,True)
BTW: the code is the same in python 2.6.
I'll admit I don't know Python 3, so I may be wrong, but in Python 2, you can just check the __file__ variable in your module to get the name of the file it was loaded from. Just create your file in that same directory (preferably using os.path.dirname and os.path.join to remain platform-independent).