Using MobaXterm as Linux shell on Windows - python

I have a Python script which leverages subprocess to call MobaXterm and use it to run a command to my server through SSH. The script works fine when using the Windows Subsystem for Linux (WSL), but fails when using Moba. This is the code:
import subprocess
moba_path = "C:\Program Files (x86)\Mobatek\MobaXterm\MobaXterm.exe"
subprocess.run(f'{moba_path} -exec ssh my_server "mkdir test_dir"')
It opens the MobaXterm window but does not show any sign of command execution. I checked, and the command has not been executed (the folder has not been created).
Any ideas?

So I found a way to execute my commands using Moba in a programmatic way using the -newtab command. It starts a new tab which then runs the specified command.
import subprocess
moba_path = "C:\Program Files (x86)\Mobatek\MobaXterm\MobaXterm.exe"
subprocess.run(f'{moba_path} -newtab ssh my_server "mkdir test_dir"')

Related

How to launch gnome-terminal from dbus plugin, a systemd service, using Python

I use Python to develop a simple dbus based plugin (dbus.service.Object) that takes IPC calls from a command-line script. The dbus service is configured to host in systemd. It is running as expected. However, when I add a capability in the plugin to launch a gnome-terminal it failed. It seems the execution is stuck in any of these subprocess calls, no matter it is call() or Popen(). Wonder how can I make the plugin launch gnome-terminal correctly?
#subprocess.call(['gnome-terminal', '--', '/bin/bash', '-c', 'ls', '-al', '&'])
#subprocess.call(['systemd-run', '--user', '--service-type=forking', 'gnome-terminal', '-t', "Test",'--','/bin/bash', '-c', 'ls', '-al', "&"])
#subprocess.call(['DISPLAY=:0', 'gnome-terminal', '--', '/bin/bash', '-c', 'ls', '-al', '&'])
Things I also tried to launch a python script from the plugin and have the script to launch gnome-terminal but still failed.
Fail means that the terminal does not open and the ps doesn't show terminal. I also tried with os.system. It works if running directly from a console.
os.system('gnome-terminal -- /bin/bash -c "python /data/scripts/test.a.1.py -f /data/station_profile_A.json"')
The journal log shows the error below:
Dec 21 09:34:20 ubuntu coordinator[5380]: Unable to init server: Could not connect: Connection refused
Dec 21 09:34:20 ubuntu coordinator[5380]: # Failed to parse arguments: Cannot open display:
If I add 'DISPLAY=:0' in front of gnome-terminal, it doesn't help.
To connect to X, you need to set both DISPLAY and XAUTHORITY.
For example XAUTHORITY=$HOME/.Xauthority and DISPLAY=:0.0.
The file named by XAUTHORITY must be readable. The file is mode 0600.
I would suggest that you have your DBUS API include handing over a copy of the magic cookie, the contents of the XAUTHORITY file, to the service which then would write it to a temporary file and then with DISPLAY and XAUTHORITY set would run the command.

Script hangs while using Fabric's Connection.run() in the background

Overview
I'm trying to use python fabric to run an ssh command as root on a remote server.
The command: nohup ./foo &
foo is expected to command run for several days. I must be able to disassociate foo from fabric's remote ssh session, and put foo in the background.
The Fabric FAQ says you should use something like screen or tmux when you run your fabric script (which runs the backgrounded command). I tried that, but my fabric script still hung. foo is not hanging.
Question
How do I use fabric to run this command on a remote server without the script hanging: nohup ./foo &
Details
This is my script:
#!/bin/sh
# Credit: https://unix.stackexchange.com/a/20895/6766
if "true" : '''\'
then
exec "/nfs/it/network_python/$OSREL/bin/python" "$0" "$#"
exit 127
fi
'''
from getpass import getpass
import os
from fabric import Connection, Config
assert os.geteuid()==0, "ERROR: Must run as root"
for host in ['host1.foo.local', 'host2.foo.local']:
# Make an ssh connection to the host...
conn = Connection(host)
# The script always hangs at this line
result = conn.run('nohup ./foo &', warn=True, hide=True)
I always open a tmux session to run the aforementioned script in; even doing so, the script hangs when I get to conn.run(), above.
I'm running the script on a vanilla CentOS 6.5 VM; it runs under python 2.7.10 and fabric 2.1.
The Fabric FAQ is unclear... I thought the FAQ wanted tmux used on the local side when I executed the Fabric script.
The correct way to fix this problem is to replace nohup in the remote command, with screen -d -m <command>. Now I can run the whole script locally with no hangs (and I don't have to use tmux in the local term).
Explicitly, I have to rewrite the last line of my script in my question as:
# Remove &, and nohup...
result = conn.run('screen -d -m ./foo', warn=True, hide=True)

How do I copy files from windows system to any other remote server from python script?

I don't want to use external modules like paramiko or fabric. Is there any python built in module through which we can transfer files from windows. I know for linux scp command is there like this is there any command for windows ?
Paramiko is stable, simple and supports Linux, OS X and Windows.
You can install via pip:
pip install paramiko
Simple Demo:
import base64
import paramiko
key = paramiko.RSAKey(data=base64.b64decode(b'AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('ssh.example.com', username='strongbad', password='thecheat')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
print('... ' + line.strip('\n'))
client.close()
Something similar to scp is the Copy-Item cmdlet that's available in Powershell, You could execute powershell and run a Copy-Item command to copy a file from your local windows system to another directory or a remote server directory.
You need to first set the PowerShell for unrestricted access by doing Set-ExecutionPolicy Unrestriced after which you can use the subprocess module of python to make a call to execute the required script.
Maybe this answer is of help to you.
Server
python -m http.server
this will create a http server on port 8000
client
python -c "import urllib; urllib.urlretrieve('http://x.x.x.x:8000/filename', 'filename')"
where x.x.x.x is your server ip, filename is what you want to download

How to execute remote pysftp commands under a specific shell

I use python module pysftp to connect to remote server. Below you can see python code :
import pysftp
import sys
import sqr_common
srv = pysftp.Connection(host="xxxxxx", username="xxxx",
password="xxxxx")
command = "/usr/bin/bash"
command2="APSHOME=/all/aps/msc_2012; export APSHOME; "
srv.execute(command)
srv.execute(command2)
srv.close()
Problem is that command /usr/bin/bash is an infinite process , so my script will never be executed. Can anyone help me how to choose shell on remote server for example bash and execute command in bash on remote server?? Is there any pysftp function that allows me chosing shell??
try this
/usr/bin/bash -c "APSHOME=/all/aps/msc_2012; export APSHOME; "
This problem is not specific to Python, but more like how to execute commands under specific shell.
If you need to run only single command you can run using bash -c switch
bash -c "echo 123"
You can run multiple commands ; separated
bash -c "echo 123 ; echo 246"
If you need to many commands under a specific shell, remotely create a shell script file (.bash file) an execute it
bash myscript.bash

python subprocess: how to run an app on OS X?

I am porting a windows application to OS X 10.6.8. It is a new platform for me and I am facing some difficulties.
The application is a small webserver (bottle+waitress) which is starting a browser (based on chromium embedded framework) thanks to a subprocess call.
The browser is an app file and runs ok when started from gui.
I am launching it this way:
subprocess.Popen([os.getcwd()+"/cef/cefclient.app", '--url=http://127.0.0.1:8100'])
Unfortunately, this fails with OSError: permission denied.
I tried to run the script with a sudo with similar result.
I can launch the app from shell with the following command:
open -a "cef/cefclient.app" --args --url-http://127.0.0.1:8100
But
subprocess.Popen(['open', '-a', os.getcwd()+'/cef/cefclient.app', '--args', '--url-http://127.0.0.1:8100'])
fails with the following error
FSPathMakeRef(/Users/.../cefclient.app) failed with error -43.
Any idea how to fix this issue?
The file cefclient.app is actually a directory (an application bundle, specifically), not the application executable. The real executable is located inside the bundle, with a path like Contents/MacOS/executable_name. So to launch it, you'd do this:
subprocess.Popen([os.getcwd()+"/cef/cefclient.app/Content/MacOS/executable_name",
"--url=http://127.0.0.1:8100"])
Alternatively,
os.system('open -a "cef/cefclient.app" --args --url-http://127.0.0.1:8100')
Just depends if you want to control stdin / stdout or if starting the app is enough.

Categories