Raspberry Pi Tkinter via shh and xming - python-3.x

I'm trying to run a Tkinter script from a raspberry, via an ssh client and xming. Once I've logged into the pi via shh I use the command:
gksudo python3 home/pi/PythonScripts/TkinterTest.py
This is the error that is given on my PC:
(gksudo:2700): Gtk-WARNING **: cannot open display:
and a different error on my laptop running the same software:
(gksudo:3227): GLib-CRITICAL **: g_str_has_prefix: assertion 'str != NULL' failed
I have tried to change the display with the command:
export DISPLAY=:0.0
But this had no effect on the output.

First of all be sure that the X forwarding is actived on your raspberry, you can check that in /etc/ssh/sshd_config: X11Forwarding yes
ssh -X username#<raspberry> (-X flag for the X11 forwarding)
Run your script : (su) python /path/to/script.py
Sometimes when you try to run program via sudo you can have some error, you need to check the permissions of .Xauthority file

I had a similar problem. I know this Question is 3 years old. But my search landed me here. So just answering the question
sudo cp ~pi/.Xauthority ~root/
This just copies the X11 authority file directly to root without the xauth command management. This will make all active user pi X11 connections available for use by root without having to sort through and find the correct one.
P.S : I'm just copy pasting, credit goes to this answer in this forum

Related

How to unlock Gnome Keyring on Debian headless (WSL 2) and make it work in Python?

I have read the guindance that the keyring package has in its project for headless linux systems.
So the main recommendation is to install the gnome-keyring package in order to work with the Secret Service Backend.
sudo apt install gnome-keyring
Then, as I already have the dbus package installed I just run:
dbus-run-session -- sh
But, as I am in WSL 2 I get a weird prompt, it seems that PS1 is not parsed and I get something like this:
\[\e]0;\u#\h: \w\a\]\[\033[01;32m\]\u#\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$
In a normal Debian or Ubuntu instance I would get $
I send the password to unlock the keyring
echo 'db' | gnome-keyring-daemon --unlock
I also tried to enter the password manually through stdin as this answer points out, with the same result:
gnome-keyring-daemon --unlock
Now the guide says "run your application in the same D-Bus session as the daemon". I don't know if I need to do something special to achieve that. I just run python after entering the password.
$ python
>>> import keyring
>>> keyring.get_keyring()
<keyring.backends.SecretService.Keyring object at 0x7f383b89f220>
>>> keyring.set_password("system", "username", "password")
But at this point I get this error:
dbus-daemon[9337]: [session uid=1000 pid=9337] Activating service name='org.freedesktop.secrets' requested by ':1.4' (uid=1000 pid=9339 comm="python ")
GNOME_KEYRING_CONTROL=/home/db/.cache/keyring-TPE3M1
dbus-daemon[9337]: [session uid=1000 pid=9337] Successfully activated service 'org.freedesktop.secrets'
dbus-daemon[9337]: [session uid=1000 pid=9337] Activating service name='org.gnome.keyring.SystemPrompter' requested by ':1.5' (uid=1000 pid=9356 comm="/usr/bin/gnome-keyring-daemon --start --foreground")
Unable to init server: Could not connect: Connection refused
(gcr-prompter:9364): Gtk-WARNING **: 09:36:04.690: cannot open display:
dbus-daemon[9337]: [session uid=1000 pid=9337] Activated service 'org.gnome.keyring.SystemPrompter' failed: Process org.gnome.keyring.SystemPrompter exited with status 1
** (gnome-keyring-daemon:9356): WARNING **: 09:36:04.701: couldn't create system prompt: GDBus.Error:org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.gnome.keyring.SystemPrompter exited with status 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/env/lib/python3.9/site-packages/keyring/core.py", line 60, in set_password
get_keyring().set_password(service_name, username, password)
File "/path/to/env/lib/python3.9/site-packages/keyring/backends/SecretService.py", line 87, in set_password
collection = self.get_preferred_collection()
File "/path/to/env/lib/python3.9/site-packages/keyring/backends/SecretService.py", line 67, in get_preferred_collection
raise KeyringLocked("Failed to unlock the collection!")
keyring.errors.KeyringLocked: Failed to unlock the collection!
And the processes tree look like this
I also tried with
dbus-run-session -- bash
With the same result
Possible WSL 2 Issue
I also found an issue on WSL2 project where "jaraco" says that the guidance that I followed may give some hints, but I could not get it to work.
Alternative Backend
I tried with other backend as well, though in some places they say that this backend is not recommendable:
“alternate”, possibly-insecure backends, originally part of the core package, but available for opt-in"
pip install keyrings.alt
With similar result. The keyring backend was different:
>>> keyring.get_keyring()
<keyring.backends.chainer.ChainerBackend object at 0x7ffbad5fd040>
Any alternative or recommendation? Am I missing some step? Is this possible to make in WSL 2? I think I will try in a debian machine directly to check if it is a problem of WSL or all Debian headless distros. Anybody make it work on Debian without Gnome desktop installed?
The next step would be to automate all the process, but first I need to get this to work
Update
Well, I can confirm that in a virtual machine on Debian 11.3 works fine. So it must be something to do with WSL 2
Update 2
Ah, I have just realized that I had installed the WSL2, but my Debian System was in WSL so I had to update it to WSL2 with the following instruction. Anyway, I think the behaviour, in this case would be the same.
wsl --set-version Debian 2
Note that I have been able to get this to work (WSL2, Debian Bullseye, python3, gnome-keyring, Windows 10). I can understand parts of why it may not be working for you, but there are some minor differences in the errors you are seeing from what I can reproduce (when I try to break it). We'll come back to those if we need to, but let me go through what I've tried successfully so far.
But, as I am in WSL 2 I get a weird prompt
First, I think this is an orthogonal issue, but perhaps not. I always suspect startup configuration files for this type of weirdness, so I would try eliminating those from the equation:
dbus-run-session -- bash --noprofile --norc
If the prompt looks normal when running that, I'd look to ~/.profile since it sounds like it it happens both Bash and Dash (sh) for you and Dash doesn't have an rc file.
Again, I'm assuming that's not the problem with the keyring, but it doesn't hurt to eliminate it as a potential contributor.
As for the main keyring problem, that, I believe, is because:
Gnome Keyring is attempting to ask for a password. It does this with a graphical password prompt, which fails because ...
You are running Windows 10 without an X server, or if you are running an X server, then the DISPLAY variable is "lost". That's the cannot open display error in the trace. If you were on Windows 11, the graphical prompt would display. You could also configure Windows 10 WSL to use a third-party X server like VcXsrv. Or you could run with Xrdp. See this Super User question (and others) for more info.
Of course, that would no longer count as "headless", which is your question. So we need to figure out why gnome-keyring is asking for a password. I can think of at least possible three reasons, but there may be others:
The default collection (keyring) doesn't exist yet. I'm fairly sure that's not the case for you, since it should have been created when you ran the --unlock. Of course, you can verify this by checking ~/.local/share/keyrings.
gnome-keyring-daemon hasn't yet been started, and needs the keyring password. Again, you've clearly run that here. You've done the right thing by running the dbus-run-session first, then inside that session, run the --unlock. You can, of course, verify that it is running with a ps -efH or similar.
The password that was passed via --unlock is wrong.
So with the first two eliminated, we're left with the assumption there's an issue with the unlock password. If you created the collection with the initial --unlock, then the first password you used should be the one set on the collection.
There are some "gotchas" here. First, contrary to what the answer you linked says, I'm convinced that the newline is added to the password. If you somehow initially set the password without a newline, you'd need to unlock it with echo -n. E.g.:
echo -n 'db' | gnome-keyring-daemon --unlock
Second, it doesn't sound like this was the case for you, but if you create the keyring through the normal frontend, then it appears to me that the password may be salted. I have not been able to use gnome-keyring-daemon --unlock (in any of its forms) to unlock a collection where the password was entered through the graphical prompt. To clarify:
If I initially create the keyring via gnome-keyring-daemon --unlock, then I can unlock it either through the GUI askpass program that it uses (on Windows 11 or with a Windows 10 VcXsrv installation), but ...
If I initially create the keyring via an initial access of it which prompts for the password through the GUI, then I can subsequently only unlock it through the GUI. I can no longer use gnome-keyring-daemon --unlock.
Assuming this is a new keyring in WSL2, then my advice would be to remove it and try again:
dbus-run-session -- bash --noprofile --norc
# Back them up first if you'd like
rm -rf ~/.local/share/keyrings
echo -n 'db' | gnome-keyring-daemon --unlock
python3
Note that you can test the keyring module directly from the shell via:
python3 -m keyring set system username
# Will prompt for the secret
python3 -m keyring get system username
# Should return the secret
If things are working from there, they'll work from your code. If it fails, it should do so with the same error at least. This might save some time in troubleshooting if this doesn't work.

Cygwin: Unable to initialize GTK: could not open display

I've got a Win 10 box with Cygwin and the X packages installed. I run xlaunch and start up the X server. I then do "ssh -Y user#myserver". Then I su and run virt-manager. I get an error:
Cygwin: Unable to initialize GTK: could not open display
echo $DISPLAY shows:
localhost:10.0
I've tried changing it with EXPORT DISPLAY=localhost:0.0 with no luck.
I've googled and read all of the similar questions but none address my problem, as simple as I'm sure it is.
Starting from xorg-server version 1.17 , the option -nolisten tcp is now the default, so the server only accepts local connections on a unix domain socket.
To allow connection by TCP you should use the option -listen that has been added to restore the previous behaviour.
As reported by the package maintainer:
https://sourceware.org/ml/cygwin-announce/2015-10/msg00111.html

I'm trying to run gedit in cygwin, but receiving error

I'm trying to run some normal text editor in cygwin (version 2.4.1(0.293/5/3)).
I've really disappointed and frustrated with emacs :( So I downloaded and installed gedit as a part of cygwin package, but when I'm trying to run it, I receive:
$ gedit
Unable to init server: Could not connect to 127.0.0.1: Connection refused
(gedit:8196): Gtk-WARNING **: cannot open display:
I understand that it can be somehow connected with security issues (it runs on multiuser win10 PC), but I cannot find out how to solve it....
Please help!
I was having the same problem and was able to solve. Your case may be the same
install Cygwin/X
open cygwin and start x11 server by typing
startxwin >/dev/null 2>&1 &
set DISPLAY environment variable as explained here by typing
export DISPLAY=:0.0
Start gedit normally
This (startxwin >/dev/null 2>&1 & export DISPLAY=:0.0) work for temporary, not permanent. It is needed to type each time I close terminal.

SCP error: Bad configuration option: PermitLocalCommand

When I execute this command below:
scp -P 36000 hdfs#192.168.0.114:~/tmp.txt SOQ_log.txt
I get an error:
command-line: line 0: Bad configuration option: PermitLocalCommand
Does anyone know why?
scp runs a copy of the ssh program to create the communications channel, and it runs ssh with the options:
-oForwardAgent=no -oPermitLocalCommand=no -oClearAllForwardings=yes
So that explains where the "PermitLocalCommand" option is coming from in the first place. I'll add that sftp uses the same options to run ssh, so it'll probably display the same behavior.
"PermitLocalCommand" is normally a valid ssh configuration option. If your copy of ssh is complaining about it, then it seems that your copy of ssh isn't the normal copy of ssh that goes with your copy of scp.
This serverfault question suggests that the error could be due to someone installing a malware version of ssh (ie, a rootkit) on your system. This forum thread also suggests that the problem is due to having an altered version of ssh, which was fixed by removing and reinstalling the OpenSSH client utilities.
An alternate explanation would be that someone--maybe your Linux distro maintainer--has installed a version of ssh on your system with that option removed, and you're using it unawares. Or you have a very old version of the ssh program for some reason, which doesn't support the option.
My system is CentOs 5.9
I'm facing the same problem, I found it to be due to this configuration line in /etc/ssh/sshd_config:
# override default of no subsystems
Subsystem sftp /opt/libexec/sftp-server
But I cannot run /opt/libexec/sftp-server, it is broken for some reason
now it is solved by reinstall the remote openssh-server:
yum erase openssh-server
yum install openssh-server
now the changes to
# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server
and /usr/libexec/openssh/sftp-server is runnable
don't forget to execute:
/etc/init.d/sshd restart
Sometimes command cannot parse this kind of stuff
:~/
Id change it to the full path.

Debugging in pyCharm with sudo privileges?

I've tested code that requires root access in pyCharm by running sudo pycharm.sh but this is not the way I would recommend of doing so.
I know it's possible to debug with sudo privileges by running the python interpreter as sudo in pyCharm but how do we do this?
Create a shell script that does "sudo python" and forwards the arguments, and configure that script as a Python interpreter in PyCharm.
Name of this shell script should start with python (source: http://forum.jetbrains.com/message/PyCharm-424-3).
In PyCharm new version, it has a configure to run Python interpreter in root, no need workaround. See picture below. Check to checkbox: Execute code using this interpreter with root privileges via sudo
For what it's worth, I've managed run a python script with sudo priviledges (on Ubuntu 16.04) like this:
In the very first line in the script, define the interpreter like this:
#!/usr/bin/sudo python
Make the script executable:
chmod +x myscript.py
Run the script directly, without specifying the python interpreter yourself:
./myscript.py
The script will ask for sudo password and continue running with elevated priviledges.
I solved this problem by copying /usr/bin/python3 in my home, then setting cap_net_bind_service capability:
cp /usr/bin/python3 ~/python35-setcap
sudo setcap 'cap_net_bind_service=+ep' ~/python35-setcap
And then using ~/python35-setcap as python interpreter in pycharm.
This way, you can bind lower ports, but not any python 3 program can do it, and pycharm can still kill your script. You could also restrict execute permission to yourself if you want more security.
I have encountered the same problem trying to debug Bluetooth related code on a Raspberry Pi. I suppose, since you're doing remote debug on the device, that the device is for development use only. In such a case, in my humble option, you should permit ssh root login, so you can configure PyCharm to use the root user and you don't need to sudo. That's the solution I have chosen.
The following instructions are for a Raspberry Pi, but the procedure is the same for any Linux distribution:
First of all, add your public key to the authorized_keys:
cat ~/.ssh/id_rsa.pub | ssh pi#raspberrypi "mkdir -p ~/.ssh && cat >>
~/.ssh/authorized_keys"
Then login into the Raspberry Pi:
ssh pi#raspberrypi
Once you have a console copy your key into the root directory:
sudo mkdir /root/.ssh
sudo cp authorized_keys /root/.ssh/
Finally edit sshd_config adding PermitRootLogin without-password:
sudo vim /etc/ssh/sshd_config
Use your preferred editor.
Now you are able to ssh inside the Raspberry Pi as root:
ssh root#raspberrypi
Using root instead or pi user, give you the ability to run your code, even remotely, with root privileges, as
required by BlueZ.
I have encounter another way to solve this issue so I thought to share it (this answer is more like an alternative for the other answers).
It is worth to mention here that this solution "attacks" the problem by running only a certain Python script (within the pPyCharm IDE) in root mode , and not the entire PyCharm application.
1) Disable requiring password for running Python:
This will be achieved by editing the /etc/sudoers.d/python file. What we need to do is to add an entry in that file as follows:
user host = (root) NOPASSWD: full_path_to_python, for example:
guya ubuntu = (root) NOPASSWD: /usr/bin/python
NOTES:
user can be detected by the command: whoami
host can be detected by the command: hostname
2) Create a "sudo script": The purpose of this script is to give Python privilege to run as root user.
Create a script called python-sudo.sh , and add the following into it:
#!/bin/bash
sudo /usr/bin/python "$#"
Note again that the path is the path to your Python as the previous phase.
Also, this path is the path to Python2 on the system.
Don't forget to give execution permissions to this script using the command: chmod
chmod +x python-sudo.sh
3) Use the python-sudo.sh script as your PyCharm interpreter:
Within PyCharm go to: File --> Settings --> Project interpreter
At the right top hand side click the "setting" icon, and click "Add local".
In the browser option choose the python-sudo.sh script we have created previously. This will give PyCharm the privilege to run a Python script as root.
4) Debug the test: All there is left to do is actually debug the specific Python script in the PyCharm IDE. This can be done easily via Right-click on the script to debug --> hit Debug sample_script_to_debug.py
For those looking for a cleaner solution and don't mind entering a password each time.
Go to your Run Configuration > Edit Configurations
Under 'Execution', check the Emulate terminal in output console option.
This will allow you to debug a Python script while maintaining your current user and giving elevated sudo privileges to the script when it's needed. It also makes it easier to maintain different virtual environments if you work across multiple projects.
Terminal:
sudo ./Pycharm
this way you can start PyCharm as SuperUser
I follow the instructions here and success. But there is a problem that the PYTHONPATH is not valid when you use sudo. So when you edit with
sudo visudo -f /etc/sudoers.d/python
add that:
user host = (root) NOPASSWD:SETENV: /home/yizhao/anaconda3/bin/python
also your script should be:
#! /bin/bash
sudo PYTHONPATH=$PYTHONPATH /home/name/anaconda3/bin/python "$#"
Similar to what #Richard pointed out, the answer posted here worked for me
sudo /Applications/PyCharm.app/Contents/MacOS/pycharm on MacOS

Resources