eive-obsw/scripts/q7s-cp.py

80 lines
2.2 KiB
Python
Raw Normal View History

2021-07-26 01:21:37 +02:00
#!/usr/bin/env python3
import argparse
import os
2022-01-27 17:30:28 +01:00
import sys
2021-07-26 01:21:37 +02:00
def main():
args = handle_args()
cmd = build_cmd(args)
# Run the command
2022-01-27 17:30:28 +01:00
print(f"Running command: {cmd}")
2021-07-28 18:56:36 +02:00
result = os.system(cmd)
if result != 0:
2022-01-27 17:30:28 +01:00
print("")
print("Removing problematic SSH key and trying again..")
remove_ssh_key_cmd = (
'ssh-keygen -f "${HOME}/.ssh/known_hosts" -R "[localhost]:1535"'
)
2021-07-28 18:56:36 +02:00
os.system(remove_ssh_key_cmd)
2022-01-27 17:30:28 +01:00
print(f'Running command "{cmd}"')
2021-07-28 18:56:36 +02:00
result = os.system(cmd)
2021-07-26 01:21:37 +02:00
def handle_args():
2022-01-27 17:30:28 +01:00
help_string = (
"This script copies files to the Q7S as long as port forwarding is active.\n"
)
help_string += (
"You can set up port forwarding with "
2021-07-26 01:21:37 +02:00
'"ssh -L 1535:192.168.133.10:22 <eive-flatsat-ip>" -t /bin/bash'
)
2022-01-27 17:30:28 +01:00
parser = argparse.ArgumentParser(description=help_string)
2021-07-26 01:21:37 +02:00
# Optional arguments
2022-01-27 17:30:28 +01:00
parser.add_argument(
"-r", "--recursive", dest="recursive", default=False, action="store_true"
)
parser.add_argument(
"-t",
"--target",
help="Target destination. If files are copied to Q7S, will be /tmp by default. "
"If files are copied back to host, will be current directory by default",
default="",
)
parser.add_argument("-P", "--port", help="Target port", default=1535)
parser.add_argument(
"-i",
"--invert",
default=False,
action="store_true",
help="Copy from Q7S to host instead. Always copies to current directory.",
)
2021-07-26 01:21:37 +02:00
# Positional argument(s)
2022-01-27 17:30:28 +01:00
parser.add_argument(
"source", help="Source files to copy or target files to copy back to host"
)
2021-07-26 01:21:37 +02:00
return parser.parse_args()
def build_cmd(args):
# Build run command
2022-01-27 17:30:28 +01:00
cmd = "scp "
2021-07-26 01:21:37 +02:00
if args.recursive:
2022-01-27 17:30:28 +01:00
cmd += "-r "
target = args.target
if args.invert and target == "":
target = "."
elif target == "":
target = f"/tmp"
if args.invert:
cmd += f"-P {args.port} root@localhost:{args.source} {target}"
else:
cmd += f"-P {args.port} {args.source} root@localhost:{target}"
2021-07-26 01:21:37 +02:00
if args.target:
cmd += args.target
return cmd
if __name__ == "__main__":
main()