Search code examples
pythonsshgnupg

python gnupg over ssh works in python shell, not in script


This is a question about a command which works in pythons interactive mode over SSH, but not if included in a script. It is driving me mad. I have been having problems with the script, but now I have discovered that I can simply put the lines into the python shell and I get the exact result I was expecting! This is confusing me, and I don't know how to proceed because I need it to work in a script. For the python shell, I log in via SSH, and then open a python script rather than login via the python ssh module. From there, it works exactly as expected.

import ssh
import gnupg
import pickle

s = ssh.Connection(host = 'ipaddress', username = 'toolserv', password = 'xxxx') 

gpg = gnupg.GPG(gnupghome="/home/toolserv/.gnupg") 

with open("result1.txt", "r") as my_file:
    signed_data1 = pickle.load(my_file)
    my_file.close()

print signed_data1

s.close()

If I execute the script as from sudo the error I get from the script is:

Traceback (most recent call last):
  File "sshx.py", line 11, in <module>
    with open("result1.txt", "r") as my_file:
IOError: [Errno 2] No such file or directory: 'result1.txt

ls -ld gives the following result: drwxr-xr-x 29 toolserv toolserv 4096 2012-08-19 22:38


Solution

  • Initial answer

    Your script is getting executed on your local host, not on your target server. Notice how you open an SSH session and then don't use it.

    The toolserv user likely doesn't exist on this host. Hence the error when gnupg tries to create the directory.

    In reaction to your comment:

    Let me make this clearer. Merely calling s = ssh.Connection(host = 'ipaddress', username = 'toolserv', password = 'xxxx') does not mean that all subsequent code will be executed on the remote host.

    Right now, what you code does is the following:

    1. Connect to the remote host at ipaddress through SSH
    2. Use the gnupg lib with the keys located at /home/toolserv/.gnupg on the local host.
    3. Read some (pickled?) file's content that is on your local host.
    4. Print that (unpickled) content
    5. Close the SSH connection (without ever using it).

    You never use the SSH connection, this is probably not what you want and probably why your script is failing.

    Of course, if you execute the exact same script on your remote host by login in through SSH and then using the shell, your local host is actually the remote host, so it works. However, the fact that the code works when executed from your remote host is nothing more than an coincidence.

    One last time, your script probably does not do what you think it does, and unless you investigate that, it's never going to work.