diff --git a/scripts/reclassify_servers_to_network.py b/scripts/reclassify_servers_to_network.py index b33bb8e..ba29679 100644 --- a/scripts/reclassify_servers_to_network.py +++ b/scripts/reclassify_servers_to_network.py @@ -7,8 +7,8 @@ audit history all carry over. Only the extension row is swapped (computers -> networkdevices) and the asset's type is flipped, and the network device is given the 'Server' networkdevicetype. -Identify servers by their computer type name (default 'Server'); pass --type to -match a different one. +Identify servers by a name/hostname prefix (default 'SVR-'), or pass --type to +match an exact computer type instead. Usage (on the target instance, in the app dir): DATABASE_URL=... venv/bin/python scripts/reclassify_servers_to_network.py # dry run @@ -41,9 +41,13 @@ def _get_or_create_networkdevicetype(name): def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--type', default='Server', - help="computer type name that holds the servers (default 'Server')") + parser = argparse.ArgumentParser(description=__doc__) + group = parser.add_mutually_exclusive_group() + group.add_argument('--prefix', default='SVR-', + help="match servers by name/assetnumber/hostname starting " + "with this (default 'SVR-')") + group.add_argument('--type', + help="instead of --prefix, match by an exact computer type name") parser.add_argument('--commit', action='store_true', help='apply the change; without it this is a dry run') args = parser.parse_args() @@ -54,21 +58,30 @@ def main(): if not nd_assettype: sys.exit("No 'network_device' asset type - is the network plugin installed?") - ctype = ComputerType.query.filter_by(computertype=args.type).first() - if not ctype: - sys.exit("No computer type named %r. Pass --type with the exact name." - % args.type) + query = Computer.query.join(Asset) + if args.type: + ctype = ComputerType.query.filter_by(computertype=args.type).first() + if not ctype: + sys.exit("No computer type named %r." % args.type) + query = query.filter(Computer.computertypeid == ctype.computertypeid) + criterion = "computer type %r" % args.type + else: + like = args.prefix + '%' + query = query.filter(db.or_( + Asset.assetnumber.like(like), + Asset.name.like(like), + Computer.hostname.like(like), + )) + criterion = "name/hostname prefix %r" % args.prefix - servers = (Computer.query - .filter(Computer.computertypeid == ctype.computertypeid) - .all()) + servers = query.all() if not servers: - print("No computers under type %r - nothing to do." % args.type) + print("No computers match %s - nothing to do." % criterion) return ndt = _get_or_create_networkdevicetype('Server') - print("%d server(s) under computer type %r -> network_device / type 'Server':" - % (len(servers), args.type)) + print("%d server(s) matching %s -> network_device / type 'Server':" + % (len(servers), criterion)) moved = 0 for computer in servers: