Python - Executing shell command does not work on Linux - python

I like to run a shell command from Python on my Linux Mint system.
Specifically the command runs all Bleachbit cleaners and works perfectly
fine when run maually.
Yet, trying to run the same command via the subprocess.call module
always results in an exception raised.
I just can not see why it should not work.
The command does not require sudo rights, so not requiring
right not given.
I also have firefox/browsers closed when executing the python command.
Anybody, any suggestions how to fix this issue?
My code:
try:
subprocess.call('bleachbit -c firefox.*')
except:
print "Error."

subprocess module does not run the shell by default therefore the shell wildcards (globbing patterns) such as * are not expanded. You could use glob to expand it manually:
#!/usr/bin/env python
import glob
import subprocess
pattern = 'firefox.*'
files = glob.glob(pattern) or [pattern]
subprocess.check_call(["bleachbit", "-c"] + files)
If the command is more complex and you have full control about its content then you could use shell=True to run it in the shell:
subprocess.check_call("bleachbit -c firefox.*", shell=True)

When shell is False you need to pass a list of args:
import subprocess
try:
subprocess.call(["bleachbit", "-c","firefox.*"])
except:
print ("Error.")

Related

Execute Commands in Kali-Linux's Terminal through Python

I want to execute commands in the terminal through a python scripts.
i want to create a script which takes data from a .txt file adds that in a list and then one by one execute them in the terminal.
what i am looking for is a process to execute commands in the terminal in Kali Linux, I couldn't find anything online.
like in windows we use import subprocess or import os
Thank you.
example command is like
python3 app.py
Try this:
import subprocess
command = "python3 app.py"
subprocess.call(command, shell=True)
You can use the os.system function. It returns the return value of the command run.
E.g.,
status = os.system('echo hello')

How to convert sh -c "$(curl -fsSL URL)" to native python

I am trying convert the shell command:
sh -c "$(curl -fsSL https://raw.githubusercontent.com/foo/install.sh)"
To native python. I cannot rely on curl being on the system. I start with this to replace curl
from urllib.request import urlretrieve
from urllib.error import URLError
try:
urlretrieve("https://raw.githubusercontent.com/foo/install.sh",
os.path.expanduser('~/' + 'install.sh'))
except URLError as e:
...
What is the best way to then replicate the sh -c install.sh portion of the command in native python? I need an interactive shell to install.sh, then for the script to carryon in python. I need a python interactive subprocess with exception handling to execute install.sh
Some examples of subprocess?
import subprocess
p = subprocess.Popen(['sh install.sh'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout,stderr = p.communicate()
print(stdout)
print(stderr)
Another that does not wait for command to complete before writing out
import subprocess, sys
cmd = "sh install.sh"
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
You could try os.system(), that is, after you save the install script in the current directory, then
os.system('sh -c install.sh')
The script is presumably written in sh, so you'll need sh (or compatible) to run it.
This uses stdin/stdout, so you can interact with it using the terminal if necessary. When the subprocess terminates, os.system() returns its exit code and Python resumes.
(If you're not saving to the working directory, you could use the absolute path to install.sh, or change the working directory using os.chdir().)
If you need to automate this interaction in Python, you should probably use subprocess instead, it's more powerful, but takes more work to configure.
Yes, I need to run sh and os.system() is the easiest way. I would like the script to run unattended and only prompt user if input is needed. I will expand on my question with a subprocess example.
If the script runs and terminates itself on its own in the normal case with no further input, then os.system() is enough, even to run unattended, since Python will resume when the script completes. You can also raise an exception for a nonzero exit code, if desired:
if os.system('sh -c install.sh'): raise ...

How to run a series of bash commands via Python?

Running on Windows system, I run bash.exe using subprocess.call().
Following is the code
def predict():
os.system('notepad cmnd.txt')
subprocess.call(['C:/Windows/System32/bash.exe'])
print(file_contents)
label = Label(master, text=file_contents)
#subprocess.call(['c:/users/hp/open.py'])
label.pack()
The handle passes to bash,thus not executing a couple of commands.
cd commands that runs on actually entering values return Missing Directory error.
ls command returns 'cannot run binary file' error.
What should I do?
I'm not really sure what you want here, but if you want to run bash commands in a Windows enviorment, you can try using subprocess.check_output():
from subprocess import check_output
bash_commands = ['ls', 'pwd']
for command in bash_commands:
output = check_output(['bash', '-c', command]).decode()
print(output)
Which in this example, lists all files in the current directory and prints out the parent working directory.

Execute a program using python on windows

I am new to windows python. I am trying to run a command line tool using python. This tool will flash the firmware connecting to IP address of the machine. I could open cmd prompt and use the command
C:\ToolsSuite>sdi --ip 172.23.240.41 --fwdl "c:\BUILDS\firmware_image.zip
.This works for me very well.
But when I try to execute using the python script on windows, I am not able to do that. Python script looks like this.
import subprocess
import os
os.chdir(r"C:\ToolsSuite")
#os.system('cd c:\mydir')
os.system("sdi --ip 192.92.48.32 --fwdl C:\firmware_image.zip")
#subprocess.Popen(r'sdi --ip 192.92.48.32 --fwdl "c:\firmware_image.zip"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
The exception thrown is "Could not find file". I am not getting how to give the path of the firmware file when it is stored in some location, say for example 'C' drive or in some folder location of windows.
If the sdi executable is in "C:\ToolsSuite", this should work:
subprocess.call(['sdi', '--ip 192.92.48.32', r'--fwdl "c:\firmware_image.zip"'])
If you want to call a Windows command, you need to give the full path to the command.
You can try:
import subprocess
import os.path
# C:\ToolsSuite>sdi --ip 172.23.240.41 --fwdl "c:\BUILDS\firmware_image.zip"
cmd = os.path.join("C:\\ToolsSuite", "sdi")
args = [cmd,
'--ip', '172.23.240.41',
'--fwdl', 'c:\\BUILDS\\firmware_image.zip']
subprocess.check_call(args)
Here, check_call is useful to replace non-zero exit code by an exception. Of course, you can also choose another function of the same family.

how to invoke sshfs within python script?

I want to mount a remote directory using sshfs. sshfs working fine from terminal.
But how to invoke it from within python script?
I tried something like this - but didn't work at all.
import os
cmd = "/usr/bin/sshfs giis#giis.co.in:/home/giis /mnt"
os.system(cmd)
first, you should make sure your sshfs command works fine using the shell. Then, go to here to see many examples of using subprocess module of Python to call your sshfs commmand
import subprocess
mount_command = f'sshfs {host_username}#{host_ip}:{host_data_directory} {local_data_directory}'
subprocess.call(mount_command, shell=True)
# Do your stuff with mounted folder
unmount_command = f'fusermount -u {local_data_directory}'
subprocess.call(unmount_command, shell=True)

Categories

Resources