]> arthur.barton.de Git - bup.git/blobdiff - lib/bup/ssh.py
join_bytes: pass the join() args correctly for py3
[bup.git] / lib / bup / ssh.py
index cefa54385307ed290dd55c856c5fb6d50dcf90e0..5602921b2d77e32152fc5a21b594d4ee381973c9 100644 (file)
@@ -1,11 +1,16 @@
-import os, re, subprocess
-from bup import helpers
+"""SSH connection.
+Connect to a remote host via SSH and execute a command on the host.
+"""
 
-def connect(rhost, subcmd):
+from __future__ import absolute_import, print_function
+import sys, os, re, subprocess
+from bup import helpers, path
+
+
+def connect(rhost, port, subcmd, stderr=None):
+    """Connect to 'rhost' and execute the bup subcommand 'subcmd' on it."""
     assert(not re.search(r'[^\w-]', subcmd))
-    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
-    nicedir = os.path.split(os.path.abspath(main_exe))[0]
-    nicedir = re.sub(r':', "_", nicedir)
+    nicedir = re.sub(r':', "_", path.exedir())
     if rhost == '-':
         rhost = None
     if not rhost:
@@ -19,17 +24,31 @@ def connect(rhost, subcmd):
         # allow shellquoting.  So we end up having to double-shellquote
         # stuff here.
         escapedir = re.sub(r'([^\w/])', r'\\\\\\\1', nicedir)
+        buglvl = helpers.atoi(os.environ.get('BUP_DEBUG'))
         force_tty = helpers.atoi(os.environ.get('BUP_FORCE_TTY'))
         cmd = r"""
-                   sh -c PATH=%s:'$PATH BUP_FORCE_TTY=%s bup %s'
-               """ % (escapedir, force_tty, subcmd)
-        argv = ['ssh', rhost, '--', cmd.strip()]
+                   sh -c PATH=%s:'$PATH BUP_DEBUG=%s BUP_FORCE_TTY=%s bup %s'
+               """ % (escapedir, buglvl, force_tty, subcmd)
+        argv = ['ssh']
+        if port:
+            argv.extend(('-p', port))
+        argv.extend((rhost, '--', cmd.strip()))
         #helpers.log('argv is: %r\n' % argv)
-    def setup():
-        # runs in the child process
-        if not rhost:
-            os.environ['PATH'] = ':'.join([nicedir,
-                                           os.environ.get('PATH', '')])
-        os.setsid()
-    return subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
-                            preexec_fn=setup)
+    if rhost:
+        env = os.environ
+    else:
+        envpath = os.environ.get('PATH')
+        env = os.environ.copy()
+        env['PATH'] = nicedir if not envpath else nicedir + ':' + envpath
+    if sys.version_info[0] < 3:
+        return subprocess.Popen(argv,
+                                stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                                stderr=stderr,
+                                env=env,
+                                preexec_fn=lambda: os.setsid())
+    else:
+        return subprocess.Popen(argv,
+                                stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                                stderr=stderr,
+                                env=env,
+                                start_new_session=True)