Add a load of handy ~/bin scripts
This commit is contained in:
76
bin/mypass
Executable file
76
bin/mypass
Executable file
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
import subprocess
|
||||
import yaml
|
||||
|
||||
PASS = 'pass'
|
||||
|
||||
def run(args):
|
||||
return(subprocess.run(
|
||||
args,
|
||||
stdin=sys.stdin,
|
||||
stdout=sys.stdout,
|
||||
stderr=sys.stderr).returncode)
|
||||
|
||||
def get_stdout(args):
|
||||
return(subprocess.run(
|
||||
args,
|
||||
stdout=subprocess.PIPE).stdout)
|
||||
|
||||
def extract_from_dict(d, k, last=None):
|
||||
if '.' in k:
|
||||
k1, k2 = k.split('.', 1)
|
||||
try:
|
||||
d1 = d[k1]
|
||||
return extract_from_dict(d1, k2, last=k1)
|
||||
except KeyError:
|
||||
print("\"{}\" was not found in the data".format(k))
|
||||
sys.exit(3)
|
||||
else:
|
||||
if not isinstance(d, dict):
|
||||
print("element \"{}\" is not a dictionary".format(last))
|
||||
sys.exit(3)
|
||||
try:
|
||||
return d[k]
|
||||
except KeyError:
|
||||
print("\"{}\" was not found in the data".format(k))
|
||||
sys.exit(3)
|
||||
|
||||
|
||||
def cmd_get(*args):
|
||||
if len(args) == 1:
|
||||
print(get_stdout(['pass', 'show', args[0]]).split(b'\n')[0].decode())
|
||||
return 0
|
||||
|
||||
if len(args) != 2:
|
||||
print("what do you want to get?")
|
||||
return 1
|
||||
|
||||
# get the pass output
|
||||
out = get_stdout(['pass', 'show', args[0]])
|
||||
try:
|
||||
data = list(yaml.safe_load_all(out))[-1]
|
||||
except yaml.scanner.ScannerError as e:
|
||||
print("invalid YAML data: {}".format(str(e)))
|
||||
return 2
|
||||
except IndexError:
|
||||
print("invalid YAML data: no YAML document found")
|
||||
return 2
|
||||
|
||||
if not isinstance(data, dict):
|
||||
print("invalid YAML data, not a dict")
|
||||
return 2
|
||||
|
||||
keydata = extract_from_dict(data, args[1])
|
||||
if isinstance(keydata, list) or isinstance(keydata, dict):
|
||||
print(yaml.safe_dump(keydata, default_flow_style=False).strip())
|
||||
else:
|
||||
print(keydata)
|
||||
|
||||
cmds = ['get']
|
||||
|
||||
if len(sys.argv) == 1 or sys.argv[1] not in cmds:
|
||||
sys.exit(run([PASS] + sys.argv[1:]))
|
||||
else:
|
||||
sys.exit(globals()['cmd_' + sys.argv[1]](*sys.argv[2:]))
|
||||
Reference in New Issue
Block a user