]> arthur.barton.de Git - bup.git/blob - lib/bup/ssh.py
643b5089965b4c0aa6116818bcaab3af9377d4d2
[bup.git] / lib / bup / ssh.py
1 """SSH connection.
2 Connect to a remote host via SSH and execute a command on the host.
3 """
4
5 from __future__ import absolute_import, print_function
6 import sys, os, re, subprocess
7
8 from bup import helpers, path
9 from bup.compat import environ
10
11 def connect(rhost, port, subcmd, stderr=None):
12     """Connect to 'rhost' and execute the bup subcommand 'subcmd' on it."""
13     assert not re.search(br'[^\w-]', subcmd)
14     if rhost is None or rhost == b'-':
15         argv = [path.exe(), subcmd]
16     else:
17         buglvl = helpers.atoi(environ.get(b'BUP_DEBUG'))
18         force_tty = helpers.atoi(environ.get(b'BUP_FORCE_TTY'))
19         tty_width = helpers.atoi(environ.get(b'BUP_TTY_WIDTH'))
20         cmd = b"""
21                    sh -c 'BUP_DEBUG=%d BUP_FORCE_TTY=%d BUP_TTY_WIDTH=%d bup %s'
22                """ % (buglvl, force_tty, tty_width, subcmd)
23         argv = [b'ssh']
24         if port:
25             argv.extend((b'-p', port))
26         argv.extend((rhost, b'--', cmd.strip()))
27         #helpers.log('argv is: %r\n' % argv)
28     if sys.version_info[0] < 3:
29         return subprocess.Popen(argv,
30                                 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
31                                 stderr=stderr,
32                                 preexec_fn=lambda: os.setsid())
33     else:
34         return subprocess.Popen(argv,
35                                 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
36                                 stderr=stderr,
37                                 start_new_session=True)