how to invoke sshfs within python script? - python

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)

Related

How to run bash commands from Python preferably with the os library?

I am trying to run the following python script named test.py. It contains multiple bash commands which I would like to execute in a Linux terminal (unix). This is the content of the file:
import os
os.system('echo install virtualenv')
os.system('sudo pip install virtualenv')
os.system('echo create virtual environment')
os.system('virtualenv my_virtualenvironment')
os.system('echo activate virtual environment')
os.system('source my_virtualenvironment/bin/activate')
I am running the Python script using the following in the terminal:
python3 test.py
The problem that I have is that the commands do not run the same way as they would on a Linux terminal. The output is the following error when trying to execute the last line of the Python script:
sh: 1: source: not found
The last command source my_virtualenvironment/bin/activate normally runs fine if I execute it directly in the terminal (without my Python script). Now, what does sh: 1: mean and why does it not work with my code? I would expect to get something starting with bash: .
Also I have found this solution, but I would like not to use lists for executing commands and maybe even to stick with the os library (if there is a simpler solution without os, I am also open for that):
https://stackoverflow.com/a/62355400/11535508
source is a bash built-in command, not an executable.
Use the full path to the python interpreter in your commands instead of venv activation, e.g. os.system('<venv>/bin/python ...').
The second option is to write your commands into a separate bash script and call it from python:
os.system('bash script.sh')

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')

Start a background shell script from python

I would like to connect a remote machine and run background script in that machine from python.
I tried:
os.system("ssh root#10.0.0.1 \' nohup script.sh & \')
But it seems not working. And if I put nohup in script.sh, and simply run
os.system("ssh root#10.0.0.1 \' script.sh \'")
The nohup command would not work in either cases.
I'm confused why so, and is there anybody knows how to do background job from python or it's just impossible doing it this way?
What kind of errors are you getting? What version of Python are you using?
You should take a look at this Python subprocess - run multiple shell commands over SSH
import subprocess
sshProcess = subprocess.Popen(["ssh", "root#10.0.0.1"],
stdin=subprocess.PIPE,
stdout = subprocess.PIPE,
universal_newlines=True,
bufsize=0)
sshProcess.stdin.write("nohup script.sh &")
For example you have a local script (python, bash, etc. Here I am demonstrating you using a python script)
First you create a python file locally. Lets say hello.py
# 'hello.py'
import os
print os.system('hostname')
Secondly now a python script which would execute the above hello.py on a remote machine
import pathos
copy = pathos.core.copy('hello.py', destination='abc.remote.com:~/hello.py')
exec = pathos.core.execute('python hello.py', host='.remote.com')
print exec.response()

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.

Python - Executing shell command does not work on Linux

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.")

Categories

Resources