summaryrefslogtreecommitdiff
path: root/tar_over_paramiko.py
blob: 080147827b77efbe01c73827bcac180ae95138b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python3

import paramiko, sys, os, io, tarfile, subprocess
from pathlib import Path

if len(sys.argv) != 5:
    print(f"Usage: {sys.argv[0]} USERNAME HOST PORT DIR")
    sys.exit(1)

ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

key_path = os.path.join(Path.home(), '.ssh/id_rsa')
key = paramiko.RSAKey.from_private_key_file(key_path)

ssh.connect(
        hostname=sys.argv[2], 
        username=sys.argv[1],
        port=sys.argv[3],
        pkey=key,
        )

tarlist = 'tarlist.txt'
find_cmd = 'find {} -type f > {}'.format(sys.argv[4], tarlist)

stdin, stdout, stderr = ssh.exec_command('sh')
stdin.write(find_cmd)

stdin.flush()
stdin.channel.shutdown_write()

for l in stdout:
    print('[FIND STDOUT]\t{}'.format(l.strip('\n')))

for l in stderr:
    print('[FIND STDOUT]\t{}'.format(l.strip('\n')))

stdin, stdout, stderr = ssh.exec_command('tar cf - -T {}'.format(tarlist))
stderr_lines = 0
stdout_lines = 0
stdout_type = None

stdin.flush()
stdin.channel.shutdown_write()

untar = subprocess.Popen(
        ["tar", "xf", "-"],
        stdin=subprocess.PIPE,
        stdout=subprocess.DEVNULL,
        )

tar_data = io.BytesIO()
tar_file = open('/tmp/tartest', 'wb')

for l in stdout:
    l_byte = l.encode()

    untar.stdin.write(l_byte)

    tar_data.write(l_byte)
    tar_file.write(l_byte)

    stdout_lines += 1
    stdout_type = type(l)

    print('[TAR{}]\tReceived {} bytes'.format(stdout_lines, len(l_byte)))

for l in stderr:
    print("[STDERR]\t{}".format(l.strip('\n')))
    stderr_lines += 1

tar_file.close()
untar.stdin.close()

tar_data.seek(0)
tar_obj = tarfile.open(fileobj=tar_data, mode='r')

print(f"Received {stderr_lines} stderr line(s)")
print(f"Received {stdout_lines} stdout line(s)")
print(f"Type of stdout line is {stdout_type}")

for tarinfo in tar_obj:
    print(tarinfo)

tar_obj.close()
ssh.close()