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
|
import argparse
import contextlib
import json
import os
import pathlib
import subprocess
import tempfile
import urllib.request
import zipfile
BW = pathlib.Path.home() / ".local" / "bin" / "bw"
class Bitwarden():
@contextlib.contextmanager
def login(self, server, email):
if subprocess.run([BW, "config", "server"], check=True, text=True, stdout=subprocess.PIPE).stdout.strip() != server:
subprocess.run([BW, "config", "server", server], check=True)
status = self.status()["status"]
if status == "unauthenticated":
command = ["login", email]
elif status == "locked":
command = ["unlock"]
else:
assert False, f"unexpected status {status}"
command = subprocess.run([BW] + command, check=True, stdout=subprocess.PIPE, encoding="UTF8")
export_line = command.stdout.splitlines()[3]
session = export_line.split('"')[1]
os.environ["BW_SESSION"] = session
try:
yield
subprocess.run([BW, "logout"], check=True)
finally:
del os.environ["BW_SESSION"]
def sync(self):
subprocess.run([BW, "sync"], check=True)
def status(self):
return json.loads(subprocess.run([BW, "status"], check=True, stdout=subprocess.PIPE).stdout)
def get_item(self, uuid):
return json.loads(subprocess.run([BW, "get", "item", uuid], check=True, stdout=subprocess.PIPE).stdout)
def get_attachment(self, attachment_id, item_id, destination):
subprocess.run([BW, "get", "attachment", attachment_id, "--itemid", item_id, "--output", destination], check=True)
def get_item(server, email, uuid):
b = Bitwarden()
with b.login(server, email):
b.sync()
return b.get_item(uuid)
@contextlib.contextmanager
def default():
b = Bitwarden()
with b.login("https://vaultwarden.pdp7.net", "alex@corcoles.net"):
b.sync()
yield b
def install_cli(version):
with tempfile.TemporaryDirectory() as tempdir:
tempdir = pathlib.Path(tempdir)
zip = tempdir / "zip"
with urllib.request.urlopen(f"https://github.com/bitwarden/clients/releases/download/cli-v{version}/bw-oss-linux-{version}.zip") as urlopen:
zip.write_bytes(urlopen.read())
with zipfile.ZipFile(zip) as zip:
with zip.open("bw") as bw:
BW.parent.mkdir(exist_ok=True, parents=True)
if BW.exists():
BW.unlink()
BW.write_bytes(bw.read())
BW.chmod(0o555)
def install_cli_main():
parser = argparse.ArgumentParser()
parser.add_argument("version")
args = parser.parse_args()
install_cli(args.version)
|