3

I have written a script that establishes an SSH tunnel and connects to a database over that tunnel.

Extremely simplified nutshell (obvious parameters and extra logic omitted):

sshTunnelCmd = "ssh -N -p %s -L %s:127.0.0.1:%s -i %s %s@%s" % (
   sshport, localport, remoteport, identityfile, user, server
)
args = shlex.split(sshTunnelCmd)
tunnel = subprocess.Popen(args)
time.sleep(2)
con = MySQLdb.connect(host="127.0.0.1", port=localport, user=user, passwd=pw, db=db)
## DO THE STUFF ##
con.close()
tunnel.kill()

The shell-equivalent commands are below, and I have tested both the commands and the script to work in "clean client" conditions, i.e. after a reboot.

ssh -N -p 22 -L 5000:127.0.0.1:3306 user@server
mysql --port 5000 -h 127.0.0.1 -u dbuser -p

SSH login is with keys and in ~/.ssh/config the server is configured as

Host server
  Hostname F.Q.D.N
  Port 22
  User user
  ControlMaster auto
  ControlPath ~/.ssh/master-%r@%h:%p
  ControlPersist 600
  IdentityFile ~/.ssh/id_rsa

In the ## DO THE STUFF ## section there is code that tries to connect to the database as regular users. If an exception is raised, it asks for manual input of root credentials, creates the regular users and continue to do the stuff (ordinary queries, all tested manually and working in the python code under clean client conditions).

ruz = raw_input('root user? ')
print (ruz)
rup = raw_input('root password? ')
print (rup)

print ("Root connecting to database.")
try:
  cxroot = MySQLdb.connect(host=host, port=port, user=ruz, passwd=rup)
  cur = cxroot.cursor()
except MySQLdb.Error, e:
  print ("Root failed, sorry.")
  print "Error %d: %s" % (e.args[0],e.args[1])
  print ("GAME OVER.")
  return -1

Under clean client, the first and some subsequent executions work well, including when I try to test the script robustness and remove the user server-side. However, at some point, it hangs in a weird way after the second raw_input in the code block above. Output:

root user? root
root
root password? s3cReTsTr1n9
-bash: line 1: s3cReTsTr1n9: command not found

The only thing I can do at this point is kill the process or hit CTRL+C, which is followed by the following traceback:

^CTraceback (most recent call last):
  File "./initdb.py", line 571, in <module>
    main()
  File "./initdb.py", line 526, in main
    connection = connectDB ('127.0.0.1', localport, dbuser, dbpw, db)
  File "./initdb.py", line 128, in connectDB
    rup = raw_input('root password? ')
KeyboardInterrupt

Another unexpected symptom I noticed is that keyboard input to the terminal window (I am running this in a bash terminal within Xubuntu 14.04LTS) becomes spuriously unresponsive, so I have to close the terminal tab and start a new tab. This clears keyboard input, but not script behaviour.

I have tried to search for a solution but the usual search engines are not helpful in my case, probably because I do not completely understand what is going on. I suspect that keyboard input is somehow redirected to a process, possibly the tunnel subprocess, but I cannot explain why the first raw_input works as expected and the second one does not.

I am also uncomfortable with the way I create the tunnel, so any advice for a more robust tunnel creation is welcome. Specifically, I would like to have more fine grained control over the tunnel creation, rather than waiting an arbitrary two seconds for the tunnel to be established because I have no feedback from that subprocess.

Thanks for sharing your time and expertise.

Yuv
  • 314
  • 3
  • 8

3 Answers3

0

Are you free to configure the server as you like? Then try a vpn connection instead of ssh port forwarding. This will easier reconnect without affecting your application, so the tunnel may be more stable.

For the raw_input problem i cannot see why it happens, but maybe the ssh command in a shell interferes with your terminal? If you really want to integrate the ssh tunnel you may want to look at some python modules for handling ssh.

allo
  • 3,955
  • 8
  • 40
  • 71
0

There's two sections to my answer: how I'd go about diagnosing this, and how I would go about doing this.

To begin with, I'd suggest using the prompt that's failing as an opportunity to do some exploration.

There's two approaches you could take here:

  • Just enter hostname (or whatever) to find out where it's running
  • Enter bash, or if the remote end has an X server add -X to your ssh command then type a terminal program (xterm, gnome-terminal, etc). In your new shell you can poke around to see what's going on.

If you determine it's running on the client side you could diagnose it with strace:

strace -f -o blah.log yourscript.py

... where you'd enter an easy to search string for the password then search for that in blah.log. Because of the -f flag it will print the PID of the process that attempted to execute it; backtracking from there you'll probably find that PID started with a fork from another PID. That PID is what tried to execute it, so you should be able to investigate from there.


As for how I'd do this: I'm still fairly new to python so I would've been inclined to use perl or expect. Down the perl path you might look at:

  • Net::SSH::Tunnel; this is probably the first one I'd look at using.
  • Use open or open3 then do something hacky like:
    • wait for stdout on the process to have text available; you'd have to get rid of -N for that, and you'd be at the mercy of remote auto-logout.
    • One of the various responses to ssh-check-if-a-tunnel-is-alive
  • Net::SSH::Expect (eg this post, though I didn't look at his implementation so you'd have to make your own choice on that). This or the "real" expect are probably overkill but you could find a way I'm sure.

Although ruby has a gem like perl's Net::SSH::Tunnel, I don't see a pip for python. This question and this one both discuss it and they seem to indicate you're limited to either starting it as a sub-process or using paramiko.

Community
  • 1
  • 1
Brian Vandenberg
  • 4,011
  • 2
  • 37
  • 53
  • Thank you for directing me to explore the failing prompt. It is running on the server side. Scary. The first line takes the input as expected. The second line is a shell prompt. When I enter a third line, it is the actual second raw_input command that get printed properly. – Yuv Jul 09 '15 at 03:09
  • Poking around, /bin/bash does not work, /bash does not work, but hostname does and so does whoami. The good news is that whoami is the same user that connects to the tunnel, so no privilege escalation or other scary stuff. – Yuv Jul 09 '15 at 03:10
  • Try just `bash`, `csh`, `tcsh`, `zsh`, or whatever. – Brian Vandenberg Jul 09 '15 at 16:12
  • That's really strange/scary to me that it's running on the remote end. In all of my experiments, `-N` prevents a prompt from showing up and doesn't let you execute anything remotely. – Brian Vandenberg Jul 09 '15 at 16:13
  • Try running `pstree` (whether directly or starting a shell then running it) so you can see who the parent process(es) are. – Brian Vandenberg Jul 09 '15 at 16:15
  • Some other things to try: `-n` should prevent ssh from reading anything from its `stdin`. That will at least prevent it from running anything remotely, but it won't necessarily make your script work correctly. `-T` will prevent pseudo-tty allocation; I doubt that would help, but I thought I'd mention it as something to tinker with. – Brian Vandenberg Jul 09 '15 at 16:23
  • This little project of mine got pushed on ice by serious priorities and I am not sure I can return to it any time soon. Maybe over the year-end holidys, but unlikely. I mark your answer as the most helpful. Even though I have not found the solution yet, it points in the right direction. – Yuv Nov 01 '15 at 16:39
0

-bash: line 1: s3cReTsTr1n9: command not found

I got same error as -bash command not found even though I was just accepting raw_input() / input(). I tried this in both 2.7 and 3.7 version.

I was trying run a client server program on same mac machine. I had two files server.py and client.py. Everytime in the terminal, I first ran the server.py in background and then ran client.py.
Terminal 1: python server.py &
Terminal 2: python client.py
Each time I got the error "-bash: xxxx: command not found". xxxx here is whatever input I gave.

Finally after spending 5 hours on this I stopped running server.py in background.
Terminal 1: python server.py
Terminal 2: python client.py

And viola it worked. raw_input and input did not give me this error again.

I am not sure if this helps. But this is the only post I found on internet which had exactly the same issue as mine. And thought maybe this would help.

ShahK
  • 1
  • 1