def exec_command(command, cwd=None):
    r'''
    Helper to exec locally (subprocess) or remotely (paramiko)
    '''

    rc = None
    stdout = stderr = None
    if ssh_conn is None:
        ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', '')}
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=ld_library_path, cwd=cwd)
        stdout, stderr = p.communicate()
        rc = p.returncode
    else:
        # environment= requires paramiko >= 2.1 (fails with 2.0.2)
        final_command = command if cwd is None else 'cd %s && %s %s' % (cwd, 'LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH', command)
        ssh_stdin, ssh_stdout, ssh_stderr = ssh_conn.exec_command(final_command)
        stdout = ''.join(ssh_stdout.readlines())
        stderr = ''.join(ssh_stderr.readlines())
        rc = ssh_stdout.channel.recv_exit_status()

    return rc, stdout, stderr
r'''
    Helper to exec locally (subprocess) or remotely (paramiko)